Compare commits

..
Author SHA1 Message Date
Gabriel De Andrade aadd5f0327 fix(server): tombstone deletion of missing threads
- Make thread deletion idempotent for stale client entries
- Add coverage for emitting a deletion tombstone when the thread is missing
2026-07-30 21:49:09 -04:00
Julius MarmingeandClaude Fable 5 df78cda8bf fix(contracts): decode growing config unions forward-compatibly (#5055)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 01:11:46 +02:00
Alex 605c2bb734 fix(mobile): show the correct build channel in Android's Threads page header (#4861) 2026-07-30 22:30:46 +00:00
Aditya Vardhan Sharma cb11a71d63 fix(mobile): accept Android clipboard images in composer (#4836) 2026-07-31 00:20:33 +02:00
Simon DobaandClaude Opus 5 41124c7260 fix(desktop): link release notes from the update downloaded toast (#4771)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-07-31 00:19:34 +02:00
Max Anderson b0b275227b chore: add mobile issue template area (#4895) 2026-07-31 00:19:00 +02:00
Alex cb293fe790 fix(mobile): restore iOS Threads branding (#4862) 2026-07-31 00:17:47 +02:00
Simone 1d694dcbd8 fix(mobile): default bare IP pairing to HTTP (#4990) 2026-07-30 22:17:38 +00:00
Arham AminandClaude Opus 4.8 32407df9c5 fix(shared): lenient JSON parser deletes commas inside string values (#5025)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-30 22:16:22 +00:00
Elaine Lyons 162e774294 fix(mobile): remove unnecessary photo library permission (#4929) 2026-07-31 00:15:38 +02:00
Arham AminandClaude Opus 4.8 063ed7120a feat(shared): support shorthand (major-only) versions in the semver helpers (#5027)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-30 22:13:46 +00:00
Utkarsh Patil 34b15a9ace perf(server): cache default branch name and origin existence across status refreshes (#5008) 2026-07-31 00:08:59 +02:00
Julius MarmingeandClaude Fable 5 fbecb7365e fix(desktop): bump Clerk Electron SDK to 0.0.24 and register t3code:// scheme on Linux (#5015)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 00:06:49 +02:00
Julius MarmingeandClaude Fable 5 4029b858ea fix(ci): drop sparse-checkout from EAS workflows
actions/checkout implements sparse-checkout with --filter=blob:none, so
the runner repo is a partial clone missing the .repos/ blobs. eas-cli
archives the project via `git clone --depth 1 file://<workspace>`,
which upload-pack cannot serve from a partial clone and exits 128
(#4802 broke both EAS build workflows this way).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 13:15:03 -07:00
maria 5b2577f6a9 style(web): make scroll-to-end pill translucent (#5036) 2026-07-30 20:08:05 +00:00
Julius MarmingeandClaude Fable 5 bc142f84a2 chore(mobile): bump app version to 1.0.1
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 13:07:10 -07:00
Theo Browne e4829603ff perf(ci): cut stale runs and redundant setup (#4802) 2026-07-30 14:25:31 -04:00
Gabriel De Andrade 1d77cec991 fix: cache project favicons across web and mobile (#4767) 2026-07-30 14:13:50 -04:00
maria 4ba4871af7 fix(web): fill fast mode icon (#5004) 2026-07-30 12:42:21 -04:00
Wout Stiens edc503a7a8 fix(server): restore PR detection without HOME (#4985) 2026-07-30 12:17:44 -04:00
Gabriel De Andrade 323dc321a2 fix(mobile): support pre-Liquid-Glass iOS bottom toolbar (#4984) 2026-07-30 12:01:14 -04:00
Julius Marmingeandcodex 6154b46cb8 Check for mobile app updates on launch (#4958)
Co-authored-by: codex <[email protected]>
2026-07-30 16:57:00 +02:00
abc409c2d4 Add project file picker (⌘P) and project content search (⇧⌘F) (#4855)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-30 16:39:15 +02:00
Theo BrowneandClaude Fable 5 1877237c7a fix(connect): reboots no longer strand the relay link, 403s now say why (#4988)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 07:31:53 -07:00
Theo BrowneandClaude Fable 5 e0513d2983 fix(web): server updates no longer look like warnings (#4992)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 07:30:24 -07:00
Theo BrowneandClaude Fable 5 9dd425b223 docs: split user and maintainer docs, fix 100+ stale claims (#4807)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 06:10:47 -07:00
Theo BrowneandClaude Fable 5 50871eb5de fix: marketing site Vercel builds no longer die after ~100 deploys (#4975)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 05:31:42 -07:00
Theo Browne 4b71a2ae2f feat(search): find threads by conversation content (#4959) 2026-07-30 05:30:11 -07:00
Theo Browne 197d348711 fix(web): show server update progress through reconnect (#4903) 2026-07-30 04:45:04 -07:00
Theo Browne 5c9358acaa feat(web): regenerate thread titles from sidebar (#4810) 2026-07-30 04:39:38 -07:00
Theo BrowneandClaude Fable 5 cbe8052020 feat(web): pasting a huge screenshot now compresses it instead of erroring (#4967)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 04:35:06 -07:00
Theo Browne 69a18ce912 perf(mobile): reconnect environments immediately on resume (#4878) 2026-07-30 04:10:26 -07:00
Theo BrowneandClaude Fable 5 f0c6ba9946 fix(web): keep worktree default when switching a draft's machine (#4964)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 03:48:33 -07:00
Theo BrowneandClaude Fable 5 90f3913a81 fix(mobile): stop long iOS threads from jumping while scrolling up (#4867)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 03:05:25 -07:00
Theo Browne 2652fee49b fix(mobile): support dragged images in the composer (#4953) 2026-07-30 03:01:56 -07:00
Theo BrowneandClaude Fable 5 2f466ffc9c docs: seed worktrees with a copy of real userdata instead of banning it (#4949)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 09:29:27 +00:00
Theo Browne 9146ed2f49 fix(web): show Codex fast mode as a bolt (#4947) 2026-07-30 02:15:48 -07:00
Theo BrowneandClaude Fable 5 f0f16e4f6e perf(mobile): sends respond instantly, thread opens stop freezing (#4882)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 01:54:59 -07:00
Theo Browne 00da6b57a4 fix(mobile): stop shared content errors in Personal Team builds (#4943) 2026-07-30 01:48:16 -07:00
Theo BrowneandClaude Fable 5 6ab2f16809 fix(connect): suggest a serve command that matches how you ran connect (#4897)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 01:46:10 -07:00
Wout Stiens 6efcf3e10c fix(web): align remote server update action (#4731) 2026-07-30 01:30:23 -04:00
Theo BrowneandClaude Fable 5 748203ea19 docs: link iOS and Android app store downloads (#4902)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-29 21:54:08 -07:00
Max Katz b125b76351 fix(composer): hide default Codex service tier (#4784) 2026-07-29 22:35:53 -04:00
Wout Stiens 758decaa56 fix(clients): disable add project while disconnected (#4834) 2026-07-29 22:14:06 -04:00
Theo BrowneandClaude Fable 5 2d9066e089 fix(web): settle button now works on hover, not just right-click (#4905)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-29 19:01:24 -07:00
Jono Kemball 35a684000d fix(web): restore sidebar v2 thread actions and terminal icon (#4712) 2026-07-29 21:48:01 -04:00
Gabriel De Andrade 9e3e9bb4f0 fix(mobile): reduce thread feed scroll jank (#4874) 2026-07-29 21:21:16 -04:00
t3-code[bot] a8e05cbb92 chore(release): prepare v0.0.31 2026-07-29 20:56:43 +00:00
e6987965f6 fix(web): remember the rendered-markdown choice across threads (#4853)
Co-authored-by: Simon Doba <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
2026-07-29 18:01:03 +00:00
Jake Leventhal fc28abf24b Fix editable file focus and live syntax highlighting (#3979) 2026-07-29 19:06:39 +02:00
ohbentos 85a8986870 fix(git): disable external diff for review diff previews (#4854) 2026-07-29 16:27:00 +00:00
Utkarsh Patil faea70aeba perf(server): merge separate staged/unstaged numstat calls into single diff HEAD --numstat (#4843) 2026-07-29 18:24:11 +02:00
Wout Stiens d19039aeef fix(server): detect repositories after initialization (#4848) 2026-07-29 11:48:57 -04:00
Julius Marmingeandcodex 49c0d96edf Reduce idle work and disk churn with native resource diagnostics (#2679)
Co-authored-by: codex <[email protected]>
2026-07-29 14:42:01 +02:00
Julius Marminge 3137c2b162 Preserve the thread shell while detail loads (#4830) 2026-07-29 13:54:17 +02:00
Julius Marminge c3e8fb67d7 Update model version from claude-opus-4-8 to claude-opus-5 (#4832) 2026-07-29 11:39:24 +00:00
wukko 72b960fa39 build(desktop): reduce installed app size by ~300MB (#4824) 2026-07-29 12:39:23 +02:00
Julius Marminge 08e4932f04 Simplify files panel header (#4828) 2026-07-29 10:36:54 +00:00
1b4830ff06 fix(desktop): restore T3 Connect sign-in (#4809)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-29 10:59:12 +02:00
t3-code[bot] 694f8d1c6e chore(release): prepare v0.0.30 2026-07-29 01:12:24 +00:00
Julius Marminge 1b61ce1112 Fix Connect sign-in settings label (#4806) 2026-07-29 01:03:04 +00:00
Julius Marminge 60af905e70 Remove Connect waitlist and add GA announcement tooling (#4691) 2026-07-29 02:29:01 +02:00
Julius Marmingeandcodex 8650f05f95 refactor(server): use native HTTP compression streams (#4798)
Co-authored-by: codex <[email protected]>
2026-07-29 00:03:39 +00:00
Julius Marmingeandcodex 8fe8f9a9c1 fix(mobile): defer filesystem navigation (#4799)
Co-authored-by: codex <[email protected]>
2026-07-29 01:46:59 +02:00
Julius Marmingeandcodex 936593c258 refactor(client): share filesystem browse navigation (#4797)
Co-authored-by: codex <[email protected]>
2026-07-29 01:24:29 +02:00
Theo Browne 2919147c80 fix(release): skip scripts during Vercel installs (#4796) 2026-07-28 16:16:14 -07:00
Julius Marmingeandcodex 1ba3d01bc6 fix(web): defer command palette filesystem navigation (#2109)
Co-authored-by: codex <[email protected]>
2026-07-29 00:58:38 +02:00
Theo BrowneandClaude Fable 5 5fcdefd057 perf(server): trim stale context-window rows and drop dead replay RPC (#4791)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-28 15:50:43 -07:00
Julius Marmingeandcodex 38a6e3ce65 Fix Git ref refresh resource storms (#4727)
Co-authored-by: codex <[email protected]>
2026-07-29 00:42:50 +02:00
Theo BrowneandClaude Fable 5 f2d2fb2f24 fix(web): stashed prompts now survive switching providers (#4787)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-28 15:22:22 -07:00
Theo Browne 8829e2f9b9 perf(server): gzip large thread snapshots (#4788) 2026-07-28 15:17:30 -07:00
Julius Marminge 2deea7abb0 Prevent sidebar row labels from truncating (#4789) 2026-07-28 21:58:21 +00:00
Theo Browne b64ae880e0 docs: overhaul agent guidance (#4782) 2026-07-28 14:10:26 -07:00
Theo BrowneandClaude Fable 5 887dd6e455 perf(server): negotiate permessage-deflate on the websocket (#4705)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-28 06:03:03 -07:00
Julius MarmingeandClaude f1a68ac9b0 Fix Android showcase capture and rebuild v2 queued rows (#4730)
Co-authored-by: Claude <[email protected]>
2026-07-28 14:09:34 +02:00
Julius MarmingeandClaude Fable 5 55dd01612e Link inline code file paths in chat markdown (#4726)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-28 13:37:36 +02:00
jan 3c50a64885 fix(web): prevent diff panel scroll jumping (#4724) 2026-07-28 12:29:18 +02:00
jan 9ccfd9dfef fix(desktop): allow updater-controlled relaunch (#4721) 2026-07-28 11:45:02 +02:00
Max Katz 4f584da0f8 feat(web): add appearance settings category (#4715) 2026-07-28 11:28:29 +02:00
Max Katz 362f127922 feat(web): add maria's sidebar header artwork toggle (#4652) 2026-07-28 11:17:45 +02:00
Theo Browne 9cf9fc9c5c Settle merged PR threads immediately (#4704) 2026-07-28 11:15:14 +02:00
Julius Marmingeandcodex e00781a661 Fix relay credential lookup for unlinked environments (#4692)
Co-authored-by: codex <[email protected]>
2026-07-28 11:12:07 +02:00
Julius Marminge d25b15737a Fix mobile showcase workflow without Clerk (#4718) 2026-07-28 11:08:43 +02:00
Julius Marminge b0c4992c79 Make mobile Thread List v2 the default (#4717) 2026-07-28 10:48:31 +02:00
Max Katz dd5ea32488 fix(web): 33 web UI fixes (#4700) 2026-07-27 21:43:49 -07:00
Theo BrowneandClaude Opus 5 c13a021e43 feat: default sidebar v2 on for nightly and dev builds (#4491)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-07-27 21:41:08 -07:00
Theo BrowneandClaude Fable 5 476d69cd1d fix(mobile): threads load snapped to bottom on iOS (#4689)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-27 19:24:44 -07:00
Julius Marminge a148e08197 Add OTA update checks to mobile settings (#4686) 2026-07-28 00:55:00 +02:00
t3-code[bot] 831eb66fee chore(release): prepare v0.0.29 2026-07-27 22:37:18 +00:00
494 changed files with 43031 additions and 7878 deletions

No files matched your search

+1 -1
View File
@@ -66,7 +66,7 @@ Use these client origins:
- Android Emulator: `http://10.0.2.2:<server-port>`
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
Enter the complete `http://` origin to make the test transport explicit. Bare IP addresses default to HTTP, while bare hostnames default to HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
## Start or reuse Metro safely
+1
View File
@@ -30,6 +30,7 @@ body:
- apps/web
- apps/server
- apps/desktop
- apps/mobile
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
@@ -30,6 +30,7 @@ body:
- apps/web
- apps/server
- apps/desktop
- apps/mobile
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
+45 -3
View File
@@ -6,6 +6,10 @@ on:
branches:
- main
concurrency:
group: ci-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
check:
name: Check
@@ -14,6 +18,11 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -22,6 +31,11 @@ jobs:
cache: true
run-install: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
@@ -31,6 +45,9 @@ jobs:
- name: Typecheck
run: vpr typecheck
- name: Check resource monitor formatting
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
- name: Build desktop pipeline
run: vp run build:desktop
@@ -47,6 +64,11 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -55,26 +77,39 @@ jobs:
cache: true
run-install: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
run: vp run test
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
runs-on: blacksmith-6vcpu-macos-26
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
@@ -89,13 +124,20 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+8 -1
View File
@@ -38,13 +38,20 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=t3code-relay...
- name: Deploy production relay stage
id: deploy
+14 -3
View File
@@ -2,13 +2,18 @@ name: Mobile EAS Preview
on:
pull_request:
types: [opened, reopened, synchronize, labeled, unlabeled]
types: [opened, reopened, synchronize, labeled]
jobs:
preview:
name: EAS Preview
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
if: |
contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') &&
(github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment')
runs-on: blacksmith-8vcpu-ubuntu-2404
concurrency:
group: mobile-eas-preview-${{ github.event.pull_request.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
@@ -34,6 +39,10 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
@@ -41,7 +50,9 @@ jobs:
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=@t3tools/mobile...
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
+7 -1
View File
@@ -57,6 +57,10 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
@@ -64,7 +68,9 @@ jobs:
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=@t3tools/mobile...
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
@@ -37,13 +37,21 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- name: Expose pnpm
run: |
@@ -77,13 +85,21 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
with:
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- name: Expose pnpm
run: |
+99 -4
View File
@@ -38,6 +38,10 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- id: check
name: Compare HEAD to last nightly tag
@@ -84,6 +88,10 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -192,6 +200,10 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -269,14 +281,19 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=t3...
- name: Build node-pty linux-x64 prebuild
shell: bash
@@ -326,21 +343,29 @@ jobs:
platform: mac
target: dmg
arch: arm64
rust_target: aarch64-apple-darwin
resource_key: darwin-arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
rust_target: x86_64-apple-darwin
resource_key: darwin-x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
rust_target: x86_64-unknown-linux-gnu
resource_key: linux-x64
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
rust_target: x86_64-pc-windows-msvc
resource_key: win32-x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
@@ -351,14 +376,26 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
run-install: |
args:
- --filter=@t3tools/desktop...
- --filter=t3...
- --filter=@t3tools/scripts...
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.rust_target }}
- name: Download relay client tracing config
uses: actions/download-artifact@v8
@@ -598,6 +635,19 @@ jobs:
# done
# fi
- name: Collect resource monitor
shell: bash
run: |
set -euo pipefail
binary_name="t3-resource-monitor"
if [[ "${{ matrix.platform }}" == "win" ]]; then
binary_name="${binary_name}.exe"
fi
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
mkdir -p "$target_dir"
cp "$source_path" "$target_dir/$binary_name"
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -605,6 +655,13 @@ jobs:
path: release-publish/*
if-no-files-found: error
- name: Upload resource monitor
uses: actions/upload-artifact@v7
with:
name: resource-monitor-${{ matrix.resource_key }}
path: resource-monitor-publish/${{ matrix.resource_key }}/*
if-no-files-found: error
publish_cli:
name: Publish CLI to npm
needs: [preflight, relay_public_config, build]
@@ -624,6 +681,10 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -659,6 +720,24 @@ jobs:
- name: Build CLI package
run: vp run --filter t3 build
- name: Download resource monitors
uses: actions/download-artifact@v8
with:
pattern: resource-monitor-*
path: ${{ runner.temp }}/resource-monitors
- name: Bundle resource monitors into CLI package
shell: bash
run: |
set -euo pipefail
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
resource_key="${artifact_dir##*/resource-monitor-}"
target_dir="apps/server/dist/resource-monitor/${resource_key}"
mkdir -p "$target_dir"
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
done
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
@@ -681,6 +760,10 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -802,6 +885,10 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
@@ -916,6 +1003,10 @@ jobs:
fetch-depth: 0
token: ${{ steps.app_token.outputs.token }}
persist-credentials: true
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- id: app_bot
name: Resolve GitHub App bot identity
@@ -986,6 +1077,10 @@ jobs:
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
+1
View File
@@ -30,6 +30,7 @@ dist-electron/
.showcase/
apps/mobile/.showcase/
artifacts/app-store/screenshots/
native/**/target/
node_modules/
.alchemy/
*.log
@@ -1,6 +1,6 @@
---
title: Effect Service Conventions
model: claude-opus-4-8
model: claude-opus-5
effort: high
input: full_diff
tools:
+136 -40
View File
@@ -1,52 +1,148 @@
# AGENTS.md
# T3 Code
## Task Completion Requirements
T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs (Codex, Claude Code, Cursor, Grok, OpenCode) and serves web, desktop, and mobile clients.
- Keep local verification focused on the files and packages changed. Run the smallest relevant test set; do not run the full workspace test suite as a routine completion step.
- Use `vp test run <test-files>` for focused built-in Vite+ tests. Use `vp run test` only when the affected package specifically requires its `test` script.
- Backend changes must include and run focused tests for the changed behavior.
- Run targeted formatting, lint, and type checks for the affected scope when available.
- Do not run repo-wide `vp check`, `vp run typecheck`, `vp run test`, or equivalent full-suite commands locally unless the user explicitly requests them. CI is responsible for the full verification suite.
- After frontend feature development or any user-visible frontend behavior change, the primary agent must run one integrated verification pass for each affected client surface after integrating the work:
- Web: use the `test-t3-app` skill. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
- Mobile: use the `test-t3-mobile` skill. Connect one representative iOS Simulator or Android Emulator available on the host to one isolated environment and verify the affected flow. On compatible macOS hosts, prefer iOS for cross-platform changes and stream it through serve-sim in the T3 Code in-app browser or another available agent browser; use Android when it is the affected or viable platform.
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor.
## Dev Servers
## What makes T3 Code special?
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
We have over 100,000 users who love T3 Code. It's important we maintain the things they love as we continue to iterate on the product. Here's a brief list of the things we can never compromise on.
## Package Roles
### 1. Open at the core
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
- `packages/shared`: Shared runtime utilities consumed by both server and client applications. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
- `packages/client-runtime`: Shared runtime package for sharing client code across web and mobile.
T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks. We work in the open, and should strive to stay that way.
## Reference Repos
### 2. Performance without compromise
- Open-source Codex repo: https://github.com/openai/codex
Lots of apps have gotten bogged down with bad tech decisions and "slop". We have not, and we're proud of the performance of T3 Code. We regularly audit for performance regressions, often caused by sending too much data over websockets, css animations causing gpu spikes, lists being hard to render, and more. Make sure all changes are considerate of performance impact.
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
### 3. Remote ready
## Vendored Repositories
The architecture of T3 Code's websocket layer (npx t3) enables a lot of awesome remote features. These have become core to the product. Whether users are connecting directly over their local network, using Tailscale, or leaning in fully with T3 Connect (our tunnel solution, also in this repo), we need to make sure new features are properly supported.
This project vendors external repositories under `.repos/` as read-only reference material for coding
agents.
### 4. Multi-surface
- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
- Do not edit files under `.repos/` unless explicitly asked.
- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
`.repos/` matches the installed dependency version.
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
examples of idiomatic usage, tests, module structure, and API design.
- When writing relay infrastructure code with Alchemy, inspect `.repos/alchemy-effect/` for examples of
idiomatic usage, tests, module structure, and API design.
T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**.
**Web** is kind of two surfaces, as we have the public facing "app.t3.codes" as well as locally hosting the web app through the `npx t3` command. Both need to be supported by all new features where reasonable.
**Desktop** is the main surface most users install first. It's a full Electron app that bundles the server runner as well. The desktop app can also be used as the host server, allowing remote connections from app.t3.codes or the mobile app.
**Mobile** is a React Native app for both iOS and Android, available on the App Store and Google Play. The mobile app allows for connecting to any T3 Code server to control work remotely.
## A note from Theo
I like ambitious ideas, simple systems, and software that feels obvious. Do not preserve complexity just because it already exists. Do not introduce machinery because it looks architecturally impressive. Understand the real constraint, then fight for the smallest model that makes the correct behavior unsurprising.
Channel both "measure twice, cut once" and "yagni". Fight scope creep. Try to honor the dev's intent in both a minimal and realistic fashion.
The rest of this document is meant to help you navigate the codebase and make changes effectively. Think of these instructions less as "hard rules", more as "good defaults". The developer's preferences should be able to override anything here.
Of note: Most T3 Code contributions will come from T3 Code itself, often controlled remotely. This means you should be careful about accessing data, killing dev servers, and other things that may damage the T3 Code instance that the contributor is using.
## A small glossary
We need to be on the same page with terminology. When communicating, use this language:
- **you** means the agent reading this file and changing T3 Code.
- **we, us, and maintainers** mean Theo, Julius and the people building T3 Code. These are who you are talking to now.
- **user** means the person using T3 Code to direct coding agents.
- **agent** means the coding agent a user runs inside T3 Code. Depending on context, that may also include you.
- **provider** means the agent runtime or harness T3 Code talks to, such as Codex, Claude, Cursor, or OpenCode.
- **client** means the web, desktop, or mobile UI.
- **environment** means one running T3 server and the machine, filesystem, provider credentials, and state it owns.
- **project** means an environment-local workspace record rooted at a directory.
- **thread** means the durable conversation and work history for a project.
- **turn** means one user-to-agent cycle, including follow-up work such as checkpointing.
- **T3 home** means the base data directory. Runtime state normally lives below its userdata directory.
## The three ways to hurt yourself
1. **Killing by pattern.** Never `pkill -f`, `pgrep | kill`, or `kill` a PID you found by matching a name, path, or worktree string. Your own agent process has this worktree's path in its argv, and this machine runs several other dev servers at once. Kill only a PID you captured at spawn, or the owner of your port from `ss -H -ltnp` after confirming `/proc/<pid>/cwd` is your worktree.
2. **Writing to the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Reading it and copying from it are fine, and a good way to get real test data (see Test data). Never start a server against it, never open it read-write, never clean it up.
3. **Baking in origins.** Never set `VITE_HTTP_URL` or `VITE_WS_URL` for dev. Dev is single-origin and Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known`. Setting them bakes localhost into the bundle and silently breaks every remote browser.
## Hit every surface
The most common defect in this repo is a change that works on the path you tested and is missing everywhere else. Before calling frontend work done, walk this list and say which entries applied:
- **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature.
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime`
- **Providers.** Codex, Claude, Cursor, Grok, and OpenCode each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
- **Docs.** `docs/` splits by audience. Behavior changes that a user would notice belong in `docs/user/` (shipped-product voice, no repo tooling or source paths); architecture and contributor changes in `docs/internals/`; runbooks in `docs/operations/`; new vocabulary in `docs/internals/glossary.md`.
## Dev servers
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
- `--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.
- Stop what you started, by the PID you tracked. See rule 1.
## Test data
An empty database is a bad test. Seed your worktree's `.t3` with a copy of real data instead of pointing at live state:
- Copy from `~/.t3/userdata` (the developer's real data, the most realistic test set) or `~/.t3/dev`. Worktree state lives at `<worktree>/.t3/userdata`.
- Snapshot the database with `VACUUM INTO`, which is safe even while a server has the source open and yields one consistent file:
```bash
mkdir -p .t3/userdata
rm -f .t3/userdata/state.sqlite* # VACUUM INTO refuses to overwrite
bun -e "new (require('bun:sqlite').Database)(process.env.HOME + '/.t3/userdata/state.sqlite', { readonly: true }).run(\"VACUUM INTO '.t3/userdata/state.sqlite'\")"
```
A plain `cp` is only safe when no server has the source open, and must bring the `-wal` and `-shm` siblings along. A live file copy is a corrupt copy.
- Bring `secrets` and `settings.json` only if the flow under test needs them.
- Copy in, never symlink. Data flows one way: into your sandbox, never back out.
## Verifying
- Smallest proof that the change works. `vp test run <files>` for the tests you touched, targeted lint and typecheck for the scope you changed.
- **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite.
- Backend behavior changes ship with focused tests for that behavior.
- The server is event-sourced and its async flows emit typed receipts. Wait on receipts and worker drains, never on sleeps or polling. A test that needs a timeout to pass is wrong.
- Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
## Pull requests
- Never make a PR unless the developer explicitly asks you to do so.
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
- **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.
## How it works
Clients send typed WebSocket requests. The server turns them into _commands_, a pure _decider_ turns commands into persisted _events_, and a _projector_ derives the read model the UI renders. Provider CLIs run as subprocesses; per-provider _adapters_ translate their native protocols into orchestration events. Side effects run in queue-backed _reactors_ that emit _receipts_ when milestones land. Each turn ends with a _checkpoint_, a hidden git ref, so the app can diff and restore.
Full glossary with file links: `docs/internals/glossary.md`
## Where code lives
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code.
- `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site.
- `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic.
- `packages/shared` - shared runtime utils, subpath exports, no barrel.
- `packages/client-runtime` - client code shared by web and mobile.
- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency.
## Taste
- Complexity belongs at the adapter boundary. Orchestration stays pure, UI stays dumb.
- Inferred types over annotations. `any` is the enemy.
- Comments describe how a thing is used, and move when the code moves. To be used mostly to describe functions, not to annotate every line of behavior.
- Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays.
- If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it.
## Additional tips
- Don't verify with browsers or computer use unless the user explicitly agrees or requests it.
- Security is important, but should not be over-indexed on, especially for dev mode/maintainer-only features.
+30 -15
View File
@@ -1,24 +1,36 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app ([iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824), [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code)), [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, and OpenCode. If they're set up on your computer, T3 Code can control them.
## "Wait, what are you selling me?"
Nothing. We built T3 Code because we wanted the best possible development experience with agents. We were inspired by existing solutions like the Codex desktop app, Conductor, Claude Desktop and Cursor Glass, but none met our bar.
We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork and build the editor that you want.
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
> Install and authenticate at least one provider before use:
> T3 Code currently supports Codex, Claude, Cursor, Grok Build and OpenCode. Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `agent login`
> - Grok Build: install [Grok Build CLI](https://x.ai/cli) and run `grok login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Run without installing
### Try it out (install-free)
The easiest way to test T3 Code is to run the server in your terminal (requires Node.js 22.16+, 23.11+, or 24.10+):
```bash
npx t3@latest
```
This will launch T3 Code's backend on your machine as well as the local web app to control your agents.
Tip: Use `npx t3@latest --help` for the full CLI reference.
### Desktop app
@@ -47,19 +59,22 @@ yay -S t3code-bin
We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be.
## Documentation
- [Getting started](./docs/getting-started/quick-start.md)
- [Remote access](./docs/user/remote-access.md)
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
- [Architecture overview](./docs/architecture/overview.md)
- [Provider guides](./docs/providers/codex.md)
- [Operations](./docs/operations/ci.md)
- [Reference](./docs/reference/encyclopedia.md)
Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
- Linux: [run T3 Code as a background service](./docs/user/background-service.md)
Building from source? Start at [docs/internals/overview.md](./docs/internals/overview.md).
## If you REALLY want to contribute still.... read this first
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.28",
"version": "0.0.31",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -54,7 +54,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
calls.setAboutPanelOptions.push(options);
}),
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
@@ -63,6 +63,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
calls.setDockIcon.push(iconPath);
}),
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
+27 -19
View File
@@ -45,6 +45,27 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
export const resolveUserDataPath = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
export const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
@@ -90,24 +111,11 @@ export const make = Effect.gen(function* () {
return commitHash;
});
const resolveUserDataPath = Effect.gen(function* () {
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
const userDataPath = resolveUserDataPath.pipe(
Effect.provide(
yield* Effect.context<DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem>(),
),
);
const configure = Effect.gen(function* () {
const commitHash = yield* resolveAboutCommitHash;
@@ -136,7 +144,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
return DesktopAppIdentity.of({
resolveUserDataPath,
resolveUserDataPath: userDataPath,
configure,
});
});
+90 -5
View File
@@ -22,17 +22,38 @@ vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true) => {
const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
appDataDirectory: "/tmp/app-data",
userDataDirName: isDevelopment ? "t3code-dev" : "t3code",
legacyUserDataDirName: isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)",
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const electronApp = {
setPath: (name: string, value: string) =>
Effect.sync(() => {
events.push(`setPath:${name}:${value}`);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
return DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
Layer.succeed(ElectronApp.ElectronApp, electronApp),
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
),
),
);
};
@@ -55,11 +76,15 @@ describe("DesktopClerk", () => {
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
const events: string[] = [];
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
createClerkBridgeMock.mockImplementation(() => {
events.push("createClerkBridge");
return { cleanup, isPrimaryInstance: true };
});
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
@@ -71,6 +96,10 @@ describe("DesktopClerk", () => {
],
]);
assert.equal(cleanup.mock.calls.length, 1);
// The bridge acquires Electron's single-instance lock at creation, and
// the lock both lives in and creates the userData directory — so the
// real path must be set before the bridge exists.
assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
@@ -124,11 +153,67 @@ describe("DesktopClerk", () => {
});
});
it.effect("registers the second-instance handler in the primary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.isSuccess(exit));
assert.equal(quit.mock.calls.length, 0);
assert.deepEqual(registeredEvents, ["second-instance"]);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
it.effect("quits and interrupts startup in a secondary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.hasInterrupts(exit));
assert.equal(quit.mock.calls.length, 1);
assert.deepEqual(registeredEvents, []);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
+19 -2
View File
@@ -11,6 +11,7 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
@@ -84,7 +85,18 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
const electronApp = yield* ElectronApp.ElectronApp;
// Electron scopes the single-instance lock to the userData directory and
// creates that directory when the lock is acquired. The SDK bridge takes
// the lock at creation, so userData must already point at the real
// directory here — under the default productName-derived path, acquiring
// the lock would create "T3 Code (Alpha)" and make the legacy-install
// detection in resolveUserDataPath match on fresh installs.
const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
const bridge = yield* Effect.acquireRelease(
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
@@ -113,7 +125,12 @@ export const make = Effect.gen(function* () {
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
// The SDK bridge holds Electron's single-instance lock (acquired at
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
// forwarded to the running app. In a secondary instance the bridge has
// already begun quitting the app; app.quit() is asynchronous, so stop
// bootstrap here before whenReady can fire.
if (!bridge.isPrimaryInstance) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
@@ -0,0 +1,123 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import type * as Electron from "electron";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
describe("DesktopLifecycle", () => {
for (const platform of ["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>) {
it.effect(`lets the updater's quit event proceed on ${platform}`, () => {
const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
appListeners.set("before-quit-for-update", listener);
}),
() =>
Effect.sync(() => {
appListeners.delete("before-quit-for-update");
}),
).pipe(Effect.asVoid),
on: (eventName, listener) =>
Effect.acquireRelease(
Effect.sync(() => {
appListeners.set(
eventName,
listener as unknown as (...args: readonly unknown[]) => void,
);
}),
() =>
Effect.sync(() => {
appListeners.delete(eventName);
}),
).pipe(Effect.asVoid),
} satisfies ElectronApp.ElectronApp["Service"]);
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
shouldUseDarkColors: Effect.succeed(false),
setSource: () => Effect.void,
onUpdated: () => Effect.void,
});
const desktopWindowLayer = Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected window creation"),
ensureMain: Effect.die("unexpected window creation"),
revealOrCreateMain: Effect.die("unexpected window creation"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.void,
syncAppearance: Effect.void,
});
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
platform,
isDevelopment: false,
} as DesktopEnvironment.DesktopEnvironment["Service"]);
const layer = DesktopLifecycle.layer.pipe(
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(electronThemeLayer),
Layer.provideMerge(desktopWindowLayer),
Layer.provideMerge(environmentLayer),
Layer.provideMerge(DesktopShutdown.layer),
Layer.provideMerge(DesktopState.layer),
);
return Effect.scoped(
Effect.gen(function* () {
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
yield* lifecycle.register;
appListeners.get("before-quit-for-update")?.();
let prevented = false;
const event = {
preventDefault: () => {
prevented = true;
},
} as Electron.Event;
appListeners.get("before-quit")?.(event);
assert.isFalse(
prevented,
"cancelling this event prevents the updater from completing its relaunch",
);
const state = yield* DesktopState.DesktopState;
assert.isTrue(yield* Ref.get(state.quitting));
}),
).pipe(Effect.provide(layer));
});
}
});
+13 -1
View File
@@ -176,16 +176,28 @@ export const make = DesktopLifecycle.of({
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
let updaterQuitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.onBeforeQuitForUpdate(() => {
// Electron's updater owns the remaining quit/install/relaunch sequence.
// Cancelling the following app "before-quit" event breaks that sequence,
// most visibly on macOS where the native updater performs the relaunch.
updaterQuitAllowed = true;
void runEffect(
logLifecycleInfo("allowing updater-controlled quit").pipe(
Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => quitAllowed || updaterQuitAllowed,
() => {
quitAllowed = true;
},
+180 -14
View File
@@ -49,20 +49,41 @@ const environmentInput = (baseDir: string) =>
runningUnderArm64Translation: false,
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const makeEnvironmentLayer = (baseDir: string) =>
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
}),
),
),
);
describe("DesktopObservability", () => {
it("advances a retained output offset instead of repeatedly copying a full head chunk", () => {
const maxBufferedBytes = 1024 * 1024;
const initial = DesktopObservability.appendBoundedOutputChunk(
{
runId: "test-run",
startDetails: "pid=123",
chunks: [],
byteLength: 0,
},
"stderr",
new Uint8Array(maxBufferedBytes),
);
const initialBackingBuffer = initial.chunks[0]?.chunk.buffer;
const next = DesktopObservability.appendBoundedOutputChunk(initial, "stderr", Uint8Array.of(1));
assert.equal(next.chunks[0]?.chunk.buffer, initialBackingBuffer);
assert.equal(next.chunks[0]?.offset, 1);
assert.equal(next.byteLength, maxBufferedBytes);
});
it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -112,26 +133,34 @@ describe("DesktopObservability", () => {
),
);
it.effect("persists backend child output as structured JSON records in development", () =>
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-log-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir);
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
const tracePath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.writeSessionBoundary({
phase: "START",
yield* outputLog.beginSession({
details: "pid=123 port=3773 cwd=/repo",
});
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
assert.isFalse(yield* fileSystem.exists(logPath));
yield* outputLog.persistFailure({ details: "code=1" });
yield* outputLog.beginSession({ details: "pid=456" });
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n"));
yield* outputLog.discardSession;
}).pipe(
Effect.annotateLogs({ runId: "test-run" }),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
@@ -139,16 +168,18 @@ describe("DesktopObservability", () => {
const log = yield* fileSystem.readFileString(logPath);
const lines = log.trimEnd().split("\n");
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
assert.equal(boundary.message, "backend child process session start");
assert.equal(boundary.level, "INFO");
assert.equal(boundary.annotations.component, "desktop-backend-child");
assert.equal(boundary.annotations.runId, "test-run");
assert.equal(boundary.annotations.instanceId, "primary");
assert.equal(boundary.annotations.phase, "START");
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
assert.equal(lines.length, 3);
assert.equal(start.message, "backend child process failure output start");
assert.equal(start.level, "ERROR");
assert.equal(start.annotations.component, "desktop-backend-child");
assert.equal(start.annotations.runId, "test-run");
assert.equal(start.annotations.instanceId, "primary");
assert.equal(start.annotations.phase, "START");
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
assert.equal(output.message, "backend child process output");
assert.equal(output.level, "INFO");
@@ -157,6 +188,141 @@ describe("DesktopObservability", () => {
assert.equal(output.annotations.instanceId, "primary");
assert.equal(output.annotations.stream, "stdout");
assert.equal(output.annotations.text, "hello server\n");
assert.equal(end.message, "backend child process failure output end");
assert.equal(end.level, "ERROR");
assert.equal(end.annotations.instanceId, "primary");
assert.equal(end.annotations.phase, "END");
assert.equal(end.annotations.details, "code=1");
const traceRecords = (yield* fileSystem.readFileString(tracePath))
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => decodeTraceRecordLine(line));
assert.isFalse(
traceRecords.some(
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
),
);
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("keeps buffering output after a non-terminal failure snapshot", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-snapshot-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.beginSession({ details: "pid=123" });
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.annotateLogs({ runId: "test-run" }),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
);
const records = yield* Effect.forEach(
(yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
(line) => decodeDesktopBackendChildLogRecord(line),
);
assert.equal(
records.some((record) => record.annotations.text === "after timeout\n"),
true,
);
assert.equal(records.at(-1)?.annotations.details, "code=1");
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("retains only the last mebibyte of backend child output", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-bound-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
const maxBufferedBytes = 1024 * 1024;
const discardedPrefixBytes = 128;
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
output.fill("x".charCodeAt(0));
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
yield* Effect.scoped(
Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.beginSession({ details: "pid=123" });
yield* outputLog.writeOutputChunk("stderr", output);
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
const text = record.annotations.text;
assert.equal(typeof text, "string");
if (typeof text !== "string") {
return;
}
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
assert.isFalse(text.includes("y"));
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("bounds the number of retained backend child output chunks", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-chunks-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.scoped(
Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.beginSession({ details: "pid=123" });
for (let index = 0; index < 300; index += 1) {
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
}
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
assert.equal(lines.length, 258);
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
+167 -42
View File
@@ -24,7 +24,9 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
export interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
@@ -32,14 +34,14 @@ export interface RotatingLogFileWriter {
}
export interface DesktopBackendOutputLogShape {
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
readonly persistFailureSnapshot: (input: { readonly details: string }) => Effect.Effect<void>;
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
readonly discardSession: Effect.Effect<void>;
}
// Factory for per-instance backend output logs. `forInstance(id)` returns
@@ -127,10 +129,80 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
writeSessionBoundary: () => Effect.void,
beginSession: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailureSnapshot: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
};
interface BufferedBackendOutputChunk {
readonly streamName: "stdout" | "stderr";
readonly chunk: Uint8Array;
readonly offset: number;
}
interface BackendOutputSession {
readonly runId: string;
readonly startDetails: string;
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
readonly byteLength: number;
}
export function appendBoundedOutputChunk(
session: BackendOutputSession,
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): BackendOutputSession {
if (chunk.byteLength === 0) {
return session;
}
const retainedChunk =
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
: chunk.slice();
const chunks = [...session.chunks, { streamName, chunk: retainedChunk, offset: 0 }];
let byteLength = session.byteLength + retainedChunk.byteLength;
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
let firstRetainedIndex = 0;
while (overflow > 0) {
const first = chunks[firstRetainedIndex];
if (!first) break;
const retainedByteLength = first.chunk.byteLength - first.offset;
if (retainedByteLength <= overflow) {
overflow -= retainedByteLength;
byteLength -= retainedByteLength;
firstRetainedIndex += 1;
continue;
}
chunks[firstRetainedIndex] = {
...first,
offset: first.offset + overflow,
};
byteLength -= overflow;
overflow = 0;
}
const excessChunks = Math.max(
0,
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
);
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
const chunk = chunks[index];
byteLength -= chunk ? chunk.chunk.byteLength - chunk.offset : 0;
}
firstRetainedIndex += excessChunks;
return {
...session,
chunks: chunks.slice(firstRetainedIndex),
byteLength,
};
}
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
@@ -345,47 +417,93 @@ const makeBackendOutputLogShape = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
sink: Option.Option<RotatingLogFileWriter>,
): DesktopBackendOutputLogShape =>
): Effect.Effect<DesktopBackendOutputLogShape> =>
Option.match(sink, {
onNone: () => DesktopBackendOutputLogNoop,
onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
Effect.gen(function* () {
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
function* (session: BackendOutputSession, details: string) {
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
message: "backend child process failure output start",
level: "ERROR",
annotations: {
component: "desktop-backend-child",
runId,
runId: session.runId,
instanceId: id,
phase,
phase: "START",
details: session.startDetails,
},
});
for (const output of session.chunks) {
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: output.streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId: session.runId,
instanceId: id,
stream: output.streamName,
text: textDecoder.decode(output.chunk.subarray(output.offset)),
},
});
}
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process failure output end",
level: "ERROR",
annotations: {
component: "desktop-backend-child",
runId: session.runId,
instanceId: id,
phase: "END",
details: sanitizeLogValue(details),
},
});
},
),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
);
return {
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
details,
}) {
const runId = yield* currentDesktopRunId;
yield* Ref.set(
sessionRef,
Option.some({
runId,
startDetails: sanitizeLogValue(details),
chunks: [],
byteLength: 0,
}),
);
}),
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
instanceId: id,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLogShape,
yield* Ref.update(
sessionRef,
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
);
}),
persistFailureSnapshot: Effect.fn(
"desktop.observability.backendOutput.persistFailureSnapshot",
)(function* ({ details }) {
const session = yield* Ref.get(sessionRef);
if (Option.isSome(session)) {
yield* writeFailure(session.value, details);
}
}),
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
function* ({ details }) {
const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
if (Option.isNone(session)) return;
yield* writeFailure(session.value, details);
},
),
discardSession: Ref.set(sessionRef, Option.none()),
} satisfies DesktopBackendOutputLogShape;
}),
});
const backendOutputLogFactoryLayer = Layer.effect(
@@ -412,10 +530,9 @@ const backendOutputLogFactoryLayer = Layer.effect(
const cacheKey = backendLogFilePathForInstance(environment, id);
const cached = cache.get(cacheKey);
if (cached !== undefined) {
return Effect.succeed([
makeBackendOutputLogShape(environment, id, cached),
cache,
] as const);
return makeBackendOutputLogShape(environment, id, cached).pipe(
Effect.map((outputLog) => [outputLog, cache] as const),
);
}
return makeBackendOutputSinkForInstance(environment, id).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
@@ -424,11 +541,19 @@ const backendOutputLogFactoryLayer = Layer.effect(
Effect.map((sink) => {
const next = new Map(cache);
next.set(cacheKey, sink);
return [
makeBackendOutputLogShape(environment, id, sink),
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
] as const;
return { sink, next };
}),
Effect.flatMap(({ sink, next }) =>
makeBackendOutputLogShape(environment, id, sink).pipe(
Effect.map(
(outputLog) =>
[
outputLog,
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
] as const,
),
),
),
);
});
@@ -52,6 +52,7 @@ function makeEnvironmentLayer(
baseDir: string,
options?: {
readonly appPath?: string;
readonly dirname?: string;
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
readonly platform?: NodeJS.Platform;
@@ -59,7 +60,7 @@ function makeEnvironmentLayer(
},
) {
return DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
dirname: options?.dirname ?? "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: options?.platform ?? "darwin",
processArch: "x64",
@@ -464,6 +465,8 @@ describe("DesktopBackendConfiguration", () => {
// both wslhost-forwarded localhost and the distro's eth0 IP.
assert.equal(config.bootstrap.host, "0.0.0.0");
assert.equal(config.bootstrap.tailscaleServeEnabled, false);
assert.notProperty(config.bootstrap, "desktopTelemetryFd");
assert.notProperty(config.bootstrap, "resourceMonitorPath");
// httpBaseUrl uses the resolved distro IP from the test stub,
// not localhost — the renderer reaches the backend directly to
// avoid relying on wslhost forwarding.
@@ -713,6 +716,97 @@ describe("DesktopBackendConfiguration", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const resourcesPath = `${baseDir}/resources`;
const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
yield* fileSystem.makeDirectory(
`${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
{ recursive: true },
);
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
recursive: true,
});
yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
yield* fileSystem.writeFileString(monitorPath, "binary");
yield* fileSystem.chmod(monitorPath, 0o755);
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: `${resourcesPath}/app.asar`,
dirname,
isPackaged: true,
resourcesPath,
}),
),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("prefers the release resource monitor when both development builds exist", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const dirname = path.join(baseDir, "apps/desktop/src");
const releaseMonitorPath = path.join(
baseDir,
"native/resource-monitor/target/release/t3-resource-monitor",
);
const debugMonitorPath = path.join(
baseDir,
"native/resource-monitor/target/debug/t3-resource-monitor",
);
yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
yield* fileSystem.writeFileString(releaseMonitorPath, "release");
yield* fileSystem.writeFileString(debugMonitorPath, "debug");
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
dirname,
devServerUrl: "http://127.0.0.1:5733",
isPackaged: false,
}),
),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
withHarness(
Effect.gen(function* () {
@@ -141,6 +141,44 @@ const logBackendObservabilitySettingsReadFailure = (
);
};
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
}
const resolveResourceMonitorPath = Effect.fn(
"desktop.backendConfiguration.resolveResourceMonitorPath",
)(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const binaryName = resourceMonitorBinaryName(environment.platform);
const candidates = environment.isDevelopment
? [
environment.path.join(
environment.rootDir,
"native/resource-monitor/target/release",
binaryName,
),
environment.path.join(
environment.rootDir,
"native/resource-monitor/target/debug",
binaryName,
),
]
: environment.isPackaged
? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
: environment.resolveResourcePathCandidates(
environment.path.join("resource-monitor", binaryName),
);
for (const candidate of candidates) {
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -326,7 +364,9 @@ const buildObservabilityFragment = (observabilitySettings: BackendObservabilityS
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
function* (
input: SharedBootstrapInput,
input: SharedBootstrapInput & {
readonly resourceMonitorPath: Option.Option<string>;
},
): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
@@ -345,6 +385,12 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
desktopBootstrapToken: input.bootstrapToken,
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
tailscaleServePort: backendExposure.tailscaleServePort,
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
...Option.match(input.resourceMonitorPath, {
onNone: () => ({}),
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
}),
...buildObservabilityFragment(input.observabilitySettings),
};
@@ -411,6 +457,10 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
// inert.
tailscaleServeEnabled: false,
tailscaleServePort: 443,
// The packaged sidecar is a Windows executable and cannot run inside the
// Linux WSL backend. Keep the field absent instead of passing an unusable
// `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
// See docs/architecture/resource-telemetry.md.
...buildObservabilityFragment(input.observabilitySettings),
};
@@ -621,7 +671,11 @@ export const make = Effect.gen(function* () {
const buildWindowsPrimaryConfig = Effect.gen(function* () {
const shared = yield* sharedInputs;
return yield* resolvePrimaryStartConfig(shared).pipe(
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
@@ -1,14 +1,17 @@
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
DesktopTelemetryControlMessage,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -21,10 +24,15 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
const encodeDesktopTelemetryControl = Schema.encodeSync(
Schema.fromJsonString(DesktopTelemetryControlMessage),
);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
@@ -41,6 +49,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
desktopBootstrapToken: "token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
},
bootstrapDelivery: "fd3",
extendEnv: true,
@@ -52,14 +62,16 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
const configWithObservability: DesktopBackendBootstrapValue = {
...baseConfig.bootstrap,
tailscaleServeEnabled: true,
desktopTelemetryFd: 4,
otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
};
function makeProcess(options?: {
readonly stdout?: Stream.Stream<Uint8Array>;
readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
@@ -71,7 +83,7 @@ function makeProcess(options?: {
kill: options?.kill ?? (() => Effect.void),
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
unref: Effect.succeed(Effect.void),
});
}
@@ -112,7 +124,14 @@ interface MakeInstanceInput {
failure: DesktopBackendManager.PreflightFailure,
) => Effect.Effect<boolean>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
readonly configResolve?: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
readonly desktopTelemetryPublisher?: Partial<
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
>;
}
// Helper that constructs a primary backend instance using the factory
@@ -122,8 +141,11 @@ interface MakeInstanceInput {
// to drive the instance's lifecycle.
function makeTestInstance(input: MakeInstanceInput) {
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
writeSessionBoundary: () => Effect.void,
beginSession: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailureSnapshot: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
...input.backendOutputLog,
};
const servicesLayer = Layer.mergeAll(
@@ -135,6 +157,16 @@ function makeTestInstance(input: MakeInstanceInput) {
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () => Effect.succeed(stubLog),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
latest: Effect.succeed(Option.none()),
changes: Stream.empty,
encoded: input.desktopTelemetryStream ?? Stream.empty,
handleControl: () => Effect.void,
handleControlForSource: (_sourceId, message) =>
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
removeControlSource: () => Effect.void,
...input.desktopTelemetryPublisher,
}),
);
const instance = DesktopBackendManager.makeBackendInstance({
@@ -150,11 +182,12 @@ function makeTestInstance(input: MakeInstanceInput) {
}
describe("DesktopBackendManager", () => {
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
Effect.scoped(
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
let bootstrapJson = "";
let telemetryJson = "";
let readyCount = 0;
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
@@ -169,6 +202,10 @@ describe("DesktopBackendManager", () => {
if (fd3?.type === "input" && fd3.stream) {
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
}
const fd4 = command.options.additionalFds?.fd4;
if (fd4?.type === "input" && fd4.stream) {
telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
}
}
return makeProcess({
@@ -184,12 +221,14 @@ describe("DesktopBackendManager", () => {
bootstrap: configWithObservability,
},
spawnerLayer,
desktopTelemetryStream: Stream.encodeText(
Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
),
onReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
},
});
@@ -210,16 +249,400 @@ describe("DesktopBackendManager", () => {
assert.equal(spawnedCommand.options.stderr, "pipe");
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
assert.isDefined(spawnedCommand.options.forceKillAfter);
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
assert.equal(
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
2_000,
);
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
assert.equal(
telemetryJson,
'{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
);
}),
),
);
it.effect("preserves the readiness timeout cause and process context", () =>
Effect.gen(function* () {
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
const layer = Layer.merge(
TestClock.layer(),
httpClientLayer((request) =>
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
),
);
yield* Effect.gen(function* () {
const readiness = yield* DesktopBackendManager.waitForHttpReady({
executablePath: baseConfig.executablePath,
entryPath: baseConfig.entryPath,
cwd: baseConfig.cwd,
httpBaseUrl: baseConfig.httpBaseUrl,
timeout: Duration.millis(50),
}).pipe(Effect.flip, Effect.forkChild);
const request = yield* Deferred.await(requested);
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(readiness);
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
assert.equal(error.timeoutMs, 50);
assert.isDefined(error.cause);
assert.equal(
error.message,
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
);
}).pipe(Effect.provide(layer));
}),
);
it.effect("reports bootstrap encoding failures with stable process context", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
bootstrap: {
...baseConfig.bootstrap,
port: 0,
},
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessBootstrapEncodeError") {
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.isDefined(error.cause);
assert.equal(
error.message,
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves spawn failures without deriving their message from the cause", () =>
Effect.gen(function* () {
const spawnCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcessSpawner",
method: "spawn",
pathOrDescriptor: baseConfig.executablePath,
description: "low-level detail that must not become the public message",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessSpawnError") {
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, spawnCause);
assert.equal(
error.message,
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
);
assert.notInclude(error.message, spawnCause.message);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves exit-status failures without copying their detail into the message", () =>
Effect.gen(function* () {
const exitCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "exitCode",
description: "exit-status-secret-sentinel",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Effect.fail(exitCause),
}),
),
),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessExitStatusError") {
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
}
assert.equal(error.pid, 123);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, exitCause);
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
assert.notInclude(error.message, "exit-status-secret-sentinel");
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("reports output stream failures with process and stream context", () =>
Effect.gen(function* () {
const outputCause = PlatformError.systemError({
_tag: "BadResource",
module: "ChildProcess",
method: "stdout",
description: "output-stream-secret-sentinel",
});
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fail(outputCause),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputReadError") {
return assert.fail(`Expected output read error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.strictEqual(error.cause, outputCause);
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
assert.notInclude(error.message, "output-stream-secret-sentinel");
}),
);
it.effect("reports output handler failures separately from stream read failures", () =>
Effect.gen(function* () {
const chunk = new TextEncoder().encode("backend output");
const nextChunk = new TextEncoder().encode("still draining");
const outputCause = new Error("output-handler-secret-sentinel");
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const drained = yield* Deferred.make<void>();
let outputCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.make(chunk, nextChunk),
exitCode: Deferred.await(drained).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onOutput: () => {
outputCount += 1;
return outputCount === 1
? Effect.fail(outputCause)
: Deferred.succeed(drained, void 0).pipe(Effect.asVoid);
},
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputHandlingError") {
return assert.fail(`Expected output handling error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.equal(error.chunkByteLength, chunk.byteLength);
assert.strictEqual(error.cause, outputCause);
assert.equal(
error.message,
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
);
assert.notInclude(error.message, "output-handler-secret-sentinel");
assert.equal(outputCount, 2);
}),
);
it.effect("reports child exit before waiting for trailing output to drain", () =>
Effect.scoped(
Effect.gen(function* () {
const exitObserved = yield* Deferred.make<void>();
const finishOutputDrain = yield* Deferred.make<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fromEffect(
Deferred.await(finishOutputDrain).pipe(
Effect.as(new TextEncoder().encode("trailing output\n")),
),
),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
}),
),
),
);
const runFiber = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
}).pipe(
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
Effect.forkChild,
);
yield* Deferred.await(exitObserved);
assert.isUndefined(runFiber.pollUnsafe());
yield* Deferred.succeed(finishOutputDrain, void 0);
assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
}),
),
);
it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
Effect.scoped(
Effect.gen(function* () {
const handled = yield* Deferred.make<boolean>();
const controlMessage = encodeDesktopTelemetryControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
getOutputFd: (fd) =>
fd === 5
? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
: Stream.empty,
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
desktopTelemetryPublisher: {
handleControl: (message) =>
message.type === "setDiagnosticsDemand"
? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
: Effect.void,
},
});
yield* instance.start;
assert.isTrue(yield* Deferred.await(handled));
}),
),
);
it.effect("drains trailing child output before persisting an unexpected exit", () =>
Effect.scoped(
Effect.gen(function* () {
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
const outputDrainStarted = yield* Deferred.make<void>();
const outputChunks = yield* Ref.make<Array<string>>([]);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fromEffect(
Deferred.succeed(outputDrainStarted, void 0).pipe(
Effect.andThen(Effect.sleep(Duration.seconds(1))),
Effect.as(new TextEncoder().encode("trailing output\n")),
),
),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
}),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
backendOutputLog: {
writeOutputChunk: (_streamName, chunk) =>
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
persistFailure: () =>
Ref.get(outputChunks).pipe(
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
Effect.asVoid,
),
},
});
yield* instance.start;
yield* Deferred.await(outputDrainStarted);
yield* TestClock.adjust(Duration.seconds(1));
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -256,8 +679,7 @@ describe("DesktopBackendManager", () => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
},
});
@@ -285,9 +707,15 @@ describe("DesktopBackendManager", () => {
let startCount = 0;
let closedCount = 0;
const closed = yield* Deferred.make<void>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const ready = yield* Deferred.make<void>();
const backendReadyFlag = yield* Ref.make(false);
let shutdownCount = 0;
let persistedFailureCount = 0;
let discardedSessionCount = 0;
let removedTelemetrySources = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
@@ -296,9 +724,16 @@ describe("DesktopBackendManager", () => {
const scope = yield* Scope.Scope;
startCount += 1;
yield* Queue.offer(startedPids, 123);
const close = Effect.sync(() => {
closedCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
const close = Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(
Effect.sync(() => {
closedCount += 1;
}),
),
Effect.andThen(Deferred.succeed(closed, void 0)),
Effect.asVoid,
);
yield* Scope.addFinalizer(scope, close);
@@ -316,7 +751,28 @@ describe("DesktopBackendManager", () => {
Effect.andThen(Deferred.succeed(ready, void 0)),
Effect.asVoid,
),
onShutdown: Ref.set(backendReadyFlag, false),
onShutdown: Ref.set(backendReadyFlag, false).pipe(
Effect.andThen(
Effect.sync(() => {
shutdownCount += 1;
}),
),
),
backendOutputLog: {
persistFailure: () =>
Effect.sync(() => {
persistedFailureCount += 1;
}),
discardSession: Effect.sync(() => {
discardedSessionCount += 1;
}),
},
desktopTelemetryPublisher: {
removeControlSource: () =>
Effect.sync(() => {
removedTelemetrySources += 1;
}),
},
});
assert.isTrue(Option.isNone(yield* instance.currentConfig));
@@ -330,12 +786,21 @@ describe("DesktopBackendManager", () => {
assert.equal(runningSnapshot.ready, true);
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
yield* instance.stop();
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
assert.isFalse(yield* Ref.get(backendReadyFlag));
assert.equal(shutdownCount, 1);
yield* Deferred.succeed(finishTeardown, undefined);
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
assert.equal(startCount, 1);
assert.equal(closedCount, 1);
assert.equal(persistedFailureCount, 0);
assert.equal(discardedSessionCount, 1);
assert.equal(removedTelemetrySources, 1);
const stoppedSnapshot = yield* instance.snapshot;
assert.isFalse(yield* Ref.get(backendReadyFlag));
assert.equal(shutdownCount, 1);
assert.equal(stoppedSnapshot.desiredRunning, false);
assert.equal(stoppedSnapshot.ready, false);
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
@@ -343,6 +808,213 @@ describe("DesktopBackendManager", () => {
),
);
it.effect("restarts when start is requested during stop teardown", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const closed = yield* Deferred.make<void>();
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(Deferred.succeed(closed, undefined)),
Effect.asVoid,
),
);
} else {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
);
}
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
yield* instance.start;
assert.equal((yield* instance.snapshot).desiredRunning, true);
yield* Deferred.succeed(finishTeardown, undefined);
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
const restarted = yield* instance.snapshot;
assert.equal(restarted.desiredRunning, true);
assert.deepEqual(restarted.activePid, Option.some(123));
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("retries config resolution after a start request during stop teardown", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
const configAttempts = yield* Ref.make(0);
let startCount = 0;
const configFailure = PlatformError.systemError({
_tag: "Unknown",
module: "DesktopBackendManager",
method: "configResolve",
description: "transient configuration failure",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const closed = yield* Deferred.make<void>();
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(Deferred.succeed(closed, undefined)),
Effect.asVoid,
),
);
} else {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
);
}
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const configResolve = Ref.updateAndGet(configAttempts, (attempt) => attempt + 1).pipe(
Effect.flatMap((attempt) =>
attempt === 2 ? Effect.fail(configFailure) : Effect.succeed(baseConfig),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
configResolve,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
yield* instance.start;
yield* Deferred.succeed(finishTeardown, undefined);
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
const pendingRestart = yield* instance.snapshot;
assert.equal(pendingRestart.desiredRunning, true);
assert.equal(pendingRestart.restartScheduled, true);
yield* TestClock.adjust(Duration.seconds(2));
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
assert.equal(yield* Ref.get(configAttempts), 3);
assert.equal((yield* instance.snapshot).desiredRunning, true);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("keeps a timed-out run active until its process exits", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const teardownStarted = yield* Deferred.make<void>();
const finishTeardown = yield* Deferred.make<void>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
const closed = yield* Deferred.make<void>();
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(teardownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishTeardown)),
Effect.andThen(Deferred.succeed(closed, undefined)),
Effect.asVoid,
),
);
} else {
yield* Scope.addFinalizer(
scope,
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
);
}
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
const stopFiber = yield* instance
.stop({ timeout: Duration.millis(100) })
.pipe(Effect.forkChild);
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
yield* instance.start;
yield* TestClock.adjust(Duration.millis(100));
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
assert.equal(startCount, 1);
const timedOut = yield* instance.snapshot;
assert.equal(timedOut.desiredRunning, true);
assert.deepEqual(timedOut.activePid, Option.some(123));
yield* Deferred.succeed(finishTeardown, undefined);
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("does not notify shutdown before the first start has prior state", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -383,6 +1055,7 @@ describe("DesktopBackendManager", () => {
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const failures = yield* Queue.unbounded<string>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
@@ -402,11 +1075,15 @@ describe("DesktopBackendManager", () => {
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
backendOutputLog: {
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
},
});
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
yield* TestClock.adjust(Duration.millis(499));
assert.equal(yield* Queue.size(starts), 0);
@@ -657,6 +1334,13 @@ describe("DesktopBackendManager", () => {
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
let restartScheduled = false;
while (!restartScheduled) {
restartScheduled = (yield* instance.snapshot).restartScheduled;
if (!restartScheduled) {
yield* Effect.yieldNow;
}
}
yield* instance.start;
assert.equal(yield* Queue.take(starts), 2);
+473 -151
View File
@@ -33,7 +33,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
@@ -46,10 +45,13 @@ import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
PRIMARY_LOCAL_ENVIRONMENT_ID,
DesktopTelemetryControlMessage,
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
} from "@t3tools/contracts";
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
const INITIAL_RESTART_DELAY = Duration.millis(500);
const MAX_RESTART_DELAY = Duration.seconds(10);
@@ -62,7 +64,10 @@ const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
const { logWarning: logBackendProcessWarning } =
DesktopObservability.makeComponentLogger("desktop-backend-process");
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
@@ -70,13 +75,17 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
export interface DesktopBackendStartConfig {
export interface BackendProcessContext {
readonly executablePath: string;
readonly args: ReadonlyArray<string>;
readonly entryPath: string;
readonly cwd: string;
readonly httpBaseUrl: URL;
}
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
export interface DesktopBackendStartConfig extends BackendProcessContext {
readonly args: ReadonlyArray<string>;
readonly env: Record<string, string | undefined>;
// When true the spawner merges the desktop process.env on top of `env`;
// when false `env` is passed verbatim. WSL mode opts out so a leaking
@@ -106,55 +115,122 @@ export interface PreflightFailure {
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
url: Schema.instanceOf(URL),
},
) {
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
const backendProcessContextSchema = {
executablePath: Schema.String,
entryPath: Schema.String,
cwd: Schema.String,
httpBaseUrl: Schema.URL,
};
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
{
entryPath: Schema.String,
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message() {
override get message(): string {
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
}
}
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
...backendProcessContextSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
executablePath: Schema.String,
...backendProcessContextSchema,
cause: Schema.Defect(),
},
) {
override get message() {
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
override get message(): string {
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
}
}
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export const BackendProcessError = Schema.Union([
BackendProcessBootstrapEncodeError,
BackendProcessSpawnError,
BackendProcessExitStatusError,
]);
export type BackendProcessError = typeof BackendProcessError.Type;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
readonly onDesktopTelemetryControl?: (
message: DesktopTelemetryControlMessageValue,
) => Effect.Effect<void>;
readonly readinessTimeout?: Duration.Duration;
readonly outputDrainTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onExitObserved?: () => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void>;
) => Effect.Effect<void, Error>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -225,6 +301,8 @@ interface ActiveBackendRun {
readonly scope: Scope.Closeable;
readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
readonly pid: Option.Option<number>;
readonly exitObserved: boolean;
readonly stopRequested: boolean;
}
interface BackendManagerState {
@@ -266,76 +344,130 @@ const calculateRestartDelay = (attempt: number): Duration.Duration =>
const closeRun = (
run: ActiveBackendRun,
parentScope: Scope.Scope,
options?: { readonly timeout?: Duration.Duration },
): Effect.Effect<void> => {
): Effect.Effect<boolean> => {
const waitForFiber = Option.match(run.fiber, {
onNone: () => Effect.void,
onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
});
const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
const timeout = options?.timeout;
return (
options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
).pipe(Effect.ignore);
if (!timeout) {
return close.pipe(Effect.as(true));
}
return Effect.forkIn(close, parentScope).pipe(
Effect.flatMap((closeFiber) =>
Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)),
),
);
};
const waitForHttpReady = (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
export const waitForHttpReady = (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
return waitForHttpReadyShared({
baseUrl: baseUrl.href,
baseUrl: options.httpBaseUrl.href,
path: BACKEND_READINESS_PATH,
timeoutMs: Duration.toMillis(timeout),
timeoutMs: Duration.toMillis(options.timeout),
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
makeError: ({ cause }) =>
new BackendReadinessTimeoutError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
readinessUrl,
timeoutMs: Duration.toMillis(options.timeout),
cause,
}),
});
};
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
onOutput: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
Stream.mapError(
(cause) =>
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
Effect.catchTag("BackendProcessOutputHandlingError", onOutputFailure),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
}),
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
Schema.fromJsonString(DesktopTelemetryControlMessage),
);
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError(
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
(cause) =>
new BackendProcessBootstrapEncodeError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
);
const onOutput = options.onOutput ?? (() => Effect.void);
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
if (options.bootstrapDelivery === "fd3") {
additionalFds.fd3 = {
type: "input",
stream: bootstrapStream,
};
if (options.bootstrap.desktopTelemetryFd !== undefined) {
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
type: "input",
stream: options.desktopTelemetryStream,
};
}
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
type: "output",
};
}
}
const command = ChildProcess.make(options.executablePath, options.args, {
cwd: options.cwd,
env: options.env,
@@ -350,34 +482,131 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
// wsl.exe drops additional file descriptors when forwarding to the Linux
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
// (`--bootstrap-fd 0`) instead.
...(options.bootstrapDelivery === "fd3"
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
: {}),
...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
});
const handle = yield* spawner
.spawn(command)
.pipe(
Effect.mapError(
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
),
);
const handle = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
);
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
if (
options.bootstrap.desktopTelemetryControlFd !== undefined &&
options.onDesktopTelemetryControl !== undefined
) {
const controlFd = options.bootstrap.desktopTelemetryControlFd;
const handleControl = options.onDesktopTelemetryControl;
yield* handle.getOutputFd(controlFd).pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.filter((line) => line.trim().length > 0),
Stream.runForEach((line) =>
decodeDesktopTelemetryControlLine(line).pipe(
Effect.flatMap(handleControl),
Effect.catchCause((cause) =>
logBackendProcessWarning("ignored invalid desktop telemetry control message", {
fd: controlFd,
cause: Cause.pretty(cause),
}),
),
),
),
Effect.catchCause((cause) =>
logBackendProcessWarning("desktop telemetry control stream stopped", {
fd: controlFd,
cause: Cause.pretty(cause),
}),
),
Effect.ensuring(
handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
}),
),
Effect.forkScoped,
);
}
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
if (options.captureOutput) {
const outputContext = {
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
outputFibers.push(
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped),
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped),
);
}
yield* waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.forkScoped,
);
return describeProcessExit(yield* Effect.result(handle.exitCode));
const exit = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
cause,
}),
),
Effect.exit,
);
yield* options.onExitObserved?.() ?? Effect.void;
yield* Effect.forEach(outputFibers, Fiber.await, {
concurrency: "unbounded",
discard: true,
}).pipe(
Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
Effect.ignore,
);
if (Exit.isFailure(exit)) {
return yield* Effect.failCause(exit.cause);
}
const exitCode = exit.value;
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
} satisfies BackendProcessExit;
});
// Factory for one pooled backend instance. The returned instance owns
@@ -394,12 +623,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory
| DesktopTelemetryPublisher.DesktopTelemetryPublisher
| Scope.Scope
> {
const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem;
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const state = yield* Ref.make(initialState);
@@ -444,6 +675,12 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
Effect.gen(function* () {
const current = yield* Ref.get(state);
if (Option.isSome(current.active)) {
if (!current.desiredRunning) {
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: true,
}));
}
return;
}
@@ -462,6 +699,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
Effect.option,
);
if (Option.isNone(config)) {
if (current.desiredRunning) {
yield* scheduleRestart("failed to generate desktop backend configuration");
}
return;
}
const entryExists = yield* fileSystem
@@ -561,6 +801,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
scope: runScope,
fiber: Option.none(),
pid: Option.none(),
exitObserved: false,
stopRequested: false,
} satisfies ActiveBackendRun),
nextRunId: latest.nextRunId + 1,
},
@@ -571,54 +813,70 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
) {
yield* mutex.withPermits(1)(
Effect.gen(function* () {
const { isCurrentRun, nextState, pid } = yield* Ref.modify(
state,
(
latest,
): readonly [
{
readonly isCurrentRun: boolean;
readonly nextState: BackendManagerState;
readonly pid: Option.Option<number>;
},
BackendManagerState,
] => {
const currentRun = Option.getOrUndefined(latest.active);
if (currentRun?.id !== runId) {
const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
yield* Ref.modify(
state,
(
latest,
): readonly [
{
readonly isCurrentRun: boolean;
readonly nextState: BackendManagerState;
readonly pid: Option.Option<number>;
readonly exitObserved: boolean;
readonly stopRequested: boolean;
readonly wasReady: boolean;
},
BackendManagerState,
] => {
const currentRun = Option.getOrUndefined(latest.active);
if (currentRun?.id !== runId) {
return [
{
isCurrentRun: false,
nextState: latest,
pid: Option.none<number>(),
exitObserved: false,
stopRequested: false,
wasReady: false,
},
latest,
] as const;
}
const next = {
...latest,
active: Option.none<ActiveBackendRun>(),
ready: false,
};
return [
{
isCurrentRun: false,
nextState: latest,
pid: Option.none<number>(),
isCurrentRun: true,
nextState: next,
pid: currentRun.pid,
exitObserved: currentRun.exitObserved,
stopRequested: currentRun.stopRequested,
wasReady: latest.ready,
},
latest,
next,
] as const;
}
const next = {
...latest,
active: Option.none<ActiveBackendRun>(),
ready: false,
};
return [
{
isCurrentRun: true,
nextState: next,
pid: currentRun.pid,
},
next,
] as const;
},
);
},
);
if (isCurrentRun) {
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
if (Option.isSome(pid)) {
yield* backendOutputLog.writeSessionBoundary({
phase: "END",
details: `pid=${pid.value} ${reason}`,
});
if (exitObserved && !stopRequested) {
yield* backendOutputLog.persistFailure({
details: `pid=${pid.value} ${reason}`,
});
} else {
yield* backendOutputLog.discardSession;
}
}
if (wasReady) {
yield* spec.onShutdown?.() ?? Effect.void;
}
yield* spec.onShutdown?.() ?? Effect.void;
}
if (isCurrentRun && nextState.desiredRunning) {
@@ -630,16 +888,23 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
const program = runBackendProcess({
...config.value,
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
onDesktopTelemetryControl: (message) =>
desktopTelemetryPublisher.handleControlForSource(spec.id, message),
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
}));
yield* backendOutputLog.writeSessionBoundary({
phase: "START",
yield* backendOutputLog.beginSession({
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
onExitObserved: () =>
updateActiveRun(runId, (run) => ({
...run,
exitObserved: true,
})),
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
const isCurrentRun = yield* Ref.modify(state, (latest) => {
const activeRun = Option.getOrUndefined(latest.active);
@@ -662,10 +927,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
}),
onReadinessFailure: (error) =>
logInstanceWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
function* (error) {
yield* logInstanceWarning("backend readiness check failed during bootstrap", {
error: error.message,
});
yield* backendOutputLog.persistFailureSnapshot({
details: error.message,
});
},
),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
@@ -750,41 +1021,92 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
readonly timeout?: Duration.Duration;
}) {
const { active, restartFiber } = yield* mutex.withPermits(1)(
const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
Effect.gen(function* () {
const result = yield* Ref.modify(state, (latest) => [
{
active: latest.active,
restartFiber: latest.restartFiber,
},
{
...latest,
desiredRunning: false,
ready: false,
active: Option.none<ActiveBackendRun>(),
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
]);
// Ignore failures from spec.onShutdown so a downstream throw
// can't abort the rest of stop(). Ref.modify above already
// flipped state to "no active run / no restart fiber", and the
// physical cleanup (Fiber.interrupt + closeRun) runs after the
// mutex releases. If onShutdown were allowed to propagate, both
// would be skipped and the child process + restart fiber would
// be orphaned while state claimed nothing was running — the
// next start() would then spawn a second backend on top.
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
const result = yield* Ref.modify(state, (latest) => {
const active = Option.map(latest.active, (run) =>
run.exitObserved ? run : { ...run, stopRequested: true },
);
return [
{
active,
restartFiber: latest.restartFiber,
notifyShutdown: latest.ready,
},
{
...latest,
desiredRunning: false,
ready: false,
active,
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
] as const;
});
return result;
}),
);
if (notifyShutdown) {
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
}
yield* Option.match(restartFiber, {
onNone: () => Effect.void,
onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
});
yield* Option.match(active, {
onNone: () => Effect.void,
onSome: (run) => closeRun(run, options),
onSome: (run) =>
Effect.gen(function* () {
const closed = yield* closeRun(run, parentScope, options);
if (!closed) {
return;
}
const cleanup = yield* mutex.withPermits(1)(
Ref.modify(
state,
(
latest,
): readonly [
{
readonly needsCleanup: boolean;
readonly shouldStart: boolean;
},
BackendManagerState,
] => {
const current = Option.getOrUndefined(latest.active);
if (current?.id !== run.id) {
return [
{
needsCleanup: false,
shouldStart:
latest.desiredRunning &&
Option.isNone(latest.active) &&
Option.isNone(latest.restartFiber),
},
latest,
];
}
return [
{
needsCleanup: true,
shouldStart: latest.desiredRunning,
},
{
...latest,
active: Option.none<ActiveBackendRun>(),
},
];
},
),
);
if (cleanup.needsCleanup) {
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
yield* backendOutputLog.discardSession;
}
if (cleanup.shouldStart) {
yield* start;
}
}),
});
});
@@ -5,11 +5,13 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
@@ -56,10 +58,21 @@ function makePoolLayer(
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () =>
Effect.succeed({
writeSessionBoundary: () => Effect.void,
beginSession: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailureSnapshot: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
latest: Effect.succeed(Option.none()),
changes: Stream.empty,
encoded: Stream.empty,
handleControl: () => Effect.void,
handleControlForSource: () => Effect.void,
removeControlSource: () => Effect.void,
}),
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
resolvePrimary: Effect.die("unexpected primary config resolve"),
resolvePrimaryLabel: Ref.get(labelRef),
@@ -97,6 +97,7 @@ import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
@@ -176,7 +177,8 @@ export type BackendInstanceFactoryRequirements =
| FileSystem.FileSystem
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory;
| DesktopObservability.DesktopBackendOutputLogFactory
| DesktopTelemetryPublisher.DesktopTelemetryPublisher;
interface ActiveRegisteredInstance {
readonly _tag: "Active";
+28 -3
View File
@@ -4,6 +4,8 @@ import { beforeEach, vi } from "vite-plus/test";
const {
appendSwitchMock,
autoUpdaterOnMock,
autoUpdaterRemoveListenerMock,
exitMock,
getAppPathMock,
getVersionMock,
@@ -12,7 +14,6 @@ const {
quitMock,
relaunchMock,
removeListenerMock,
requestSingleInstanceLockMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
@@ -23,6 +24,8 @@ const {
whenReadyMock,
} = vi.hoisted(() => ({
appendSwitchMock: vi.fn(),
autoUpdaterOnMock: vi.fn(),
autoUpdaterRemoveListenerMock: vi.fn(),
exitMock: vi.fn(),
getAppPathMock: vi.fn(() => "/app"),
getVersionMock: vi.fn(() => "1.2.3"),
@@ -31,7 +34,6 @@ const {
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
requestSingleInstanceLockMock: vi.fn(() => true),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
@@ -43,6 +45,10 @@ const {
}));
vi.mock("electron", () => ({
autoUpdater: {
on: autoUpdaterOnMock,
removeListener: autoUpdaterRemoveListenerMock,
},
app: {
commandLine: {
appendSwitch: appendSwitchMock,
@@ -59,7 +65,6 @@ vi.mock("electron", () => ({
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
requestSingleInstanceLock: requestSingleInstanceLockMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
@@ -77,6 +82,8 @@ import * as ElectronApp from "./ElectronApp.ts";
describe("ElectronApp", () => {
beforeEach(() => {
appendSwitchMock.mockClear();
autoUpdaterOnMock.mockClear();
autoUpdaterRemoveListenerMock.mockClear();
exitMock.mockClear();
onMock.mockClear();
quitMock.mockClear();
@@ -153,4 +160,22 @@ describe("ElectronApp", () => {
assert.deepEqual(removeListenerMock.mock.calls, [["activate", listener]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("scopes native updater quit listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
yield* Effect.scoped(
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.onBeforeQuitForUpdate(listener);
}),
);
assert.deepEqual(autoUpdaterOnMock.mock.calls, [["before-quit-for-update", listener]]);
assert.deepEqual(autoUpdaterRemoveListenerMock.mock.calls, [
["before-quit-for-update", listener],
]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
});
+15 -2
View File
@@ -56,7 +56,7 @@ export class ElectronApp extends Context.Service<
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
@@ -66,6 +66,9 @@ export class ElectronApp extends Context.Service<
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly onBeforeQuitForUpdate: (
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
@@ -149,7 +152,7 @@ export const make = ElectronApp.of({
Effect.sync(() => {
Electron.app.setAppUserModelId(id);
}),
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
isDefaultProtocolClient: (protocol) =>
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
setAsDefaultProtocolClient: (protocol, path, args) =>
@@ -178,6 +181,16 @@ export const make = ElectronApp.of({
}
Electron.app.commandLine.appendSwitch(switchName, value);
}),
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
Electron.autoUpdater.on("before-quit-for-update", listener);
}),
() =>
Effect.sync(() => {
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
}),
).pipe(Effect.asVoid),
on: addScopedAppListener,
});
@@ -0,0 +1,89 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
export class ElectronPowerMonitor extends Context.Service<
ElectronPowerMonitor,
{
readonly isOnBatteryPower: Effect.Effect<boolean>;
readonly getSystemIdleTime: Effect.Effect<number>;
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
readonly onSimpleEvent: (
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly onThermalStateChange: (
listener: (state: ElectronThermalState) => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly onSpeedLimitChange: (
listener: (limit: number) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
const onSimpleEvent: ElectronPowerMonitor["Service"]["onSimpleEvent"] = (eventName, listener) =>
Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on(eventName as any, listener as any);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener(eventName as any, listener as any);
}),
).pipe(Effect.asVoid);
const onThermalStateChange: ElectronPowerMonitor["Service"]["onThermalStateChange"] = (
listener,
) => {
const wrapped = (
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
): void => {
listener(event.state);
};
return Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on("thermal-state-change", wrapped);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
}),
).pipe(Effect.asVoid);
};
const onSpeedLimitChange: ElectronPowerMonitor["Service"]["onSpeedLimitChange"] = (listener) => {
const wrapped = (
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
): void => {
listener(event.limit);
};
return Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on("speed-limit-change", wrapped);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
}),
).pipe(Effect.asVoid);
};
export const make = ElectronPowerMonitor.of({
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
getSystemIdleState: (idleThresholdSeconds) =>
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
onSimpleEvent,
onThermalStateChange,
onSpeedLimitChange,
});
export const layer = Layer.succeed(ElectronPowerMonitor, make);
+4
View File
@@ -24,6 +24,7 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
import * as ElectronApp from "./electron/ElectronApp.ts";
import * as ElectronDialog from "./electron/ElectronDialog.ts";
import * as ElectronMenu from "./electron/ElectronMenu.ts";
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronShell from "./electron/ElectronShell.ts";
@@ -52,6 +53,7 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -113,6 +115,7 @@ const electronLayer = Layer.mergeAll(
ElectronApp.layer,
ElectronDialog.layer,
ElectronMenu.layer,
ElectronPowerMonitor.layer,
ElectronProtocol.layer,
ElectronSafeStorage.layer,
ElectronShell.layer,
@@ -160,6 +163,7 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
Layer.provideMerge(DesktopWslEnvironment.layer),
Layer.provideMerge(DesktopTelemetryPublisher.layer),
Layer.provideMerge(desktopWindowLayer),
);
+86
View File
@@ -982,6 +982,92 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("emits debugger screencast frames only while recording is active", () =>
withManager((manager) =>
Effect.gen(function* () {
let debuggerMessage:
| ((event: unknown, method: string, params: Record<string, unknown>) => void)
| undefined;
const capturePage = vi.fn(async () => ({
toJPEG: () => Buffer.from("scheduled-recording-frame"),
getSize: () => ({ width: 1280, height: 720 }),
}));
const sendCommand = vi.fn(async (method: string) =>
method === "Runtime.evaluate" ? { result: { value: null } } : undefined,
);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(
(
event: string,
listener: (event: unknown, method: string, params: Record<string, unknown>) => void,
) => {
if (event === "message") debuggerMessage = listener;
},
),
off: vi.fn(),
},
capturePage,
} as never);
const recordingFrames: DesktopPreviewRecordingFrame[] = [];
yield* manager.subscribeRecordingFrames((frame) =>
Effect.sync(() => {
recordingFrames.push(frame);
}),
);
yield* manager.createTab("tab_screencast_guard");
yield* manager.registerWebview("tab_screencast_guard", 42);
yield* manager.automationEvaluate("tab_screencast_guard", { expression: "null" });
debuggerMessage?.({}, "Page.screencastFrame", {
sessionId: 1,
data: "inactive-frame",
metadata: { deviceWidth: 1280, deviceHeight: 720 },
});
yield* Effect.yieldNow;
expect(recordingFrames).toHaveLength(0);
yield* manager.startRecording("tab_screencast_guard");
recordingFrames.length = 0;
debuggerMessage?.({}, "Page.screencastFrame", {
sessionId: 2,
data: "active-frame",
metadata: { deviceWidth: 1280, deviceHeight: 720 },
});
yield* Effect.yieldNow;
expect(recordingFrames).toEqual([
expect.objectContaining({
tabId: "tab_screencast_guard",
data: "active-frame",
width: 1280,
height: 720,
}),
]);
yield* manager.stopRecording("tab_screencast_guard");
}),
),
);
effectIt.effect("shares background frame capture between recording and picture-in-picture", () =>
withManager((manager) =>
Effect.gen(function* () {
+55 -6
View File
@@ -671,10 +671,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
);
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
const tabs = yield* SynchronizedRef.get(tabsRef);
return (
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
);
});
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
const captureDiagnosticMessage = Effect.fnUntraced(function* (
webContentsId: number,
method: string,
params: Record<string, unknown>,
@@ -852,11 +859,53 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
const semaphore = yield* Semaphore.make(1);
const scope = yield* Scope.fork(parentScope, "sequential");
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
function* (method: string, params: Record<string, unknown>) {
yield* captureDiagnosticMessage(wc.id, method, params);
},
);
const handleDebuggerMessage = Effect.fnUntraced(function* (
method: string,
params: Record<string, unknown>,
) {
if (method === "Page.screencastFrame") {
const sessionId = params["sessionId"];
if (typeof sessionId === "number") {
yield* attemptPromise(
{
operation: "ackScreencastFrame",
webContentsId: wc.id,
},
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
).pipe(Effect.ignore);
}
const tabId = yield* tabIdForWebContents(wc.id);
const metadata =
typeof params["metadata"] === "object" && params["metadata"] !== null
? (params["metadata"] as Record<string, unknown>)
: {};
if (tabId && typeof params["data"] === "string") {
const captureSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(
tabId,
);
if (captureSession?.consumers.has("recording")) {
const receivedAt = yield* currentIso;
const listeners = yield* Ref.get(recordingFrameListenersRef);
const frame: DesktopPreviewRecordingFrame = {
tabId,
data: params["data"],
width:
typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
height:
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
receivedAt,
};
yield* Effect.forEach(
listeners,
(listener) =>
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
{ discard: true },
);
}
}
}
yield* captureDiagnosticMessage(wc.id, method, params);
});
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
runFork(handleDebuggerMessage(method, params));
};
@@ -18,6 +18,7 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
environmentIdentificationMode: "artwork",
favorites: [],
glassOpacity: 80,
providerModelPreferences: {},
@@ -28,6 +29,9 @@ const clientSettings: ClientSettings = {
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
sidebarV2Enabled: false,
sidebarV2ConfiguredByUser: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -0,0 +1,387 @@
import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
function makeElectronAppLayer(
metrics: ReadonlyArray<Electron.ProcessMetric>,
onMetricsRead: () => void = () => undefined,
) {
return Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
getAppMetrics: Effect.sync(() => {
onMetricsRead();
return metrics;
}),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
}
describe("DesktopTelemetryPublisher", () => {
it.effect("stops when its scope closes during an Electron telemetry sample", () =>
Effect.gen(function* () {
const pollStarted = yield* Deferred.make<void>();
const blockPoll = yield* Deferred.make<void>();
const powerLayer = Layer.succeed(
ElectronPowerMonitor.ElectronPowerMonitor,
ElectronPowerMonitor.ElectronPowerMonitor.of({
isOnBatteryPower: Effect.succeed(false),
getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe(
Effect.andThen(Deferred.await(blockPoll)),
Effect.as(0),
),
getSystemIdleState: () => Effect.succeed("active"),
getCurrentThermalState: Effect.succeed("nominal"),
onSimpleEvent: () => Effect.void,
onThermalStateChange: () => Effect.void,
onSpeedLimitChange: () => Effect.void,
}),
);
const layer = DesktopTelemetryPublisher.layer.pipe(
Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
);
const scope = yield* Scope.make();
yield* Layer.buildWithScope(layer, scope);
yield* Deferred.await(pollStarted);
const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
assert.isDefined(closeFiber.pollUnsafe());
}),
);
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
Effect.gen(function* () {
const onBattery = yield* Ref.make(false);
const systemIdleState = yield* Ref.make<ElectronPowerMonitor.ElectronIdleState>("active");
let beforeSystemIdleState: Effect.Effect<void> = Effect.void;
let metricsReadCount = 0;
const simpleListeners = new Map<string, () => void>();
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
null;
let speedLimitListener: ((limit: number) => void) | null = null;
const metrics = [
{
pid: 4_242,
type: "Browser",
creationTime: 1_000.75,
name: "electron",
cpu: {
percentCPUUsage: 12.5,
cumulativeCPUUsage: 3.25,
idleWakeupsPerSecond: 7,
},
memory: {
workingSetSize: 2_048,
peakWorkingSetSize: 4_096,
},
} as Electron.ProcessMetric,
];
const powerLayer = Layer.succeed(
ElectronPowerMonitor.ElectronPowerMonitor,
ElectronPowerMonitor.ElectronPowerMonitor.of({
isOnBatteryPower: Ref.get(onBattery),
getSystemIdleTime: Effect.succeed(5),
getSystemIdleState: () =>
beforeSystemIdleState.pipe(Effect.andThen(Ref.get(systemIdleState))),
getCurrentThermalState: Effect.succeed("nominal"),
onSimpleEvent: (eventName, listener) =>
Effect.sync(() => {
simpleListeners.set(eventName, listener);
}),
onThermalStateChange: (listener) =>
Effect.sync(() => {
thermalListener = listener;
}),
onSpeedLimitChange: (listener) =>
Effect.sync(() => {
speedLimitListener = listener;
}),
}),
);
const layer = DesktopTelemetryPublisher.layer.pipe(
Layer.provide(
Layer.mergeAll(
makeElectronAppLayer(metrics, () => {
metricsReadCount += 1;
}),
powerLayer,
),
),
);
yield* Effect.gen(function* () {
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
const decoder = new TextDecoder();
const decodeMessage = Schema.decodeUnknownEffect(
Schema.fromJsonString(DesktopHostTelemetryMessage),
);
const messages = yield* Effect.forEach(encoded, (bytes) =>
decodeMessage(decoder.decode(bytes).trim()),
);
assert.equal(messages[0]?.type, "desktopTelemetryHello");
assert.equal(messages[0]?.electronPid, process.pid);
const initialSnapshot = messages[1];
if (initialSnapshot?.type !== "desktopTelemetry") {
return assert.fail("Expected the second telemetry message to be a snapshot.");
}
assert.deepEqual(initialSnapshot.electronProcesses, []);
assert.equal(initialSnapshot.electronPid, process.pid);
assert.equal(metricsReadCount, 0);
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
assert.equal(demandedSnapshot.electronProcesses[0]?.creationTimeMs, 1_001);
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
assert.equal(metricsReadCount, 1);
yield* publisher.handleControlForSource("secondary-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
});
yield* publisher.handleControlForSource("old-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
yield* publisher.handleControlForSource("secondary-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
});
yield* Effect.all(
[
publisher.removeControlSource("old-backend"),
publisher.handleControlForSource("replacement-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
}),
],
{ concurrency: "unbounded", discard: true },
);
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
simpleListeners.get("on-battery")?.();
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
assert.equal(batterySnapshot.power.onBattery, "true");
yield* Ref.set(onBattery, true);
const metricsAfterBatteryEvent = metricsReadCount;
yield* TestClock.adjust(Duration.millis(4_999));
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "true");
yield* Ref.set(onBattery, false);
const metricsBeforePolledAc = metricsReadCount;
yield* TestClock.adjust(Duration.seconds(5));
assert.equal(metricsReadCount, metricsBeforePolledAc + 1);
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "false");
yield* TestClock.adjust(Duration.seconds(1));
assert.equal(metricsReadCount, metricsBeforePolledAc + 2);
const suspendedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
simpleListeners.get("suspend")?.();
const suspendedSnapshot = Option.getOrThrow(yield* Fiber.join(suspendedSnapshotFiber));
assert.isTrue(suspendedSnapshot.power.suspended);
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
thermalListener?.("serious");
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
assert.equal(constrainedSnapshot.power.thermalState, "serious");
assert.isTrue(constrainedSnapshot.power.suspended);
const metricsAfterThermalEvent = metricsReadCount;
const recoveredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* TestClock.adjust(Duration.millis(14_999));
assert.equal(metricsReadCount, metricsAfterThermalEvent);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
const recoveredSnapshot = Option.getOrThrow(yield* Fiber.join(recoveredSnapshotFiber));
assert.isFalse(recoveredSnapshot.power.suspended);
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
speedLimitListener?.(65);
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
const encodedSpeedLimit = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
const decodedSpeedLimit = yield* decodeMessage(decoder.decode(encodedSpeedLimit[1]).trim());
if (decodedSpeedLimit.type !== "desktopTelemetry") {
return assert.fail("Expected the encoded telemetry message to be a snapshot.");
}
assert.equal(Option.getOrNull(decodedSpeedLimit.speedLimitPercent), 65);
assert.equal(decodedSpeedLimit.electronProcesses[0]?.pid, 4_242);
assert.equal(decodedSpeedLimit.electronProcesses[0]?.creationTimeMs, 1_001);
const metricsBeforeSecondaryOnlySample = metricsReadCount;
yield* TestClock.adjust(Duration.seconds(15));
assert.equal(metricsReadCount, metricsBeforeSecondaryOnlySample + 1);
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).electronProcesses[0]?.pid,
4_242,
);
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* publisher.handleControlForSource("replacement-backend", {
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
});
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
const metricsAfterStopping = metricsReadCount;
const configuredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setHostPowerIntervals",
activeIntervalMs: 7_000,
idleIntervalMs: 11_000,
});
const configuredSequence = Option.getOrThrow(
yield* Fiber.join(configuredSnapshotFiber),
).sequence;
yield* TestClock.adjust(Duration.millis(6_999));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
configuredSequence,
);
assert.equal(metricsReadCount, metricsAfterStopping);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
configuredSequence + 1,
);
assert.equal(metricsReadCount, metricsAfterStopping);
yield* Ref.set(systemIdleState, "locked");
yield* TestClock.adjust(Duration.seconds(7));
const lockedSequence = (yield* publisher.latest).pipe(Option.getOrThrow).sequence;
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.locked, "true");
yield* TestClock.adjust(Duration.millis(10_999));
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).sequence, lockedSequence);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
lockedSequence + 1,
);
yield* Ref.set(systemIdleState, "active");
yield* TestClock.adjust(Duration.seconds(11));
const unlockedSnapshot = (yield* publisher.latest).pipe(Option.getOrThrow);
assert.equal(unlockedSnapshot.power.locked, "false");
assert.equal(unlockedSnapshot.power.idle, "false");
yield* TestClock.adjust(Duration.millis(6_999));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
unlockedSnapshot.sequence,
);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
unlockedSnapshot.sequence + 1,
);
const pollStarted = yield* Deferred.make<void>();
const releasePoll = yield* Deferred.make<void>();
beforeSystemIdleState = Deferred.succeed(pollStarted, undefined).pipe(
Effect.andThen(Deferred.await(releasePoll)),
);
const concurrentEventSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
yield* Deferred.await(pollStarted);
simpleListeners.get("lock-screen")?.();
thermalListener?.("critical");
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Deferred.succeed(releasePoll, undefined);
const concurrentEventSnapshot = Option.getOrThrow(
yield* Fiber.join(concurrentEventSnapshotFiber),
);
assert.equal(concurrentEventSnapshot.power.locked, "true");
assert.equal(concurrentEventSnapshot.power.thermalState, "critical");
}).pipe(Effect.provide(layer));
}),
);
});
@@ -0,0 +1,379 @@
import {
DesktopHostTelemetryMessage,
type DesktopHostTelemetrySnapshot,
type DesktopTelemetryControlMessage,
type HostPowerSnapshot,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
const DEFAULT_HOST_POWER_ACTIVE_INTERVAL = Duration.seconds(30);
const DEFAULT_HOST_POWER_IDLE_INTERVAL = Duration.minutes(2);
const IDLE_THRESHOLD_SECONDS = 60;
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
const textEncoder = new TextEncoder();
type PowerEvent =
| { readonly type: "locked"; readonly value: boolean }
| { readonly type: "suspended"; readonly value: boolean }
| { readonly type: "onBattery"; readonly value: boolean }
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
| { readonly type: "speedLimit"; readonly value: number };
interface PowerState {
readonly idle: HostPowerSnapshot["idle"];
readonly locked: HostPowerSnapshot["locked"];
readonly lockedEventPending: boolean;
readonly suspended: boolean;
readonly suspendedEventPending: boolean;
readonly onBattery: HostPowerSnapshot["onBattery"];
readonly onBatteryEventPending: boolean;
readonly thermalState: HostPowerSnapshot["thermalState"];
readonly speedLimitPercent: Option.Option<number>;
}
interface HostPowerIntervals {
readonly active: Duration.Duration;
readonly idle: Duration.Duration;
}
export class DesktopTelemetryPublisher extends Context.Service<
DesktopTelemetryPublisher,
{
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
readonly encoded: Stream.Stream<Uint8Array>;
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
readonly handleControlForSource: (
sourceId: string,
message: DesktopTelemetryControlMessage,
) => Effect.Effect<void>;
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
return value ? "true" : "false";
}
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
switch (value) {
case "active":
return "false";
case "idle":
case "locked":
return "true";
case "unknown":
return "unknown";
}
}
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
switch (event.type) {
case "locked":
return {
...state,
locked: booleanState(event.value),
lockedEventPending: true,
};
case "suspended":
return {
...state,
suspended: event.value,
suspendedEventPending: event.value,
};
case "onBattery":
return {
...state,
onBattery: booleanState(event.value),
onBatteryEventPending: true,
};
case "thermal":
return { ...state, thermalState: event.value };
case "speedLimit":
return { ...state, speedLimitPercent: Option.some(event.value) };
}
}
function sampleInterval(
power: PowerState,
diagnosticsDemand: boolean,
hostPowerIntervals: HostPowerIntervals,
): Duration.Duration {
if (!diagnosticsDemand) {
return power.suspended || power.locked === "true" || power.idle === "true"
? hostPowerIntervals.idle
: hostPowerIntervals.active;
}
if (
power.suspended ||
power.locked === "true" ||
power.thermalState === "serious" ||
power.thermalState === "critical"
) {
return CONSTRAINED_SAMPLE_INTERVAL;
}
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
return LIVE_SAMPLE_INTERVAL;
}
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
yield* electronApp.whenReady;
const initialPowerState: PowerState = {
idle: "unknown",
locked: "unknown",
lockedEventPending: false,
suspended: false,
suspendedEventPending: false,
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
onBatteryEventPending: false,
thermalState: yield* powerMonitor.getCurrentThermalState,
speedLimitPercent: Option.none(),
};
const powerState = yield* Ref.make(initialPowerState);
const hostPowerIntervals = yield* Ref.make<HostPowerIntervals>({
active: DEFAULT_HOST_POWER_ACTIVE_INTERVAL,
idle: DEFAULT_HOST_POWER_IDLE_INTERVAL,
});
const powerEvents = yield* Queue.unbounded<PowerEvent>();
const sampleTriggers = yield* Queue.sliding<void>(1);
const diagnosticsDemandSources = yield* Ref.make<ReadonlySet<string>>(new Set());
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
const sequence = yield* Ref.make(0);
const offer = (event: PowerEvent): void => {
Queue.offerUnsafe(powerEvents, event);
};
yield* Effect.all(
[
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
],
{ concurrency: "unbounded" },
);
yield* Effect.forever(
Queue.take(powerEvents).pipe(
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
),
).pipe(Effect.forkScoped);
const sampleOnce = (allowSuspendRecovery: boolean) =>
Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
[
Ref.get(powerState),
powerMonitor.getSystemIdleTime,
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
powerMonitor.isOnBatteryPower,
demand ? electronApp.getAppMetrics : Effect.succeed([]),
],
{ concurrency: "unbounded" },
);
const polledLocked =
systemIdleState === "unknown"
? currentPower.locked
: booleanState(systemIdleState === "locked");
const polledOnBattery = booleanState(onBattery);
const observedPower = yield* Ref.modify(powerState, (latestPower) => {
const preserveEventLocked =
latestPower.lockedEventPending ||
latestPower.locked !== currentPower.locked ||
latestPower.lockedEventPending !== currentPower.lockedEventPending;
const preserveEventOnBattery =
latestPower.onBatteryEventPending ||
latestPower.onBattery !== currentPower.onBattery ||
latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
const preserveEventSuspended =
latestPower.suspendedEventPending ||
latestPower.suspended !== currentPower.suspended ||
latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
const next: PowerState = {
...latestPower,
idle: idleState(systemIdleState),
locked: preserveEventLocked ? latestPower.locked : polledLocked,
lockedEventPending:
latestPower.lockedEventPending &&
(systemIdleState === "unknown" || polledLocked !== latestPower.locked),
suspended:
allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
suspendedEventPending: false,
onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
onBatteryEventPending:
latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
};
return [next, next] as const;
});
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
const snapshot: DesktopHostTelemetrySnapshot = {
version: 1,
type: "desktopTelemetry",
sequence: nextSequence,
sampledAtUnixMs,
electronPid: process.pid,
power: {
source: "electron-main",
idle: observedPower.idle,
idleSeconds,
locked: observedPower.locked,
suspended: observedPower.suspended,
onBattery: observedPower.onBattery,
lowPowerMode: "unknown",
thermalState: observedPower.thermalState,
stale: false,
updatedAt: sampledAt,
},
speedLimitPercent: observedPower.speedLimitPercent,
electronProcesses: metrics.map((metric) => ({
pid: metric.pid,
creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
type: metric.type,
...(metric.name === undefined ? {} : { name: metric.name }),
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
cpuPercent: metric.cpu.percentCPUUsage,
...(metric.cpu.cumulativeCPUUsage === undefined
? {}
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
})),
};
yield* Ref.set(latest, Option.some(snapshot));
yield* PubSub.publish(changes, snapshot);
}).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("Failed to sample Electron telemetry", {
cause: String(cause),
}),
),
);
yield* Effect.gen(function* () {
yield* sampleOnce(false);
while (true) {
const [currentPower, demand, intervals] = yield* Effect.all([
Ref.get(powerState),
Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
Ref.get(hostPowerIntervals),
]);
const allowSuspendRecovery = yield* Effect.raceFirst(
Queue.take(sampleTriggers).pipe(Effect.as(false)),
Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
);
yield* sampleOnce(allowSuspendRecovery);
}
}).pipe(Effect.forkScoped);
const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
sourceId,
message,
) => {
switch (message.type) {
case "setDiagnosticsDemand":
return Ref.modify(diagnosticsDemandSources, (sources) => {
const previous = sources.size > 0;
const next = new Set(sources);
if (message.enabled) {
next.add(sourceId);
} else {
next.delete(sourceId);
}
return [[previous, next.size > 0] as const, next] as const;
}).pipe(
Effect.flatMap(([previous, enabled]) =>
previous === enabled
? Effect.void
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
),
);
case "setHostPowerIntervals":
return Ref.set(hostPowerIntervals, {
active: Duration.millis(message.activeIntervalMs),
idle: Duration.millis(message.idleIntervalMs),
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
}
};
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
sourceId,
) =>
Ref.modify(diagnosticsDemandSources, (sources) => {
const previous = sources.size > 0;
const next = new Set(sources);
next.delete(sourceId);
return [[previous, next.size > 0] as const, next] as const;
}).pipe(
Effect.flatMap(([previous, enabled]) =>
previous === enabled
? Effect.void
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
),
);
const handleControl: DesktopTelemetryPublisher["Service"]["handleControl"] = (message) =>
handleControlForSource("legacy", message);
const snapshots = Stream.unwrap(
Effect.gen(function* () {
const subscription = yield* PubSub.subscribe(changes);
const initial = yield* Ref.get(latest);
return Stream.concat(
Option.match(initial, {
onNone: () => Stream.empty,
onSome: Stream.make,
}),
Stream.fromSubscription(subscription),
);
}),
);
const encoded = Stream.concat(
Stream.make({
version: 1,
type: "desktopTelemetryHello",
electronPid: process.pid,
} as const),
snapshots,
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
return DesktopTelemetryPublisher.of({
latest: Ref.get(latest),
changes: Stream.fromPubSub(changes),
encoded,
handleControl,
handleControlForSource,
removeControlSource,
});
});
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
@@ -39,12 +39,13 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
+8 -1
View File
@@ -1,5 +1,10 @@
---
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import {
ANDROID_PLAY_STORE_URL,
GITHUB_REPOSITORY_URL,
IOS_APP_STORE_URL,
MARKETING_STATS,
} from "../lib/site";
interface Props {
title?: string;
@@ -69,6 +74,8 @@ const {
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS app</a>
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android app</a>
<a href="/terms-of-service">Terms</a>
<a href="/privacy-policy">Privacy</a>
<a href="/security-policy">Security</a>
+6
View File
@@ -1,5 +1,11 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const IOS_APP_STORE_URL =
"https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824";
export const ANDROID_PLAY_STORE_URL =
"https://play.google.com/store/apps/details?id=com.t3tools.t3code";
export const MARKETING_STATS = {
githubStars: "14k+",
users: "100,000",
+21 -1
View File
@@ -1,6 +1,7 @@
---
import Layout from "../layouts/Layout.astro";
import { RELEASES_URL } from "../lib/releases";
import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
@@ -57,6 +58,24 @@ import { RELEASES_URL } from "../lib/releases";
</a>
</div>
</section>
<!-- Mobile -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="7" y="2" width="10" height="20" rx="2.5"/><path d="M11 18.5h2"/></svg>
<h2 class="platform-name">Mobile</h2>
</div>
<div class="download-cards">
<a class="download-card" href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">
<span class="card-arch">iPhone &amp; iPad</span>
<span class="card-format">App Store</span>
</a>
<a class="download-card" href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">
<span class="card-arch">Android</span>
<span class="card-format">Google Play</span>
</a>
</div>
</section>
</div>
<p class="releases-link">
@@ -73,7 +92,8 @@ import { RELEASES_URL } from "../lib/releases";
async function init() {
const versionLabel = document.getElementById("version-label");
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
// Only release-asset cards; mobile store cards have no data-asset and keep their href.
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card[data-asset]");
try {
const release = await fetchLatestRelease();
+34 -1
View File
@@ -1,6 +1,11 @@
---
import Layout from "../layouts/Layout.astro";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import {
ANDROID_PLAY_STORE_URL,
GITHUB_REPOSITORY_URL,
IOS_APP_STORE_URL,
MARKETING_STATS,
} from "../lib/site";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -66,6 +71,12 @@ const mobileEndorsementRows = [
<span>Steal our code (legally)</span>
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<p class="hero-mobile-line">
Also on your phone:
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS</a>
<span aria-hidden="true">·</span>
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android</a>
</p>
</div>
<div class="hero-preview">
@@ -578,6 +589,28 @@ const mobileEndorsementRows = [
opacity: 1;
}
.hero-mobile-line {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--fg-dim);
font-size: 13px;
letter-spacing: -0.005em;
}
.hero-mobile-line a {
color: var(--fg-muted);
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.18s ease, text-decoration-color 0.18s ease;
}
.hero-mobile-line a:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* Download button icons (platform-aware) */
.dl-icon {
display: none;
+3 -1
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "0.1.0",
version: "1.0.1",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
@@ -275,10 +275,12 @@ const config: ExpoConfig = {
"expo-camera",
{
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
microphonePermission: false,
barcodeScannerEnabled: true,
recordAudioAndroid: false,
},
],
["expo-image-picker", { photosPermission: false, microphonePermission: false }],
[
"expo-splash-screen",
{
@@ -141,7 +141,7 @@ private final class ComposerTextView: UITextView {
replace(textRange, withText: "")
}
private func loadImages(from providers: [NSItemProvider]) {
func loadImages(from providers: [NSItemProvider]) {
let group = DispatchGroup()
let lock = NSLock()
var images = [UIImage?](repeating: nil, count: providers.count)
@@ -282,7 +282,7 @@ private final class ComposerTextView: UITextView {
}
}
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDropDelegate {
private let textView = ComposerTextView()
private let placeholderLabel = UILabel()
private var value = ""
@@ -326,6 +326,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
clipsToBounds = false
textView.delegate = self
textView.textDropDelegate = self
textView.backgroundColor = .clear
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
@@ -500,6 +501,41 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
return true
}
public func textDroppableView(
_ textDroppableView: UIView & UITextDroppable,
proposalForDrop drop: UITextDropRequest
) -> UITextDropProposal {
guard droppedImageProviders(in: drop) != nil else {
return drop.suggestedProposal
}
// The composer owns image drops so UIKit does not insert NSTextAttachments
// that the controlled plain-text value cannot represent.
let proposal = UITextDropProposal(operation: .copy)
proposal.dropAction = .insert
proposal.dropPerformer = .delegate
return proposal
}
public func textDroppableView(
_ textDroppableView: UIView & UITextDroppable,
willPerformDrop drop: UITextDropRequest
) {
guard let imageProviders = droppedImageProviders(in: drop) else {
return
}
textView.loadImages(from: imageProviders)
}
private func droppedImageProviders(in drop: UITextDropRequest) -> [NSItemProvider]? {
let providers = drop.dropSession.items.map(\.itemProvider)
guard !providers.isEmpty,
providers.allSatisfy({ $0.canLoadObject(ofClass: UIImage.self) }) else {
return nil
}
return providers
}
public func textViewDidBeginEditing(_ textView: UITextView) {
onComposerFocus()
}
+2 -2
View File
@@ -11,7 +11,7 @@
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
"start:prod": "APP_VARIANT=production expo start",
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
"showcase": "APP_VARIANT=production EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code --clear",
"screenshots": "node ../../scripts/mobile-showcase.ts",
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
@@ -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.2.0",
"@legendapp/list": "3.3.3",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
+15 -5
View File
@@ -15,6 +15,7 @@ import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "re
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";
@@ -47,7 +48,6 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
SettingsLegalDocumentCloseHeaderButton,
@@ -190,10 +190,11 @@ const SettingsSheetStack = createNativeStackNavigator({
},
}),
SettingsWaitlist: createNativeStackScreen({
screen: SettingsWaitlistRouteScreen,
// Keep the old deep link working after the Connect GA launch.
screen: SettingsAuthRouteScreen,
linking: "waitlist",
options: {
title: "Join the waitlist",
title: "Sign in",
},
}),
},
@@ -284,6 +285,15 @@ function workspacePathFromState(state: NavigationState): string {
return path.startsWith("/") ? path : `/${path}`;
}
// The drain hook subscribes to the outbox, all thread shells, projects, and
// connection statuses. Hosting it in a null-rendering leaf keeps those
// updates from re-rendering RootStackLayout (and with it every screen) on
// each enqueue, shell change, or reconnect.
function ThreadOutboxDrainWorker() {
useThreadOutboxDrain();
return null;
}
function RootStackLayout(props: {
readonly children: React.ReactNode;
readonly state: NavigationState;
@@ -292,7 +302,6 @@ function RootStackLayout(props: {
const { pendingShare } = useIncomingShare();
const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
useAgentNotificationNavigation();
useThreadOutboxDrain();
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
useConnectOnboardingNavigation();
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
@@ -320,6 +329,7 @@ function RootStackLayout(props: {
return (
<HardwareKeyboardCommandProvider pathname={pathname}>
<ThreadOutboxDrainWorker />
<ShowcaseCaptureCoordinator pathname={pathname} />
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
@@ -383,7 +393,7 @@ export const RootStack = createNativeStackNavigator({
...GLASS_HEADER_OPTIONS,
contentStyle: { backgroundColor: "transparent" },
headerBackVisible: false,
title: "Threads",
...getCompactBrandHeaderOptions(),
},
}),
Thread: createNativeStackScreen({
@@ -0,0 +1,121 @@
import Constants from "expo-constants";
import type {
NativeStackHeaderItem,
NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { Platform, View } from "react-native";
import { AppText as Text } from "./AppText";
import { T3Wordmark } from "./T3Wordmark";
import { IPAD_HOME_TITLE_OFFSET } from "../lib/layoutMetrics";
import { resolveMobileStageLabel } from "../lib/mobileBranding";
import { useThemeColor } from "../lib/useThemeColor";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
// Native leading items inherit different UIKit margins than title views.
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
/**
* Compact brand lockup sized for native navigation bars.
*/
export function CompactBrandTitle(
props: {
readonly nativeLeadingItem?: boolean;
} = {},
) {
const iconColor = useThemeColor("--color-icon");
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;
return (
<View
aria-level={1}
accessibilityLabel="T3 Code, Threads"
accessible
role="heading"
style={{
alignItems: "center",
flexDirection: "row",
gap: 6,
marginLeft: titleOffset,
}}
>
<T3Wordmark color={iconColor} height={15} />
<Text
style={{
color: mutedColor,
fontFamily: "DMSans-Medium",
fontSize: 21,
letterSpacing: -0.5,
}}
>
Code
</Text>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 999,
paddingHorizontal: 6,
paddingVertical: 2,
}}
>
<Text
style={{
color: mutedColor,
fontFamily: "DMSans-Bold",
fontSize: 9,
letterSpacing: 0.9,
textTransform: "uppercase",
}}
>
{stageLabel}
</Text>
</View>
</View>
);
}
export function renderCompactBrandTitle() {
return <CompactBrandTitle />;
}
export function renderCompactBrandHeaderItems(): NativeStackHeaderItem[] {
return [
{
element: <CompactBrandTitle nativeLeadingItem />,
hidesSharedBackground: true,
type: "custom",
},
];
}
export function getCompactBrandHeaderOptions(
fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"],
): NativeStackNavigationOptions {
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
return {
headerTitle: "Threads",
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
title: "Threads",
unstable_headerLeftItems: renderCompactBrandHeaderItems,
};
}
return {
headerTitle: renderCompactBrandTitle,
headerTitleStyle: fallbackTitleStyle,
title: "Threads",
};
}
+45 -12
View File
@@ -1,14 +1,21 @@
import { SymbolView } from "./AppSymbol";
import { Image } from "expo-image";
import { useState } from "react";
import { useLayoutEffect, useMemo, useState } from "react";
import { View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
import {
getProjectFaviconCacheKey,
isProjectFaviconFallbackUrl,
} from "@t3tools/shared/projectFavicon";
import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
const loadedFaviconUrls = new Set<string>();
import {
beginProjectFaviconRequest,
createProjectFaviconRequest,
hasLoadedProjectFavicon,
markProjectFaviconFailed,
markProjectFaviconLoaded,
} from "./projectFaviconCache";
/* ─── Component ──────────────────────────────────────────────────────── */
export function ProjectFavicon(props: {
@@ -26,10 +33,15 @@ export function ProjectFavicon(props: {
: { _tag: "project-favicon", cwd: props.workspaceRoot },
);
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
const cacheKey =
renderableFaviconUrl && props.workspaceRoot
? getProjectFaviconCacheKey(props.environmentId, props.workspaceRoot, renderableFaviconUrl)
: null;
return (
<ProjectFaviconImage
key={faviconUrl}
key={cacheKey}
cacheKey={cacheKey}
faviconUrl={renderableFaviconUrl}
open={props.open}
projectTitle={props.projectTitle}
@@ -39,18 +51,32 @@ export function ProjectFavicon(props: {
}
function ProjectFaviconImage(props: {
readonly cacheKey: string | null;
readonly faviconUrl: string | null;
readonly open?: boolean;
readonly projectTitle: string;
readonly size: number;
}) {
const iconMuted = useThemeColor("--color-icon-subtle");
const faviconRequest = useMemo(
() => createProjectFaviconRequest(props.cacheKey, props.faviconUrl),
[props.cacheKey, props.faviconUrl],
);
const [activeFaviconRequest, setActiveFaviconRequest] = useState<typeof faviconRequest>(null);
useLayoutEffect(() => {
if (faviconRequest === null) return;
const endRequest = beginProjectFaviconRequest(faviconRequest);
setActiveFaviconRequest(faviconRequest);
return endRequest;
}, [faviconRequest]);
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
props.faviconUrl && loadedFaviconUrls.has(props.faviconUrl) ? "loaded" : "loading",
hasLoadedProjectFavicon(props.cacheKey) ? "loaded" : "loading",
);
const showImage = props.faviconUrl !== null && status === "loaded";
const requestIsActive = faviconRequest !== null && activeFaviconRequest === faviconRequest;
const showImage = requestIsActive && status === "loaded";
return (
<View
@@ -72,11 +98,15 @@ function ProjectFaviconImage(props: {
) : null}
{/* Favicon image (hidden until loaded) */}
{props.faviconUrl ? (
{requestIsActive ? (
<Image
key={faviconRequest.faviconUrl}
source={{
uri: props.faviconUrl,
uri: faviconRequest.faviconUrl,
cacheKey: faviconRequest.cacheKey,
}}
cachePolicy="memory-disk"
recyclingKey={faviconRequest.cacheKey}
accessibilityLabel={`${props.projectTitle} favicon`}
style={{
width: props.size,
@@ -86,10 +116,13 @@ function ProjectFaviconImage(props: {
}}
contentFit="contain"
onLoad={() => {
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
if (!markProjectFaviconLoaded(faviconRequest)) return;
setStatus("loaded");
}}
onError={() => setStatus("error")}
onError={() => {
if (!markProjectFaviconFailed(faviconRequest)) return;
setStatus("error");
}}
/>
) : null}
</View>
@@ -0,0 +1,108 @@
import { describe, expect, it } from "vite-plus/test";
import {
beginProjectFaviconRequest,
createProjectFaviconRequest,
hasLoadedProjectFavicon,
markProjectFaviconFailed,
markProjectFaviconLoaded,
} from "./projectFaviconCache";
describe("project favicon cache", () => {
it("ignores callbacks from a superseded URL", () => {
const cacheKey = "environment-1:/workspace:v1-favicon.svg";
const expiredUrl = "https://environment.example/api/assets/expired/v1-favicon.svg";
const refreshedUrl = "https://environment.example/api/assets/refreshed/v1-favicon.svg";
const expiredRequest = createProjectFaviconRequest(cacheKey, expiredUrl);
const endExpiredRequest = beginProjectFaviconRequest(expiredRequest);
markProjectFaviconLoaded(expiredRequest);
const refreshedRequest = createProjectFaviconRequest(cacheKey, refreshedUrl);
const endRefreshedRequest = beginProjectFaviconRequest(refreshedRequest);
expect(markProjectFaviconLoaded(expiredRequest)).toBe(false);
expect(markProjectFaviconFailed(expiredRequest)).toBe(false);
expect(hasLoadedProjectFavicon(cacheKey)).toBe(true);
expect(markProjectFaviconFailed(refreshedRequest)).toBe(true);
expect(hasLoadedProjectFavicon(cacheKey)).toBe(false);
endRefreshedRequest();
endExpiredRequest();
});
it("evicts the URL that actually failed", () => {
const cacheKey = "environment-1:/workspace:v2-favicon.svg";
const faviconUrl = "https://environment.example/api/assets/current/v2-favicon.svg";
const request = createProjectFaviconRequest(cacheKey, faviconUrl);
const endRequest = beginProjectFaviconRequest(request);
markProjectFaviconLoaded(request);
expect(markProjectFaviconFailed(request)).toBe(true);
expect(hasLoadedProjectFavicon(cacheKey)).toBe(false);
endRequest();
});
it("does not supersede a request until the next request begins", () => {
const cacheKey = "environment-1:/workspace:v3-favicon.svg";
const committedUrl = "https://environment.example/api/assets/current/v3-favicon.svg";
const abandonedUrl = "https://environment.example/api/assets/abandoned/v3-favicon.svg";
const committedRequest = createProjectFaviconRequest(cacheKey, committedUrl);
const endCommittedRequest = beginProjectFaviconRequest(committedRequest);
createProjectFaviconRequest(cacheKey, abandonedUrl);
expect(markProjectFaviconLoaded(committedRequest)).toBe(true);
expect(hasLoadedProjectFavicon(cacheKey)).toBe(true);
endCommittedRequest();
});
it("requires a cache key before creating a URL-bearing request", () => {
const firstUrl = "https://environment.example/api/assets/first/favicon.svg";
const secondUrl = "https://environment.example/api/assets/second/favicon.svg";
expect(createProjectFaviconRequest(null, firstUrl)).toBeNull();
expect(createProjectFaviconRequest(null, secondUrl)).toBeNull();
});
it("restores the remaining active URL when a newer request ends", () => {
const cacheKey = "environment-1:/workspace:v4-favicon.svg";
const firstRequest = createProjectFaviconRequest(
cacheKey,
"https://environment.example/api/assets/first/v4-favicon.svg",
);
const secondRequest = createProjectFaviconRequest(
cacheKey,
"https://environment.example/api/assets/second/v4-favicon.svg",
);
const endFirstRequest = beginProjectFaviconRequest(firstRequest);
const endSecondRequest = beginProjectFaviconRequest(secondRequest);
expect(markProjectFaviconLoaded(firstRequest)).toBe(false);
endSecondRequest();
expect(markProjectFaviconLoaded(firstRequest)).toBe(true);
endFirstRequest();
expect(markProjectFaviconLoaded(firstRequest)).toBe(false);
});
it("bounds remembered loaded revisions", () => {
const firstCacheKey = "environment-1:/workspace:revision-0";
let lastCacheKey = firstCacheKey;
for (let revision = 0; revision < 300; revision++) {
lastCacheKey = `environment-1:/workspace:revision-${revision}`;
const request = createProjectFaviconRequest(
lastCacheKey,
`https://environment.example/api/assets/revision-${revision}/favicon.svg`,
);
const endRequest = beginProjectFaviconRequest(request);
markProjectFaviconLoaded(request);
endRequest();
}
expect(hasLoadedProjectFavicon(firstCacheKey)).toBe(false);
expect(hasLoadedProjectFavicon(lastCacheKey)).toBe(true);
});
});
@@ -0,0 +1,94 @@
export interface ProjectFaviconRequest {
readonly cacheKey: string;
readonly faviconUrl: string;
}
interface ActiveFaviconRequests {
readonly urls: Map<string, number>;
currentUrl: string;
}
const MAX_LOADED_FAVICONS = 256;
const activeFaviconRequests = new Map<string, ActiveFaviconRequests>();
const loadedFaviconKeys = new Map<string, true>();
export function createProjectFaviconRequest(
cacheKey: string,
faviconUrl: string,
): ProjectFaviconRequest;
export function createProjectFaviconRequest(
cacheKey: string | null,
faviconUrl: string | null,
): ProjectFaviconRequest | null;
export function createProjectFaviconRequest(cacheKey: string | null, faviconUrl: string | null) {
if (!cacheKey || !faviconUrl) return null;
return { cacheKey, faviconUrl };
}
export function beginProjectFaviconRequest(request: ProjectFaviconRequest) {
let activeRequests = activeFaviconRequests.get(request.cacheKey);
if (!activeRequests) {
activeRequests = { currentUrl: request.faviconUrl, urls: new Map() };
activeFaviconRequests.set(request.cacheKey, activeRequests);
}
const activeCount = activeRequests.urls.get(request.faviconUrl) ?? 0;
activeRequests.urls.delete(request.faviconUrl);
activeRequests.urls.set(request.faviconUrl, activeCount + 1);
activeRequests.currentUrl = request.faviconUrl;
let ended = false;
return () => {
if (ended) return;
ended = true;
const remainingCount = (activeRequests.urls.get(request.faviconUrl) ?? 1) - 1;
if (remainingCount > 0) {
activeRequests.urls.set(request.faviconUrl, remainingCount);
return;
}
activeRequests.urls.delete(request.faviconUrl);
if (activeRequests.urls.size === 0) {
if (activeFaviconRequests.get(request.cacheKey) === activeRequests) {
activeFaviconRequests.delete(request.cacheKey);
}
return;
}
if (activeRequests.currentUrl === request.faviconUrl) {
activeRequests.currentUrl = Array.from(activeRequests.urls.keys()).at(-1)!;
}
};
}
export function hasLoadedProjectFavicon(cacheKey: string | null) {
return cacheKey !== null && loadedFaviconKeys.has(cacheKey);
}
function isCurrentProjectFaviconRequest(request: ProjectFaviconRequest) {
return activeFaviconRequests.get(request.cacheKey)?.currentUrl === request.faviconUrl;
}
function rememberLoadedProjectFavicon(cacheKey: string) {
loadedFaviconKeys.delete(cacheKey);
loadedFaviconKeys.set(cacheKey, true);
if (loadedFaviconKeys.size > MAX_LOADED_FAVICONS) {
loadedFaviconKeys.delete(loadedFaviconKeys.keys().next().value!);
}
}
export function markProjectFaviconLoaded(request: ProjectFaviconRequest) {
if (!isCurrentProjectFaviconRequest(request)) return false;
rememberLoadedProjectFavicon(request.cacheKey);
return true;
}
export function markProjectFaviconFailed(request: ProjectFaviconRequest) {
if (!isCurrentProjectFaviconRequest(request)) return false;
loadedFaviconKeys.delete(request.cacheKey);
return true;
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from "@effect/vitest";
import {
MOBILE_BACKGROUND_RECONNECT_AFTER_MS,
mobileApplicationActiveWakeup,
} from "./app-state-wakeups";
describe("mobileApplicationActiveWakeup", () => {
it("uses a fast probe after a short interruption", () => {
expect(mobileApplicationActiveWakeup(null, 20_000)).toBe("application-active-probe");
expect(
mobileApplicationActiveWakeup(20_000, 20_000 + MOBILE_BACKGROUND_RECONNECT_AFTER_MS - 1),
).toBe("application-active-probe");
});
it("replaces the session after a meaningful background suspension", () => {
expect(
mobileApplicationActiveWakeup(20_000, 20_000 + MOBILE_BACKGROUND_RECONNECT_AFTER_MS),
).toBe("application-active-reconnect");
});
});
@@ -0,0 +1,18 @@
import type { Wakeups } from "@t3tools/client-runtime/connection";
export const MOBILE_BACKGROUND_RECONNECT_AFTER_MS = 10_000;
export type MobileApplicationActiveWakeup = Extract<
Wakeups.ConnectionWakeup,
"application-active-probe" | "application-active-reconnect"
>;
export function mobileApplicationActiveWakeup(
backgroundedAtMs: number | null,
activeAtMs: number,
): MobileApplicationActiveWakeup {
return backgroundedAtMs !== null &&
activeAtMs - backgroundedAtMs >= MOBILE_BACKGROUND_RECONNECT_AFTER_MS
? "application-active-reconnect"
: "application-active-probe";
}
@@ -0,0 +1,92 @@
import type { EnvironmentRpcSubscriptionObservation } from "@t3tools/client-runtime/rpc";
import { type BackgroundScope, type EnvironmentId, WS_METHODS } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
interface RetainedScope {
readonly environmentId: EnvironmentId;
readonly scope: BackgroundScope;
refCount: number;
}
const retainedScopes = new Map<string, RetainedScope>();
const listeners = new Set<() => void>();
function notify(): void {
for (const listener of listeners) {
try {
listener();
} catch {
// A failing observer must not corrupt retained-scope lifetime.
}
}
}
function stableScopeKey(environmentId: EnvironmentId, scope: BackgroundScope): string {
switch (scope.type) {
case "server-config":
case "diagnostics":
return JSON.stringify([environmentId, scope.type]);
case "provider-status":
return JSON.stringify([environmentId, scope.type, scope.instanceId ?? null]);
case "vcs-status":
case "git-refs":
return JSON.stringify([environmentId, scope.type, scope.cwd]);
case "thread":
return JSON.stringify([environmentId, scope.type, scope.threadId]);
}
}
function scopeForSubscription(
observation: EnvironmentRpcSubscriptionObservation,
): BackgroundScope | null {
if (observation.method === WS_METHODS.subscribeResourceTelemetry) {
return { type: "diagnostics" };
}
if (observation.method !== WS_METHODS.subscribeVcsStatus) {
return null;
}
const input = observation.input as { readonly cwd?: unknown };
return typeof input.cwd === "string" ? { type: "vcs-status", cwd: input.cwd } : null;
}
export function retainedMobileBackgroundScopes(
environmentId: EnvironmentId,
): ReadonlyArray<BackgroundScope> {
return Array.from(retainedScopes.values(), (entry) =>
entry.environmentId === environmentId ? entry.scope : null,
).filter((scope): scope is BackgroundScope => scope !== null);
}
export function observeMobileBackgroundActivitySubscription(
observation: EnvironmentRpcSubscriptionObservation,
): Effect.Effect<Effect.Effect<void>> {
const scope = scopeForSubscription(observation);
if (scope === null) return Effect.succeed(Effect.void);
return Effect.sync(() => {
const environmentId = observation.environmentId as EnvironmentId;
const key = stableScopeKey(environmentId, scope);
const current = retainedScopes.get(key);
if (current) {
current.refCount += 1;
} else {
retainedScopes.set(key, { environmentId, scope, refCount: 1 });
notify();
}
return Effect.sync(() => {
const retained = retainedScopes.get(key);
if (!retained) return;
retained.refCount -= 1;
if (retained.refCount <= 0) {
retainedScopes.delete(key);
notify();
}
});
});
}
export function onRetainedMobileBackgroundScopesChange(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
@@ -0,0 +1,77 @@
import { EnvironmentId, WS_METHODS } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import {
onRetainedMobileBackgroundScopesChange,
observeMobileBackgroundActivitySubscription,
retainedMobileBackgroundScopes,
} from "./background-activity-scopes";
describe("mobile background activity", () => {
it.effect("retains VCS demand only while the mobile subscription is active", () =>
Effect.gen(function* () {
const environmentId = EnvironmentId.make("mobile-environment");
const release = yield* observeMobileBackgroundActivitySubscription({
environmentId,
method: WS_METHODS.subscribeVcsStatus,
input: { cwd: "/workspace" },
});
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([
{ type: "vcs-status", cwd: "/workspace" },
]);
yield* release;
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([]);
}),
);
it.effect("keeps delimiter-containing environment and scope values distinct", () =>
Effect.gen(function* () {
const firstEnvironmentId = EnvironmentId.make("a");
const secondEnvironmentId = EnvironmentId.make("a:vcs-status:b");
const releaseFirst = yield* observeMobileBackgroundActivitySubscription({
environmentId: firstEnvironmentId,
method: WS_METHODS.subscribeVcsStatus,
input: { cwd: "b:vcs-status:c" },
});
const releaseSecond = yield* observeMobileBackgroundActivitySubscription({
environmentId: secondEnvironmentId,
method: WS_METHODS.subscribeVcsStatus,
input: { cwd: "c" },
});
expect(retainedMobileBackgroundScopes(firstEnvironmentId)).toEqual([
{ type: "vcs-status", cwd: "b:vcs-status:c" },
]);
expect(retainedMobileBackgroundScopes(secondEnvironmentId)).toEqual([
{ type: "vcs-status", cwd: "c" },
]);
yield* Effect.all([releaseFirst, releaseSecond]);
}),
);
it.effect("returns a release handle when a retained-scope listener throws", () =>
Effect.gen(function* () {
const environmentId = EnvironmentId.make("throwing-listener-environment");
const removeListener = onRetainedMobileBackgroundScopesChange(() => {
throw new Error("listener failed");
});
const release = yield* observeMobileBackgroundActivitySubscription({
environmentId,
method: WS_METHODS.subscribeVcsStatus,
input: { cwd: "/workspace" },
});
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([
{ type: "vcs-status", cwd: "/workspace" },
]);
yield* release;
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([]);
removeListener();
}),
);
});
@@ -0,0 +1,116 @@
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
import { EnvironmentRpcSubscriptionObserver, request } from "@t3tools/client-runtime/rpc";
import {
type BackgroundScope,
type ClientActivityReportInput,
type EnvironmentId,
WS_METHODS,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { AppState, type AppStateStatus } from "react-native";
import * as MobileStorage from "../persistence/mobile-storage";
import {
observeMobileBackgroundActivitySubscription,
onRetainedMobileBackgroundScopesChange,
retainedMobileBackgroundScopes,
} from "./background-activity-scopes";
const REPORT_INTERVAL_MS = 25_000;
const LEASE_TTL_MS = 45_000;
const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
function normalizeAppState(
state: AppStateStatus,
): NonNullable<ClientActivityReportInput["appState"]> {
if (state === "active" || state === "inactive" || state === "background") return state;
return "unknown";
}
export const mobileBackgroundActivityObserverLayer = Layer.succeed(
EnvironmentRpcSubscriptionObserver,
EnvironmentRpcSubscriptionObserver.of({
observe: observeMobileBackgroundActivitySubscription,
}),
);
export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
Effect.gen(function* () {
const registry = yield* EnvironmentRegistry;
const storage = yield* MobileStorage.MobileStorage;
const clientId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.map((deviceId) => `mobile-${deviceId}`),
Effect.orElseSucceed(() => "ephemeral-mobile-client"),
);
const reportRequests = yield* Queue.sliding<void>(1);
const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
let appState = AppState.currentState;
const report = Effect.gen(function* () {
const observedAtMs = yield* Clock.currentTimeMillis;
const active = appState === "active";
const entries = yield* SubscriptionRef.get(registry.entries);
yield* Effect.forEach(
entries.keys(),
(environmentId) =>
registry
.run(
environmentId,
request(WS_METHODS.serverReportClientActivity, {
environmentId: environmentId as EnvironmentId,
clientId,
clientKind: "mobile",
visible: active,
focused: active,
recentlyInteracted: active,
appState: normalizeAppState(appState),
scopes: [
...BASELINE_SCOPES,
...retainedMobileBackgroundScopes(environmentId as EnvironmentId),
],
ttlMs: LEASE_TTL_MS,
observedAt: DateTime.makeUnsafe(observedAtMs),
}),
)
.pipe(Effect.ignore),
{ concurrency: "unbounded", discard: true },
);
}).pipe(Effect.withSpan("mobile.backgroundActivity.report"));
yield* Effect.acquireRelease(
Effect.sync(() => {
const removeScopeListener = onRetainedMobileBackgroundScopesChange(requestReport);
const subscription = AppState.addEventListener("change", (nextState) => {
appState = nextState;
requestReport();
});
return { removeScopeListener, subscription };
}),
({ removeScopeListener, subscription }) =>
Effect.sync(() => {
removeScopeListener();
subscription.remove();
}),
);
yield* SubscriptionRef.changes(registry.entries).pipe(
Stream.runForEach(() => Effect.sync(requestReport)),
Effect.forkScoped,
);
yield* Stream.fromQueue(reportRequests).pipe(
Stream.debounce("250 millis"),
Stream.runForEach(() => report),
Effect.forkScoped,
);
yield* Effect.sync(requestReport).pipe(
Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)),
Effect.forkScoped,
);
}),
);
@@ -42,6 +42,12 @@ function makeDatabase() {
removed.push(id);
values.delete(id);
}),
clearCacheKind: (environmentId, kind) =>
Effect.sync(() => {
for (const key of values.keys()) {
if (key.startsWith(`${environmentId}:${kind}:`)) values.delete(key);
}
}),
clearEnvironmentCache: (environmentId) =>
Effect.sync(() => {
for (const key of values.keys()) {
@@ -80,6 +86,36 @@ describe("mobile SQLite environment cache store", () => {
}),
);
it.effect("removes one persisted VCS ref snapshot", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
yield* store.removeVcsRefs(ENVIRONMENT_ID, "/repo");
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(memory.removed).toContain(cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo"));
}),
);
it.effect("clears every persisted VCS ref snapshot in one environment", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
const otherEnvironmentId = EnvironmentId.make("environment-2");
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo-worktree", REFS);
yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
yield* store.clearVcsRefs(ENVIRONMENT_ID);
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo-worktree")).toEqual(Option.none());
expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
}),
);
it.effect("clears one environment without touching another", () =>
Effect.gen(function* () {
const memory = makeDatabase();
@@ -223,6 +223,16 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
.pipe(Effect.mapError(mapDatabaseError("save-vcs-refs")));
},
),
removeVcsRefs: Effect.fn("MobileEnvironmentCache.removeVcsRefs")((environmentId, cwd) =>
database
.removeCache(environmentId, "vcs-refs", cwd)
.pipe(Effect.mapError(mapDatabaseError("remove-vcs-refs"))),
),
clearVcsRefs: Effect.fn("MobileEnvironmentCache.clearVcsRefs")((environmentId) =>
database
.clearCacheKind(environmentId, "vcs-refs")
.pipe(Effect.mapError(mapDatabaseError("clear-vcs-refs"))),
),
clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
database
.clearEnvironmentCache(environmentId)
+39 -12
View File
@@ -30,6 +30,7 @@ import * as MobileStorage from "../persistence/mobile-storage";
import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
import { connectionStorageLayer } from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
@@ -54,27 +55,53 @@ const connectivityLayer = Connectivity.layer({
),
changes: Stream.callback((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
Network.addNetworkStateListener((state) => {
Effect.sync(() => {
let active = true;
const networkSubscription = Network.addNetworkStateListener((state) => {
Queue.offerUnsafe(queue, networkStatus(state));
}),
),
(subscription) => Effect.sync(() => subscription.remove()),
});
const appStateSubscription = AppState.addEventListener("change", (state) => {
if (state !== "active") {
return;
}
void Network.getNetworkStateAsync()
.then((current) => {
if (active) {
Queue.offerUnsafe(queue, networkStatus(current));
}
})
.catch(() => undefined);
});
return {
close: () => {
active = false;
networkSubscription.remove();
appStateSubscription.remove();
},
};
}),
({ close }) => Effect.sync(close),
).pipe(Effect.asVoid),
),
});
const wakeupsLayer = Wakeups.layer({
changes: Stream.merge(
Stream.callback<"application-active">((queue) =>
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
AppState.addEventListener("change", (state) => {
if (state === "active") {
Queue.offerUnsafe(queue, "application-active");
Effect.sync(() => {
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
return AppState.addEventListener("change", (state) => {
if (state === "background") {
backgroundedAtMs = Date.now();
return;
}
}),
),
if (state === "active") {
Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));
backgroundedAtMs = null;
}
});
}),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
+19 -3
View File
@@ -5,6 +5,10 @@ import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
import { runtimeContextLayer } from "../lib/runtime";
import {
mobileBackgroundActivityObserverLayer,
mobileBackgroundActivityReporterLayer,
} from "./background-activity";
import { connectionPlatformLayer } from "./platform";
const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
@@ -17,10 +21,22 @@ type ConnectionLayerSource =
| typeof Connection.layer
| typeof snapshotLoaderLayer
| typeof runtimeContextLayer
| typeof connectionPlatformLayer;
| typeof connectionPlatformLayer
| typeof mobileBackgroundActivityObserverLayer
| typeof mobileBackgroundActivityReporterLayer;
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
const providedClientConnectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
Layer.provideMerge(
Layer.mergeAll(
runtimeContextLayer,
providedConnectionPlatformLayer,
mobileBackgroundActivityObserverLayer,
),
),
);
const connectionLayer = mobileBackgroundActivityReporterLayer.pipe(
Layer.provideMerge(providedClientConnectionLayer),
);
export const connectionAtomRuntime: Atom.AtomRuntime<
@@ -29,7 +29,10 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import {
createNativeMailSearchToolbarItem,
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
} from "../layout/native-mail-search-toolbar";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
export interface ArchivedThreadsHeaderEnvironment {
@@ -70,7 +73,8 @@ function ArchivedThreadsHeader(props: {
const searchIconColor = useThemeColor("--color-icon");
const searchTextColor = useThemeColor("--color-foreground");
const usesNativeChrome = Platform.OS === "ios";
const usesCompactMailToolbar = Platform.OS === "ios" && width < 700;
const usesCompactMailToolbar =
Platform.OS === "ios" && width < 700 && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
const androidFilterActions = useMemo<MenuAction[]>(
() => [
{
@@ -272,7 +276,11 @@ function ArchivedThreadsHeader(props: {
...(usesNativeChrome
? {
allowToolbarIntegration: true,
placement: "integratedButton" as const,
// "integratedButton" is an iOS 26 search-bar placement;
// pre-glass iOS keeps the default pull-down placement.
...(NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED
? { placement: "integratedButton" as const }
: null),
}
: {
placement: "stacked" as const,
@@ -1,120 +0,0 @@
import { useWaitlist } from "@clerk/expo";
import { ActivityIndicator, Pressable, Text, TextInput, View } from "react-native";
import { useState } from "react";
import { cn } from "../../lib/cn";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
const { errors, fetchStatus, waitlist } = useWaitlist();
const [emailAddress, setEmailAddress] = useState("");
const [requestError, setRequestError] = useState<string | null>(null);
const isSubmitting = fetchStatus === "fetching";
const fieldError = errors.fields.emailAddress?.longMessage;
const joinWaitlist = async () => {
const normalizedEmailAddress = emailAddress.trim();
if (!normalizedEmailAddress || isSubmitting) {
return;
}
setRequestError(null);
try {
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
} catch (error) {
console.error(error);
setRequestError(
error instanceof CloudWaitlistJoinRejectedError
? "Could not join the waitlist. Check your email address and try again."
: "Could not join the waitlist. Check your connection and try again.",
);
}
};
if (waitlist.id) {
return (
<View className="gap-[18px]">
<Text className="text-center font-t3-bold text-xl text-foreground">
You are on the waitlist
</Text>
<Text className="text-center font-sans text-base text-foreground-secondary">
We will email you when your T3 Connect access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
</View>
);
}
return (
<View className="gap-[18px]">
<Text className="font-sans text-base text-foreground-secondary">
Enter your email and we will let you know when access is ready.
</Text>
<View className="gap-2">
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
<TextInput
accessibilityLabel="Email address"
autoCapitalize="none"
autoComplete="email"
autoCorrect={false}
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-4 py-3.5 font-sans text-lg text-foreground border-continuous",
(fieldError || requestError) && "border-danger-foreground",
)}
keyboardType="email-address"
onChangeText={(value) => {
setEmailAddress(value);
setRequestError(null);
}}
onSubmitEditing={() => void joinWaitlist()}
placeholder="Enter your email address"
placeholderTextColorClassName="accent-placeholder"
returnKeyType="join"
textContentType="emailAddress"
value={emailAddress}
/>
{fieldError || requestError ? (
<Text
accessibilityLiveRegion="polite"
className="font-sans text-sm text-danger-foreground"
selectable
>
{fieldError ?? requestError}
</Text>
) : null}
</View>
<Pressable
accessibilityRole="button"
accessibilityState={{
busy: isSubmitting,
disabled: isSubmitting || emailAddress.trim().length === 0,
}}
disabled={isSubmitting || emailAddress.trim().length === 0}
onPress={() => void joinWaitlist()}
className="min-h-[54px] flex-row items-center justify-center gap-2 rounded-full bg-primary px-5 py-3 disabled:opacity-[0.45]"
>
{isSubmitting ? (
<ActivityIndicator colorClassName="accent-primary-foreground" size="small" />
) : null}
<Text className="font-t3-bold text-base text-primary-foreground">
{isSubmitting ? "Joining" : "Join the waitlist"}
</Text>
</Pressable>
<SignInAction onPress={props.onSignIn} />
</View>
);
}
function SignInAction(props: { readonly onPress: () => void }) {
return (
<View className="flex-row items-center justify-center gap-1 pt-1">
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
</Pressable>
</View>
);
}
@@ -1,48 +0,0 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
CloudWaitlistJoinRejectedError,
CloudWaitlistJoinRequestError,
joinCloudWaitlist,
} from "./cloudWaitlistJoin";
describe("joinCloudWaitlist", () => {
it("submits the provided email address", async () => {
const join = vi.fn().mockResolvedValue({ error: null });
await joinCloudWaitlist({ join }, "[email protected]");
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
});
it("preserves Clerk rejection details without exposing the email address", async () => {
const cause = Object.assign(new Error("The enrollment was rejected."), {
code: "form_identifier_invalid",
});
const join = vi.fn().mockResolvedValue({ error: cause });
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
expect(failure).toMatchObject({
code: "form_identifier_invalid",
cause,
});
expect(String(failure)).not.toContain("[email protected]");
});
it("distinguishes request failures from rejected enrollments", async () => {
const cause = new Error("network unavailable");
const join = vi.fn().mockRejectedValue(cause);
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
expect(failure).toMatchObject({ cause });
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
});
});
@@ -1,46 +0,0 @@
import * as Schema from "effect/Schema";
interface CloudWaitlistJoiner {
readonly join: (input: { emailAddress: string }) => Promise<{
readonly error: { readonly code: string } | null;
}>;
}
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
"CloudWaitlistJoinRejectedError",
{
code: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
}
}
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
"CloudWaitlistJoinRequestError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Cloud waitlist enrollment request failed.";
}
}
export async function joinCloudWaitlist(
waitlist: CloudWaitlistJoiner,
emailAddress: string,
): Promise<void> {
const result = await waitlist.join({ emailAddress }).catch((cause) => {
throw new CloudWaitlistJoinRequestError({ cause });
});
if (result.error) {
throw new CloudWaitlistJoinRejectedError({
code: result.error.code,
cause: result.error,
});
}
}
@@ -134,7 +134,14 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
case "RelayEnvironmentLinkProofInvalidError":
return `Relay rejected the environment link proof (${error.reason}).`;
case "RelayEnvironmentConnectNotAuthorizedError":
return "Relay rejected the environment connection request.";
// "Not authorized" covers non-auth causes too; surface the reason so a
// missing link doesn't read as a credential problem.
if (error.reason === "environment_link_not_found") {
return "Relay has no active link for this environment. The environment server may not have re-established its link yet.";
}
return error.reason
? `Relay rejected the environment connection request (${error.reason}).`
: "Relay rejected the environment connection request.";
case "RelayEnvironmentEndpointUnavailableError":
return `Relay could not reach the environment endpoint (${error.reason}).`;
case "RelayEnvironmentEndpointTimedOutError":
@@ -24,13 +24,7 @@ import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironment
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
/**
* "T3 Connect" section: every environment published to the signed-in account,
* with connect switches, availability status, refresh, and loading/error
* states. Shared between the Settings environments screen and the T3 Connect
* onboarding sheet.
*/
export function CloudEnvironmentRows(props: {
interface CloudEnvironmentRowsProps {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
@@ -41,8 +35,31 @@ export function CloudEnvironmentRows(props: {
* pull-to-refresh).
*/
readonly showHeader?: boolean;
}) {
}
/**
* "T3 Connect" section: every environment published to the signed-in account,
* with connect switches, availability status, refresh, and loading/error
* states. Shared between the Settings environments screen and the T3 Connect
* onboarding sheet.
*/
export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
// Showcase captures run without a Clerk publishable key, so `ClerkProvider`
// is never mounted and any `useAuth` call throws — the fixture states whether
// the rows are signed in instead of asking Clerk.
if (props.showcaseSignedIn !== undefined) {
return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
}
return <SignedInCloudEnvironmentRows {...props} />;
}
function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
if (!isSignedIn) return null;
return <CloudEnvironmentRowsContent {...props} />;
}
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments =
@@ -67,8 +84,6 @@ export function CloudEnvironmentRows(props: {
const showHeader = props.showHeader ?? true;
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
return (
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
{showHeader ? (
@@ -1,11 +1,32 @@
import { describe, expect, it } from "vite-plus/test";
import {
buildPairingUrl,
extractPairingUrlFromQrPayload,
PairingQrPayloadEmptyError,
parsePairingUrl,
} from "./pairing";
describe("buildPairingUrl", () => {
it("uses HTTP for a schemeless IP address", () => {
expect(buildPairingUrl("192.168.1.100:3773", "pairing-token")).toBe(
"http://192.168.1.100:3773/#token=pairing-token",
);
});
it("keeps HTTPS as the default for a schemeless hostname", () => {
expect(buildPairingUrl("remote.example.com", "pairing-token")).toBe(
"https://remote.example.com/#token=pairing-token",
);
});
it("preserves an explicit scheme for an IP address", () => {
expect(buildPairingUrl("https://192.168.1.100:3773", "pairing-token")).toBe(
"https://192.168.1.100:3773/#token=pairing-token",
);
});
});
describe("extractPairingUrlFromQrPayload", () => {
it("trims raw pairing urls from qr payloads", () => {
expect(
+16 -1
View File
@@ -3,6 +3,21 @@ import * as Schema from "effect/Schema";
const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
function isIpLiteral(host: string): boolean {
try {
const hostname = new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, "");
if (hostname.includes(":")) return true;
const octets = hostname.split(".");
return (
octets.length === 4 &&
octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)
);
} catch {
return false;
}
}
export class PairingQrPayloadEmptyError extends Schema.TaggedErrorClass<PairingQrPayloadEmptyError>()(
"PairingQrPayloadEmptyError",
{},
@@ -19,7 +34,7 @@ export function buildPairingUrl(host: string, code: string): string {
if (!c) return h;
try {
const url = new URL(h.includes("://") ? h : `https://${h}`);
const url = new URL(h.includes("://") ? h : `${isIpLiteral(h) ? "http" : "https"}://${h}`);
url.hash = new URLSearchParams([["token", c]]).toString();
return url.toString();
} catch {
@@ -29,7 +29,10 @@ import {
useAdaptiveWorkspacePaneRole,
useRegisterWorkspaceInspector,
} from "../layout/AdaptiveWorkspaceLayout";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import {
createNativeMailSearchToolbarItem,
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
} from "../layout/native-mail-search-toolbar";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
@@ -354,7 +357,8 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
);
}
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
const usesCompactMailToolbar =
Platform.OS === "ios" && !layout.usesSplitView && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
return (
<>
+63 -67
View File
@@ -1,7 +1,6 @@
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import Constants from "expo-constants";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useMemo, useRef } from "react";
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
@@ -11,11 +10,16 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ControlPillMenu } from "../../components/ControlPill";
import { SymbolView } from "../../components/AppSymbol";
import { T3Wordmark } from "../../components/T3Wordmark";
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
import { resolveMobileStageLabel } from "../../lib/mobileBranding";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom } from "../../state/preferences";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import {
createNativeMailSearchToolbarItem,
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
} from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
buildHomeListFilterMenu,
@@ -59,21 +63,15 @@ function checkedMenuState(checked: boolean) {
return checked ? ("on" as const) : undefined;
}
/** Thread List v2 lays the list out in fixed creation order, so the
sort/group filter controls would be silently ignored — hide them and
key the "customized" icon state off the environment filter alone. */
function useThreadListV2FilterGate() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
return (
AsyncResult.isSuccess(preferencesResult) && preferencesResult.value.threadListV2Enabled === true
);
}
function AndroidHomeHeader(props: HomeHeaderProps) {
const insets = useSafeAreaInsets();
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const threadListV2Enabled = useThreadListV2FilterGate();
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
// Thread List v2 lays the list out in fixed creation order, so the
// sort/group filter controls would be silently ignored — hide them and
// key the "customized" icon state off the environment filter alone.
const threadListV2Enabled = useThreadListV2Enabled();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
@@ -201,8 +199,9 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<View
className="border-b border-header-border bg-header px-4 pb-3"
className="border-b border-header-border bg-header pb-3"
style={{
paddingHorizontal: HOME_HORIZONTAL_INSET,
paddingTop: Math.max(insets.top, 12),
}}
>
@@ -216,7 +215,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
Alpha
{stageLabel}
</RNText>
</View>
</View>
@@ -291,7 +290,10 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
function IosHomeHeader(props: HomeHeaderProps) {
const searchBarRef = useRef<SearchBarCommands>(null);
const iconColor = useThemeColor("--color-icon");
const threadListV2Enabled = useThreadListV2FilterGate();
// Thread List v2 lays the list out in fixed creation order, so the
// sort/group filter controls would be silently ignored — hide them and
// key the "customized" icon state off the environment filter alone.
const threadListV2Enabled = useThreadListV2Enabled();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
@@ -326,9 +328,11 @@ function IosHomeHeader(props: HomeHeaderProps) {
}),
]
: undefined,
unstable_headerToolbarItems:
Platform.OS === "ios"
? () => [
// The keys below are set per-branch (not `undefined`) so a later
// reapply cannot clobber options owned by NativeHeaderToolbar.
...(NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED
? {
unstable_headerToolbarItems: () => [
createNativeMailSearchToolbarItem({
composeButtonId: "home-new-task",
composeSystemImageName: "square.and.pencil",
@@ -342,14 +346,14 @@ function IosHomeHeader(props: HomeHeaderProps) {
placeholder: "Search",
searchTextChangeId: "home-search-text",
}),
]
: undefined,
headerSearchBarOptions:
Platform.OS === "ios"
? undefined
: {
],
}
: {
// Pre-Liquid-Glass iOS: standard pull-down search in the nav
// bar; create + sort live in the plain bottom toolbar below.
headerSearchBarOptions: {
ref: searchBarRef,
allowToolbarIntegration: true,
autoCapitalize: "none" as const,
hideNavigationBar: false,
placeholder: "Search",
onCancelButtonPress: () => {
@@ -359,21 +363,11 @@ function IosHomeHeader(props: HomeHeaderProps) {
props.onSearchQueryChange(event.nativeEvent.text);
},
},
}),
}}
/>
{Platform.OS === "ios" ? null : (
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
accessibilityLabel="Open settings"
icon="gearshape"
onPress={props.onOpenSettings}
separateBackground
/>
</NativeHeaderToolbar>
)}
{Platform.OS === "ios" ? null : (
{NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED ? null : (
<NativeHeaderToolbar placement="bottom">
<NativeHeaderToolbar.Menu
accessibilityLabel="Filter and sort threads"
@@ -427,35 +421,37 @@ function IosHomeHeader(props: HomeHeaderProps) {
</NativeHeaderToolbar.Menu>
) : null}
<NativeHeaderToolbar.Menu title="Sort projects">
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
{threadListV2Enabled ? null : (
<NativeHeaderToolbar.Menu title="Sort projects">
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
)}
<NativeHeaderToolbar.Menu title="Sort threads">
<NativeHeaderToolbar.Label>Sort threads</NativeHeaderToolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
{threadListV2Enabled ? null : (
<NativeHeaderToolbar.Menu title="Sort threads">
<NativeHeaderToolbar.Label>Sort threads</NativeHeaderToolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
)}
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
<NativeHeaderToolbar.SearchBarSlot />
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
<NativeHeaderToolbar.Spacer flexible />
<NativeHeaderToolbar.Button
accessibilityLabel="New task"
icon="square.and.pencil"
@@ -3,6 +3,7 @@ import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
@@ -11,6 +12,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
import { HomeScreen } from "./HomeScreen";
import { HomeHeader } from "./HomeHeader";
@@ -25,28 +27,35 @@ export function HomeRouteScreen() {
const { layout } = useAdaptiveWorkspaceLayout();
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const navigation = useNavigation();
const [searchQuery, setSearchQuery] = useState("");
useEffect(() => {
void checkForAppUpdateOnLaunch();
}, []);
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(
Order.String,
(environment: { readonly label: string }) => environment.label,
),
const environments = useMemo(() => {
const connectionStateByEnvironmentId = new Map(
workspaceEnvironments.map(
(environment) => [environment.environmentId, environment.connectionState] as const,
),
[savedConnectionsById],
);
);
return Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
connectionState:
connectionStateByEnvironmentId.get(connection.environmentId) ?? "available",
})),
Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label),
);
}, [savedConnectionsById, workspaceEnvironments]);
const availableEnvironmentIds = useMemo(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
@@ -85,7 +94,9 @@ export function HomeRouteScreen() {
if (layout.usesSplitView) {
return (
<>
<NativeStackScreenOptions options={{ title: "", headerTitle: "" }} />
<NativeStackScreenOptions
options={{ title: "", headerTitle: "", unstable_headerLeftItems: () => [] }}
/>
<WorkspaceSidebarToolbar
afterSidebarButton={
<NativeHeaderToolbar.Button
@@ -107,8 +118,8 @@ export function HomeRouteScreen() {
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
>
<>
{/* Restore the compact title in case the split branch blanked it. */}
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
{/* Restore the compact title after the split branch blanks the detail header. */}
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
<HomeHeader
environments={environments}
projects={projectFilterOptions}
+209 -102
View File
@@ -7,6 +7,10 @@ import {
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
threadSearchMatchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
@@ -22,11 +26,13 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import { environmentServerConfigsAtom } from "../../state/server";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
@@ -35,12 +41,13 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "../threads/thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
type ThreadListV2Item,
type ThreadListV2ListItem,
} from "../threads/threadListV2";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
@@ -70,7 +77,9 @@ interface HomeScreenProps {
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
readonly environments: ReadonlyArray<
HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
>;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
@@ -100,6 +109,7 @@ interface HomeScreenProps {
/* ─── Layout constants ───────────────────────────────────────────────── */
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
/**
* Top spacing between the list and the Android custom header. The Android
* header (AndroidHomeHeader) is rendered in-flow above this screen and
@@ -181,14 +191,45 @@ export function HomeScreen(props: HomeScreenProps) {
ReadonlyMap<string, HomeGroupDisplayState>
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled =
AsyncResult.isSuccess(preferencesResult) &&
preferencesResult.value.threadListV2Enabled === true;
const threadListV2Enabled = useThreadListV2Enabled();
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const iosBottomToolbarClearance =
Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
? PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT
: 0;
const searchEnvironmentIds = useMemo(
() =>
props.selectedEnvironmentId === null
? props.environments
.filter((environment) => environment.connectionState === "connected")
.map((environment) => environment.environmentId)
: props.environments.some(
(environment) =>
environment.environmentId === props.selectedEnvironmentId &&
environment.connectionState === "connected",
)
? [props.selectedEnvironmentId]
: [],
[props.environments, props.selectedEnvironmentId],
);
const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
const threadSearchMatchByKey = useMemo(() => {
const matches = new Map<string, EnvironmentThreadSearchMatch>();
for (const match of threadSearch.matches) {
if (match.source === "user" || match.source === "assistant") {
matches.set(threadSearchMatchKey(match), match);
}
}
return matches;
}, [threadSearch.matches]);
const matchedThreadKeys = useMemo(
() => new Set(threadSearch.matches.map(threadSearchMatchKey)),
[threadSearch.matches],
);
const effectiveGroupDisplayStates = useMemo(() => {
const next = new Map(groupDisplayStates);
if (!AsyncResult.isSuccess(preferencesResult)) {
@@ -318,6 +359,7 @@ export function HomeScreen(props: HomeScreenProps) {
pendingTasks: scopedPendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
matchedThreadKeys,
projectSortOrder: props.projectSortOrder,
threadSortOrder: props.threadSortOrder,
projectGroupingMode: props.projectGroupingMode,
@@ -328,6 +370,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.selectedEnvironmentId,
props.threadSortOrder,
matchedThreadKeys,
scopedPendingTasks,
scopedProjects,
scopedThreads,
@@ -516,6 +559,7 @@ export function HomeScreen(props: HomeScreenProps) {
environmentId: props.selectedEnvironmentId,
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -533,6 +577,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.selectedEnvironmentId,
props.threads,
matchedThreadKeys,
threadListV2Enabled,
v2ScopedProjectGroup,
]);
@@ -550,50 +595,107 @@ export function HomeScreen(props: HomeScreenProps) {
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const threadListV2Items = threadListV2Layout.items;
// Queued tasks are not thread shells, so the v2 partition never sees them;
// they are spliced in below the active block and stay visible and deletable
// while their environment is offline. Same environment scope and search
// filter as the list itself.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = useMemo(
() =>
props.pendingTasks.filter(
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProjectKeys === null ||
v2ScopedProjectKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 ||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
),
[props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
);
const threadListV2Items = useMemo(
() =>
buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
}),
[threadListV2Layout.items, v2PendingTasks],
);
const renderV2Item = useCallback(
({ item }: { readonly item: ThreadListV2Item }) => (
<ThreadListV2Row
thread={item.thread}
variant={item.variant}
showSettledDivider={item.showSettledDivider}
project={
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
null
}
projectTitle={v2ProjectTitleByProjectKey.get(
scopedProjectKey(item.thread.environmentId, item.thread.projectId),
)}
providerDriver={
serverConfigs
.get(item.thread.environmentId)
?.providers.find(
(provider) =>
provider.instanceId ===
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
: null
}
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
settlementSupported={settlementEnvironmentIds.has(item.thread.environmentId)}
onSettleThread={handleSettleThread}
onUnsettleThread={handleUnsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
null
}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
),
({ item }: { readonly item: ThreadListV2ListItem }) => {
if (item.type === "v2-pending") {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
item.pendingTask.creation.projectId,
);
return (
<ThreadListV2PendingRow
pendingTask={item.pendingTask}
project={projectByKey.get(pendingScopeKey) ?? null}
projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null)
: null
}
showPendingDivider={item.showPendingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
);
}
const thread = item.item.thread;
return (
<ThreadListV2Row
thread={thread}
variant={item.item.variant}
showSettledDivider={item.item.showSettledDivider}
project={
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
projectTitle={v2ProjectTitleByProjectKey.get(
scopedProjectKey(thread.environmentId, thread.projectId),
)}
providerDriver={
serverConfigs
.get(thread.environmentId)
?.providers.find(
(provider) =>
provider.instanceId ===
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
: null
}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
onUnsettleThread={handleUnsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
);
},
[
handleChangeRequestState,
handleDeleteThread,
@@ -604,21 +706,51 @@ export function HomeScreen(props: HomeScreenProps) {
projectByKey,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
serverConfigs,
settlementEnvironmentIds,
threadSearchMatchByKey,
v2ProjectTitleByProjectKey,
props.searchQuery,
],
);
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
// FlatList treats a changed extraData identity as "re-render every visible
// row", so an inline object literal would invalidate all rows on every
// HomeScreen render.
const v2ExtraData = useMemo(
() => ({
projectByKey,
projectCwdByKey,
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
searchQuery: props.searchQuery,
threadSearchMatchByKey,
}),
[
projectByKey,
projectCwdByKey,
props.searchQuery,
props.savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
v2ProjectTitleByProjectKey,
],
);
const v2KeyExtractor = useCallback(
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
[],
);
const extraData = useMemo(
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
[props.savedConnectionsById, projectCwdByKey],
() => ({
projectCwdByKey,
savedConnectionsById: props.savedConnectionsById,
searchQuery: props.searchQuery,
threadSearchMatchByKey,
}),
[projectCwdByKey, props.savedConnectionsById, props.searchQuery, threadSearchMatchByKey],
);
const renderItem = useCallback(
@@ -671,6 +803,13 @@ export function HomeScreen(props: HomeScreenProps) {
null
}
isLast={item.isLast}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onSelectThread={props.onSelectThread}
@@ -701,7 +840,9 @@ export function HomeScreen(props: HomeScreenProps) {
props.onNewThreadInProject,
props.onSelectPendingTask,
props.onSelectThread,
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
updateGroupDisplay,
],
);
@@ -741,7 +882,7 @@ export function HomeScreen(props: HomeScreenProps) {
<View
className="flex-1 items-center justify-center bg-screen px-8"
style={{
paddingBottom: Math.max(insets.bottom, 24),
paddingBottom: Math.max(insets.bottom, 24) + iosBottomToolbarClearance,
paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
}}
>
@@ -789,44 +930,12 @@ export function HomeScreen(props: HomeScreenProps) {
</>
);
// v2 renders queued offline tasks above the thread cards — they are not
// thread shells, so the v2 item builder never sees them, but they must
// stay visible and deletable while their environment is offline. They
// respect the same environment scope and search filter as the list.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = props.pendingTasks.filter(
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProjectKeys === null ||
v2ScopedProjectKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
// Project scoping lives in the header filter menu (no inline chip row on
// mobile — the menu is the one filter surface).
const v2ListHeader = (
<>
{listHeader}
{v2PendingTasks.map((pendingTask, index) => (
<PendingTaskListRow
key={pendingTask.message.messageId}
variant="compact"
pendingTask={pendingTask}
environmentLabel={
props.savedConnectionsById[pendingTask.message.environmentId]?.environmentLabel ?? null
}
isLast={index === v2PendingTasks.length - 1}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
))}
</>
);
const v2ListHeader = listHeader;
const listEmpty = !hasResults ? (
hasSearchQuery ? (
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : selectedProjectScope !== null ? (
<EmptyState
@@ -847,11 +956,10 @@ export function HomeScreen(props: HomeScreenProps) {
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Snoozed threads outrank the rest: "No
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss. Pending tasks render in the header, so the list showing them
// isn't empty in the user's eyes.
// loss.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
hasSearchQuery && threadSearch.isPending && v2SnoozedCount === 0 ? null : hasSearchQuery ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
@@ -887,11 +995,7 @@ export function HomeScreen(props: HomeScreenProps) {
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={{
projectByKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
}}
extraData={v2ExtraData}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
@@ -920,7 +1024,7 @@ export function HomeScreen(props: HomeScreenProps) {
contentContainerStyle={{
paddingBottom:
Platform.OS === "ios"
? Math.max(insets.bottom, 24) + 96
? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
: Math.max(insets.bottom, 16) + 88,
}}
/>
@@ -961,16 +1065,19 @@ export function HomeScreen(props: HomeScreenProps) {
scrollEventThrottle={16}
contentContainerStyle={{
// Android reserves room for the floating new-task FAB
// (56 button + 16 gap + bottom inset).
// (56 button + 16 gap + bottom inset). Pre-glass iOS shows a
// standard 44pt bottom toolbar that overlays the list and is not
// reflected in insets while contentInsetAdjustmentBehavior is
// "never".
paddingBottom:
Platform.OS === "ios"
? Math.max(insets.bottom, 24) + 24
? Math.max(insets.bottom, 24) + 24 + iosBottomToolbarClearance
: Math.max(insets.bottom, 16) + 88,
}}
scrollIndicatorInsets={
Platform.OS === "ios"
? {
bottom: Math.max(insets.bottom, 16) + 24,
bottom: Math.max(insets.bottom, 16) + 24 + iosBottomToolbarClearance,
top: 0,
}
: undefined
@@ -2,6 +2,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -661,6 +662,33 @@ describe("buildHomeThreadGroups", () => {
);
});
it("includes a thread matched by message content", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const thread = makeThread({
environmentId,
id: ThreadId.make("thread-content"),
projectId: project.id,
title: "Unrelated title",
});
const groups = buildGroups([project], [thread], {
searchQuery: "relay reconnect",
matchedThreadKeys: new Set([
threadSearchMatchKey({
environmentId,
threadId: thread.id,
}),
]),
});
expect(groups[0]?.threads.map((candidate) => candidate.id)).toEqual(["thread-content"]);
});
it("targets quick new threads at the group member with the newest thread", () => {
const laptopEnv = EnvironmentId.make("environment-laptop");
const desktopEnv = EnvironmentId.make("environment-desktop");
@@ -12,6 +12,7 @@ import {
sortThreads,
toSortableTimestamp,
} from "@t3tools/client-runtime/state/thread-sort";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import type {
EnvironmentId,
ScopedProjectRef,
@@ -254,6 +255,7 @@ export function buildHomeThreadGroups(input: {
readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly matchedThreadKeys?: ReadonlySet<string>;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
@@ -350,7 +352,16 @@ export function buildHomeThreadGroups(input: {
group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
const matchingThreads = groupMatches
? group.threads
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
: group.threads.filter(
(thread) =>
thread.title.toLocaleLowerCase().includes(query) ||
input.matchedThreadKeys?.has(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
) === true,
);
const matchingPendingTasks = groupMatches
? group.pendingTasks
: group.pendingTasks.filter((pendingTask) =>
@@ -1,5 +1,16 @@
import type { HeaderBarButtonMailSearchToolbarItem } from "react-native-screens";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
/**
* The patched mail-style toolbar is built natively from iOS 26 Liquid Glass
* UIKit (`UIGlassEffect`) with no earlier fallback: pre-26 the native side
* silently drops the item and hides the navigation toolbar entirely. Screens
* that send it must fall back to standard search/toolbar primitives when this
* is false.
*/
export const NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED = NATIVE_LIQUID_GLASS_SUPPORTED;
type NativeMailSearchToolbarInput = Omit<
HeaderBarButtonMailSearchToolbarItem,
"type" | "useFallbackSearchField"
@@ -0,0 +1,41 @@
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
const ENVIRONMENT_A = EnvironmentId.make("environment-a");
const ENVIRONMENT_B = EnvironmentId.make("environment-b");
function environment(environmentId: EnvironmentId, connectionState: EnvironmentConnectionPhase) {
return { environmentId, connectionState };
}
describe("resolveAddProjectEnvironment", () => {
it("does not redirect an explicit unavailable environment to another environment", () => {
expect(
resolveAddProjectEnvironment(
[environment(ENVIRONMENT_A, "offline"), environment(ENVIRONMENT_B, "connected")],
ENVIRONMENT_A,
),
).toBeNull();
});
it("resolves an explicit connected environment", () => {
expect(
resolveAddProjectEnvironment(
[environment(ENVIRONMENT_A, "connected"), environment(ENVIRONMENT_B, "connected")],
ENVIRONMENT_A,
)?.environmentId,
).toBe(ENVIRONMENT_A);
});
it("defaults to the first connected environment when no environment is requested", () => {
expect(
resolveAddProjectEnvironment(
[environment(ENVIRONMENT_A, "offline"), environment(ENVIRONMENT_B, "connected")],
null,
)?.environmentId,
).toBe(ENVIRONMENT_B);
});
});
@@ -0,0 +1,26 @@
import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
export function resolveAddProjectEnvironment<
T extends {
readonly environmentId: EnvironmentId;
readonly connectionState: EnvironmentConnectionPhase;
},
>(environmentOptions: ReadonlyArray<T>, requestedEnvironmentId: EnvironmentId | null): T | null {
if (requestedEnvironmentId !== null) {
return (
environmentOptions.find(
(environment) =>
environment.environmentId === requestedEnvironmentId &&
canCreateProjectInEnvironment(environment.connectionState),
) ?? null
);
}
return (
environmentOptions.find((environment) =>
canCreateProjectInEnvironment(environment.connectionState),
) ?? null
);
}
@@ -4,27 +4,32 @@ import {
addProjectRemoteSourceProvider,
buildAddProjectRemoteSourceReadiness,
buildProjectCreateCommand,
canCreateProjectInEnvironment,
findExistingAddProject,
getAddProjectInitialQuery,
resolveAddProjectPath,
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime/operations/projects";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import {
canPreloadBrowsePath,
createBrowseNavigationCoordinator,
filterFilesystemBrowseEntries,
getFilesystemBrowsePath,
} from "@t3tools/client-runtime/state/filesystem";
import {
appendBrowsePathSegment,
canNavigateUp,
ensureBrowseDirectoryPath,
getBrowseDirectoryPath,
getBrowseLeafPathSegment,
getBrowseParentPath,
hasTrailingPathSeparator,
inferProjectTitleFromPath,
isFilesystemBrowseQuery,
} from "@t3tools/client-runtime/state/projects";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { StackActions, useNavigation } from "@react-navigation/native";
import { SymbolView } from "../../components/AppSymbol";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
@@ -45,13 +50,21 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import {
useRemoteConnectionStatus,
useRemoteEnvironmentRuntime,
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
interface EnvironmentOption {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly platform: string;
readonly baseDirectory: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
}
const environmentOptionOrder = Order.mapInput(
@@ -61,11 +74,6 @@ const environmentOptionOrder = Order.mapInput(
(environment: EnvironmentOption) => ({ label: environment.label }),
);
const browseEntryOrder = Order.mapInput(
Order.String,
(entry: { readonly name: string }) => entry.name,
);
function platformFromOs(os: string | null | undefined): string {
if (os === "windows") return "Win32";
if (os === "darwin") return "MacIntel";
@@ -228,22 +236,91 @@ function ProjectPathInput(props: {
);
}
function useBrowsePathInput(environment: EnvironmentOption | null) {
const environmentId = environment?.environmentId ?? null;
const environmentBaseDirectory = environment?.baseDirectory ?? null;
const [pathInput, commitPathInput] = useState(() =>
getAddProjectInitialQuery(environmentBaseDirectory),
);
const previousEnvironmentIdRef = useRef(environmentId);
const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
reportFailure: false,
reportDefect: false,
});
const [browseNavigation] = useState(createBrowseNavigationCoordinator);
const [isBrowseNavigating, setIsBrowseNavigating] = useState(false);
const setPathInput = useCallback(
(path: string) => {
browseNavigation.invalidate();
setIsBrowseNavigating(false);
commitPathInput(path);
},
[browseNavigation],
);
const navigateToBrowsePath = useCallback(
async (path: string) => {
setIsBrowseNavigating(true);
const committed = await browseNavigation.run(
async () => {
if (environment && canPreloadBrowsePath(environmentRuntime?.connectionState)) {
await loadBrowsePath({
environmentId: environment.environmentId,
input: { partialPath: path },
});
}
},
() => commitPathInput(path),
);
if (committed) {
setIsBrowseNavigating(false);
}
return committed;
},
[browseNavigation, environment, environmentRuntime?.connectionState, loadBrowsePath],
);
useEffect(() => {
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
previousEnvironmentIdRef.current = environmentId;
setPathInput(getAddProjectInitialQuery(environmentBaseDirectory));
}
}, [environmentBaseDirectory, environmentId, setPathInput]);
useEffect(
() => () => {
browseNavigation.invalidate();
},
[browseNavigation],
);
return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath };
}
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const serverConfigByEnvironmentId = useServerConfigs();
const { savedConnectionsById } = useSavedRemoteConnections();
const { connectedEnvironments } = useRemoteConnectionStatus();
return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
const runtimeByEnvironmentId = new Map(
connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
);
const options = Object.values(savedConnectionsById).map((connection) => {
const config = serverConfigByEnvironmentId.get(connection.environmentId);
const runtime = runtimeByEnvironmentId.get(connection.environmentId);
return {
environmentId: connection.environmentId,
label: connection.environmentLabel,
platform: platformFromOs(config?.environment.platform.os ?? null),
baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
connectionState: runtime?.connectionState ?? "available",
connectionError: runtime?.connectionError ?? null,
connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
};
});
return Arr.sort(options, environmentOptionOrder);
}, [savedConnectionsById, serverConfigByEnvironmentId]);
}, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
}
function useSelectedEnvironment(): {
@@ -254,8 +331,14 @@ function useSelectedEnvironment(): {
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
const environmentOptions = useEnvironmentOptions();
const selectedEnvironment =
environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ??
environmentOptions[0] ??
environmentOptions.find(
(environment) =>
environment.environmentId === selectedEnvironmentId &&
canCreateProjectInEnvironment(environment.connectionState),
) ??
environmentOptions.find((environment) =>
canCreateProjectInEnvironment(environment.connectionState),
) ??
null;
return {
@@ -270,9 +353,9 @@ function EmptyEnvironmentState() {
return (
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
<Text className="text-center text-lg font-t3-bold">No environments connected</Text>
<Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
<Text className="text-center text-sm leading-normal text-foreground-muted">
Add an environment before adding a project.
Start or reconnect an environment before adding a project.
</Text>
<Pressable
onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
@@ -352,17 +435,25 @@ export function AddProjectSourceScreen() {
return (
<AddProjectShell>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
{selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
{environmentOptions.length > 1 ? (
<>
<SectionTitle>Connected environments</SectionTitle>
<SectionTitle>Environments</SectionTitle>
<ListSection>
{environmentOptions.map((environment, index) => (
<ListRow
key={environment.environmentId}
title={environment.label}
subtitle={environment.environmentId}
subtitle={
canCreateProjectInEnvironment(environment.connectionState)
? environment.environmentId
: connectionStatusText({
phase: environment.connectionState,
error: environment.connectionError,
traceId: environment.connectionErrorTraceId,
})
}
icon={
<SymbolView
name="server.rack"
@@ -372,6 +463,7 @@ export function AddProjectSourceScreen() {
/>
}
selected={environment.environmentId === selectedEnvironment?.environmentId}
disabled={!canCreateProjectInEnvironment(environment.connectionState)}
isFirst={index === 0}
right={
environment.environmentId === selectedEnvironment?.environmentId ? (
@@ -445,7 +537,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
return useCallback(
async (workspaceRoot: string) => {
if (!environment) return;
if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
const existing = findExistingAddProject({
projects,
@@ -496,11 +588,7 @@ function useEnvironmentFromParam(
): EnvironmentOption | null {
const environmentOptions = useEnvironmentOptions();
const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
return (
environmentOptions.find((environment) => environment.environmentId === environmentId) ??
environmentOptions[0] ??
null
);
return resolveAddProjectEnvironment(environmentOptions, environmentId);
}
export function AddProjectRepositoryScreen(props: {
@@ -564,26 +652,32 @@ export function AddProjectRepositoryScreen(props: {
return (
<AddProjectShell>
{error ? <ErrorBanner message={error} /> : null}
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
autoCorrect={false}
placeholder={
source === "url"
? "https://github.com/org/repo.git"
: addProjectRemoteSourcePathHint(source)
}
returnKeyType="next"
onSubmitEditing={() => void lookupRepository()}
/>
<PrimaryActionButton
label={source === "url" ? "Continue" : "Lookup repository"}
disabled={isSubmitting || repositoryInput.trim().length === 0}
onPress={() => void lookupRepository()}
loading={isSubmitting}
/>
{environment ? (
<>
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
autoCorrect={false}
placeholder={
source === "url"
? "https://github.com/org/repo.git"
: addProjectRemoteSourcePathHint(source)
}
returnKeyType="next"
onSubmitEditing={() => void lookupRepository()}
/>
<PrimaryActionButton
label={source === "url" ? "Continue" : "Lookup repository"}
disabled={isSubmitting || repositoryInput.trim().length === 0}
onPress={() => void lookupRepository()}
loading={isSubmitting}
/>
</>
) : (
<EmptyEnvironmentState />
)}
</AddProjectShell>
);
}
@@ -592,22 +686,16 @@ function FolderBrowser(props: {
readonly environment: EnvironmentOption;
readonly pathInput: string;
readonly setPathInput: (path: string) => void;
readonly navigateToBrowsePath: (path: string) => Promise<boolean>;
}) {
const accentColor = useThemeColor("--color-icon-muted");
const browseDirectoryPath = useMemo(
() =>
isFilesystemBrowseQuery(props.pathInput, props.environment.platform)
? getBrowseDirectoryPath(props.pathInput)
: "",
const browsePath = useMemo(
() => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
[props.environment.platform, props.pathInput],
);
const browseFilterQuery =
browseDirectoryPath.length > 0 && !hasTrailingPathSeparator(props.pathInput)
? getBrowseLeafPathSegment(props.pathInput).toLowerCase()
: "";
const browseInput = useMemo(
() => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null),
[browseDirectoryPath],
() => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
[browsePath.directoryPath],
);
const browseState = useEnvironmentQuery(
browseInput === null
@@ -617,20 +705,10 @@ function FolderBrowser(props: {
input: browseInput,
}),
);
const visibleBrowseEntries = useMemo(
() =>
Arr.sort(
Arr.filter(
browseState.data?.entries ?? [],
(entry) =>
!entry.name.startsWith(".") && entry.name.toLowerCase().startsWith(browseFilterQuery),
),
browseEntryOrder,
),
[browseFilterQuery, browseState.data?.entries],
const { visibleEntries: visibleBrowseEntries } = useMemo(
() => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browsePath.filterQuery),
[browsePath.filterQuery, browseState.data?.entries],
);
const parentBrowsePath = getBrowseParentPath(browseDirectoryPath);
const canBrowseUpPath = canNavigateUp(browseDirectoryPath);
return (
<>
@@ -642,7 +720,7 @@ function FolderBrowser(props: {
<ActivityIndicator color={accentColor} />
</View>
) : null}
{canBrowseUpPath ? (
{browsePath.canBrowseUp ? (
<ListRow
title=".."
icon={
@@ -656,7 +734,9 @@ function FolderBrowser(props: {
isFirst
right={null}
onPress={() => {
if (parentBrowsePath) props.setPathInput(parentBrowsePath);
if (browsePath.parentPath) {
void props.navigateToBrowsePath(browsePath.parentPath);
}
}}
/>
) : null}
@@ -665,15 +745,15 @@ function FolderBrowser(props: {
key={entry.fullPath}
title={entry.name}
icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
isFirst={index === 0 && !canBrowseUpPath}
isFirst={index === 0 && !browsePath.canBrowseUp}
right={null}
onPress={() =>
props.setPathInput(
browseDirectoryPath.length > 0
? appendBrowsePathSegment(browseDirectoryPath, entry.name)
: ensureBrowseDirectoryPath(entry.fullPath),
)
}
onPress={() => {
const nextPath =
browsePath.directoryPath.length > 0
? appendBrowsePathSegment(browsePath.directoryPath, entry.name)
: ensureBrowseDirectoryPath(entry.fullPath);
void props.navigateToBrowsePath(nextPath);
}}
/>
))}
</ListSection>
@@ -684,19 +764,13 @@ function FolderBrowser(props: {
export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
const environment = useEnvironmentFromParam(props.environmentId);
const createProject = useCreateProject(environment);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
useBrowsePathInput(environment);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!environment) return;
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
}, [environment]);
const submitPath = useCallback(async () => {
if (!environment || isSubmitting) return;
if (!environment || isBrowseNavigating || isSubmitting) return;
setError(null);
const resolved = resolveAddProjectPath({
rawPath: pathInput,
@@ -714,7 +788,7 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
setError(errorMessage(Cause.squash(result.cause)));
}
setIsSubmitting(false);
}, [createProject, environment, isSubmitting, pathInput]);
}, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
return (
<AddProjectShell>
@@ -728,12 +802,13 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
/>
<PrimaryActionButton
label="Add project"
disabled={isSubmitting}
disabled={isBrowseNavigating || isSubmitting}
onPress={() => void submitPath()}
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
navigateToBrowsePath={navigateToBrowsePath}
pathInput={pathInput}
setPathInput={setPathInput}
/>
@@ -757,19 +832,13 @@ export function AddProjectDestinationScreen(props: {
const createProject = useCreateProject(environment);
const remoteUrl = stringParam(props.remoteUrl);
const repositoryTitle = stringParam(props.repositoryTitle);
const [pathInput, setPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
);
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
useBrowsePathInput(environment);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!environment) return;
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
}, [environment]);
const submitPath = useCallback(async () => {
if (!environment || !remoteUrl || isSubmitting) return;
if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
setError(null);
const resolved = resolveAddProjectPath({
rawPath: pathInput,
@@ -798,7 +867,15 @@ export function AddProjectDestinationScreen(props: {
}
}
setIsSubmitting(false);
}, [cloneRepository, createProject, environment, isSubmitting, pathInput, remoteUrl]);
}, [
cloneRepository,
createProject,
environment,
isBrowseNavigating,
isSubmitting,
pathInput,
remoteUrl,
]);
return (
<AddProjectShell>
@@ -820,12 +897,13 @@ export function AddProjectDestinationScreen(props: {
/>
<PrimaryActionButton
label="Clone project"
disabled={isSubmitting || !remoteUrl}
disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
onPress={() => void submitPath()}
loading={isSubmitting}
/>
<FolderBrowser
environment={environment}
navigateToBrowsePath={navigateToBrowsePath}
pathInput={pathInput}
setPathInput={setPathInput}
/>
@@ -8,8 +8,8 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "../../components/AppSymbol";
import * as Effect from "effect/Effect";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { Alert, Linking, Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
@@ -37,6 +37,12 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { runtime } from "../../lib/runtime";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
registerHiddenUpdateTap,
runAppUpdateCheck,
} from "../updates/app-updates";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
@@ -156,7 +162,7 @@ function ConfiguredSettingsRouteScreen() {
const environmentCount = connections.length;
const accountLabel = useMemo(() => {
if (!isLoaded) return "Checking";
if (!isSignedIn) return "Request access";
if (!isSignedIn) return "Sign in";
return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
}, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
@@ -263,13 +269,13 @@ function ConfiguredSettingsRouteScreen() {
const promptSignIn = useCallback(() => {
Alert.alert(
"Request T3 Connect access",
"Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
"Sign in to T3 Connect",
"Live Activity updates require T3 Connect so relay can deliver updates to this device.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Continue",
onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" }),
onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
},
],
);
@@ -431,7 +437,8 @@ function ConfiguredSettingsRouteScreen() {
const openAccount = useCallback(() => {
if (!isLoaded) return;
if (!isSignedIn) {
navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" });
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
return;
}
expandClerkSheet();
@@ -546,11 +553,8 @@ function GeneralSettingsSection() {
* the counterpart of web's Settings → Beta backed by mobile preferences.
*/
function BetaSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.threadListV2Enabled === true
: false;
const threadListV2Enabled = useThreadListV2Enabled();
return (
<View className="gap-3">
@@ -572,6 +576,9 @@ function BetaSettingsSection() {
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
const updateInFlight = useRef(false);
const hiddenUpdateTapCount = useRef(0);
const version = Constants.expoConfig?.version ?? "0.0.0";
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
@@ -579,37 +586,87 @@ function AppSettingsSection() {
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
// Which JS is actually running: the bundle shipped in the binary, or an OTA
// update downloaded on top of it. Surfacing this makes "am I even on the
// right build?" answerable at a glance.
const bundleLabel = Updates.isEnabled
? Updates.isEmbeddedLaunch
? "Embedded"
: Updates.updateId
? `OTA ${Updates.updateId.slice(0, 7)}`
: null
: null;
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
// "Up to date" is a transient acknowledgement, not a state worth persisting —
// return the version row to its normal, deliberately quiet state.
useEffect(() => {
if (updateState !== "current") return;
const timer = setTimeout(() => setUpdateState("idle"), 3000);
return () => clearTimeout(timer);
}, [updateState]);
const checkForUpdate = useCallback(async () => {
// `disabled={busy}` only takes effect on the next render, so two taps in the
// same frame would both get through. The ref closes that window.
if (updateInFlight.current) return;
updateInFlight.current = true;
try {
await runAppUpdateCheck({
onFailure: (message) => Alert.alert("Update failed", message),
onStateChange: setUpdateState,
});
} finally {
updateInFlight.current = false;
}
}, []);
const handleVersionPress = useCallback(() => {
if (!Updates.isEnabled || updateInFlight.current) return;
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
hiddenUpdateTapCount.current = tap.nextCount;
if (tap.shouldCheck) {
void checkForUpdate();
}
}, [checkForUpdate]);
const statusLabel =
updateState === "checking"
? "Checking…"
: updateState === "downloading"
? "Downloading…"
: updateState === "restarting"
? "Restarting…"
: updateState === "current"
? "Up to date"
: null;
const versionRow = (
<View className="flex-row items-center gap-4 p-4">
<SymbolView
name="info.circle"
size={22}
tintColor={icon}
type="monochrome"
weight="regular"
/>
<Text className="flex-1 text-lg text-foreground">Version</Text>
<View className="items-end">
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
{statusLabel ? (
<Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
) : null}
</View>
</View>
);
return (
<SettingsSection title="App">
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
<View className="flex-row items-center gap-4 p-4">
<SymbolView
name="info.circle"
size={22}
tintColor={icon}
type="monochrome"
weight="regular"
/>
<Text className="flex-1 text-lg text-foreground">Version</Text>
<View className="items-end">
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
{bundleLabel ? (
<Text className="text-xs text-foreground-muted/70">{bundleLabel}</Text>
) : null}
</View>
</View>
{Updates.isEnabled ? (
<Pressable
accessibilityLabel={`Version ${versionLabel}`}
accessibilityRole="text"
disabled={busy}
onPress={handleVersionPress}
>
{versionRow}
</Pressable>
) : (
versionRow
)}
</SettingsSection>
);
}
@@ -1,60 +0,0 @@
import { useAuth } from "@clerk/expo";
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
import { useCallback } from "react";
import { ScrollView } from "react-native";
import { CloudWaitlistEnrollment } from "../cloud/CloudWaitlistEnrollment";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
export function SettingsWaitlistRouteScreen() {
const navigation = useNavigation();
useFocusEffect(
useCallback(() => {
if (!hasCloudPublicConfig()) {
navigation.dispatch(StackActions.replace("Settings"));
}
}, [navigation]),
);
return hasCloudPublicConfig() ? <ConfiguredSettingsWaitlistRouteScreen /> : null;
}
function ConfiguredSettingsWaitlistRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { expand } = useClerkSettingsSheetDetent();
const navigation = useNavigation();
useFocusEffect(
useCallback(() => {
if (isLoaded && isSignedIn) {
navigation.dispatch(StackActions.replace("Settings"));
}
}, [isLoaded, isSignedIn, navigation]),
);
return (
<>
<ScrollView
automaticallyAdjustKeyboardInsets
contentContainerStyle={{
paddingBottom: 32,
paddingHorizontal: 20,
paddingTop: 12,
}}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="interactive"
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
<CloudWaitlistEnrollment
onSignIn={() => {
expand();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
}}
/>
</ScrollView>
</>
);
}
@@ -15,6 +15,7 @@ import {
type IncomingShareDestination,
type IncomingShareDraft,
} from "./incoming-share-model";
import { createIncomingSharePayloadReader } from "./incoming-share-native";
import { IncomingShareInbox } from "./incoming-share-inbox";
import {
loadIncomingShareDrafts,
@@ -48,6 +49,11 @@ function receiveSharingEnabled(): boolean {
return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
}
const getIncomingSharePayloads = createIncomingSharePayloadReader({
platform: Platform.OS,
readPayloads: getSharedPayloads,
});
async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {
try {
return await getResolvedSharedPayloadsAsync();
@@ -121,7 +127,7 @@ const incomingShareInbox = new IncomingShareInbox({
loadDrafts: loadIncomingShareDrafts,
writeDraft: writeIncomingShareDraft,
removeDraft: removeIncomingShareDraft,
getPayloads: getSharedPayloads,
getPayloads: getIncomingSharePayloads,
clearPayloads: clearSharedPayloads,
buildDraft: async ({ payloads, id, createdAt }) => {
const cleanupUris = new Set<string>();
@@ -0,0 +1,46 @@
import { describe, expect, it, vi } from "@effect/vitest";
import type { SharePayload } from "expo-sharing";
import { createIncomingSharePayloadReader } from "./incoming-share-native";
const PAYLOAD: SharePayload = {
shareType: "text",
mimeType: "text/plain",
value: "Fix this",
};
describe("createIncomingSharePayloadReader", () => {
it("treats a missing iOS App Group as an unavailable inbox", () => {
const readPayloads = vi.fn((): ReadonlyArray<SharePayload> => {
throw Object.assign(new Error("Expo-sharing has failed to fetch the app group id"), {
code: "ERR_FAILED_TO_RESOLVE_APP_GROUP_ID",
});
});
const read = createIncomingSharePayloadReader({ platform: "ios", readPayloads });
expect(read()).toEqual([]);
expect(read()).toEqual([]);
expect(readPayloads).toHaveBeenCalledTimes(1);
});
it("returns native payloads when receiving is available", () => {
const read = createIncomingSharePayloadReader({
platform: "ios",
readPayloads: () => [PAYLOAD],
});
expect(read()).toEqual([PAYLOAD]);
});
it("preserves other native errors", () => {
const error = new Error("native failure");
const read = createIncomingSharePayloadReader({
platform: "ios",
readPayloads: () => {
throw error;
},
});
expect(read).toThrow(error);
});
});
@@ -0,0 +1,37 @@
import type { SharePayload } from "expo-sharing";
const IOS_APP_GROUP_UNAVAILABLE_ERROR_CODE = "ERR_FAILED_TO_RESOLVE_APP_GROUP_ID";
function errorCode(error: unknown): string | null {
if (typeof error !== "object" || error === null || !("code" in error)) {
return null;
}
return typeof error.code === "string" ? error.code : null;
}
/**
* Normalizes the native "share into" capability to an empty inbox. Personal
* Team builds cannot include the App Group that expo-sharing reads from.
*/
export function createIncomingSharePayloadReader(input: {
readonly platform: string;
readonly readPayloads: () => ReadonlyArray<SharePayload>;
}): () => ReadonlyArray<SharePayload> {
let isUnavailable = false;
return () => {
if (isUnavailable) {
return [];
}
try {
return input.readPayloads();
} catch (error) {
if (input.platform === "ios" && errorCode(error) === IOS_APP_GROUP_UNAVAILABLE_ERROR_CODE) {
isUnavailable = true;
return [];
}
throw error;
}
};
}
@@ -54,7 +54,14 @@ function useShortcutNavigation(): void {
}
function useRecentThreadShortcutSync(state: NavigationState): void {
const threadRef = useMemo(() => activeThreadRef(state), [state]);
// Launcher shortcuts are Android-only. A null ref on iOS keeps this hook
// (mounted in the root stack layout) from subscribing the root to the
// active thread's shell, which would re-render every screen on each
// title/status/session change.
const threadRef = useMemo(
() => (Platform.OS === "android" ? activeThreadRef(state) : null),
[state],
);
const threadShell = useThreadShell(threadRef);
// null until the persisted list loads; recording waits on it so the first
// thread opened after a cold start cannot clobber older entries.
@@ -946,7 +946,11 @@ export function NewTaskDraftScreen(props: {
const promptEditor = (
<ComposerEditor
ref={promptInputRef}
autoFocus={!isAndroid}
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
// forces the iOS keyboard bring-up during the formSheet present
// animation and stalls it. The runAfterInteractions effect above focuses
// the editor once the transition settles instead.
autoFocus={false}
editable={!isIncomingShareTransferPending}
multiline
scrollEnabled={isExpanded}
@@ -203,13 +203,17 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
title={screenTitle}
subtitle={incomingShareSubtitle}
onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
actions={[
{
accessibilityLabel: "Add project",
icon: "plus",
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
},
]}
actions={
catalogState.hasReadyEnvironment
? [
{
accessibilityLabel: "Add project",
icon: "plus",
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
},
]
: []
}
/>
</>
) : (
@@ -229,11 +233,13 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
separateBackground
/>
) : null}
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
separateBackground
/>
{catalogState.hasReadyEnvironment ? (
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
separateBackground
/>
) : null}
</NativeHeaderToolbar>
</>
)}
@@ -518,14 +518,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
if (inFlightThreadIdsRef.current.has(threadKey)) return;
inFlightThreadIdsRef.current.add(threadKey);
// Sending a prompt starts agent work: arm the lock-screen card now, while
// the app is foregrounded and the activity token can be registered.
armAgentAwarenessLiveActivityForLocalWork({
threadTitle: props.selectedThread.title,
projectTitle: props.environmentLabel ?? "T3 Code",
});
try {
await onSendMessage();
// Sending a prompt starts agent work: arm the lock-screen card while the
// app is foregrounded and the activity token can be registered. Armed
// after the send so its preference read and native Activity start don't
// contend with the queued-message feedback on the tap frame.
armAgentAwarenessLiveActivityForLocalWork({
threadTitle: props.selectedThread.title,
projectTitle: props.environmentLabel ?? "T3 Code",
});
} finally {
inFlightThreadIdsRef.current.delete(threadKey);
}
+107 -6
View File
@@ -48,7 +48,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
FadeIn,
FadeInUp,
LinearTransition,
useSharedValue,
withTiming,
type LayoutAnimationsValues,
type SharedValue,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -80,7 +82,9 @@ import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../.
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
scaledTypographyLineHeight,
} from "../../lib/appearancePreferences";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
@@ -91,7 +95,12 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
import {
collapsedWorkLogHeight,
ThreadWorkGroupToggle,
ThreadWorkLog,
WORK_GROUP_TOGGLE_HEIGHT,
} from "./thread-work-log";
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
@@ -109,8 +118,22 @@ function formatMessageTime(input: string): string {
}
// Rows shift when content above them grows (streaming text, work-log folds);
// animating the container position turns those jumps into slides.
const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180);
// animating the container position turns those jumps into slides. Applied
// conditionally — see the gated transition in ThreadFeed: while browsing
// history the animation must NOT run, or every estimate→actual size
// correction plays as a visible slide against the instant scroll-offset
// compensation from maintainVisibleContentPosition.
const FEED_ITEM_LAYOUT_DURATION_MS = 180;
// Pre-measurement heights for getFixedItemSize, mirroring renderFeedEntry's
// classNames. The fold row's min-h-11 (44px) stays taller than its single
// text-sm line at every supported base font size (26px at the 22pt maximum),
// so its height is a constant; a drifted value costs one correction on
// measure, not a persistent offset.
const TURN_FOLD_HEIGHT = 56; // min-h-11 (44) + mb-3 (12)
// The working row has no min-height clamp — its height follows the scaled
// text-xs line height (see workingRowHeight in ThreadFeed).
const WORKING_ROW_VERTICAL_EXTRAS = 24; // py-1 (8) + mb-4 (16)
// Entering animations must only play for rows born just now — LegendList
// remounts rows when they scroll back into view, and replaying an entrance for
@@ -1301,6 +1324,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const headerMaterialVisibleRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const { width: windowWidth } = useWindowDimensions();
const { appearance } = useAppearancePreferences();
const [viewportWidth, setViewportWidth] = useState(() =>
props.layoutVariant === "split" ? 0 : windowWidth,
);
@@ -1410,6 +1434,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
},
[props.onHeaderMaterialVisibilityChange],
);
// True while the viewport sits within ~one screen of the list end — the
// only region where layout shifts should animate. Starts true because the
// list opens pinned to the end.
const nearListEnd = useSharedValue(true);
const handleScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
// anchorTopInset, not topContentInset: under automatic insets the list
@@ -1417,9 +1446,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
// header height back or the material toggles a full header too late.
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
nearListEnd.value =
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
},
[reportHeaderMaterialVisibility, anchorTopInset],
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
);
// Gated variant of the 180ms feed layout slide. Instant while browsing
// history: maintainVisibleContentPosition compensates the scroll offset in
// the same frame a row's measured size lands, so an instant reposition is
// invisible — animating it is exactly what made cold upward scrolls slide
// and jump. Near the end the slide stays on: streaming growth and sends
// shift rows at rest, where the animation is the thing preventing a hard
// visual snap.
const feedItemLayoutTransition = useMemo(() => {
return (values: LayoutAnimationsValues) => {
"worklet";
const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0;
return {
initialValues: {
originX: values.currentOriginX,
originY: values.currentOriginY,
width: values.currentWidth,
height: values.currentHeight,
},
animations: {
originX: withTiming(values.targetOriginX, { duration }),
originY: withTiming(values.targetOriginY, { duration }),
width: withTiming(values.targetWidth, { duration }),
height: withTiming(values.targetHeight, { duration }),
},
};
};
}, [nearListEnd]);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
@@ -1636,6 +1696,38 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
setExpandedImage({ uri, headers });
}, []);
// Rows whose height is known before they ever render. Without this, every
// row above the viewport is assumed to be estimatedItemSize tall, and
// scrolling up through unmeasured content corrects each row's height as it
// mounts — the feed visibly jumps. Fixed sizes make the small chrome rows
// exact; message rows stay undefined and use LegendList's per-type running
// average once one of their type has been measured. Text-driven heights
// follow the configurable base font size via scaledTypographyLineHeight.
const workingRowHeight =
WORKING_ROW_VERTICAL_EXTRAS +
scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.label, appearance.baseFontSize);
const getFixedItemSize = useCallback(
(entry: ThreadFeedEntry) => {
switch (entry.type) {
case "turn-fold":
return TURN_FOLD_HEIGHT;
case "work-toggle":
return WORK_GROUP_TOGGLE_HEIGHT;
case "working":
return workingRowHeight;
case "activity-group":
// Expanded rows append a variable detail block — fall back to
// measurement for those groups.
return entry.activities.some((activity) => expandedWorkRows[activity.id])
? undefined
: collapsedWorkLogHeight(entry.activities, appearance.baseFontSize);
default:
return undefined;
}
},
[expandedWorkRows, workingRowHeight, appearance.baseFontSize],
);
const renderItem = useCallback(
(info: { item: ThreadFeedEntry; index: number }) =>
renderFeedEntry(info, {
@@ -1725,7 +1817,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION}
itemLayoutAnimation={feedItemLayoutTransition}
// Patched LegendList prop (patches/@[email protected]):
// lets its scroll math clamp programmatic scrolls to -headerInset
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
@@ -1769,6 +1861,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
}
getFixedItemSize={getFixedItemSize}
// Measure rows well before they scroll into view so estimate→actual
// corrections land offscreen instead of under the user's finger.
drawDistance={500}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
@@ -1788,6 +1884,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// user overscroll back to the adjusted rest position.
scrollToOverflowEnabled
estimatedItemSize={180}
// Chat-style bottom alignment: when a thread is shorter than the
// viewport, pad above the content so messages rest just above the
// composer instead of under the header. No effect on threads that
// overflow the viewport (the padding clamps to zero).
alignItemsAtEnd
initialScrollAtEnd
onScroll={handleScroll}
scrollEventThrottle={16}
@@ -3,10 +3,13 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
threadSearchMatchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
@@ -25,9 +28,10 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { mobilePreferencesAtom } from "../../state/preferences";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
import { environmentServerConfigsAtom } from "../../state/server";
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
@@ -63,26 +67,21 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "./thread-list-items";
import { ThreadListV2Row } from "./thread-list-v2-items";
import { ThreadListV2PendingRow, ThreadListV2Row } from "./thread-list-v2-items";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
type ThreadListV2Item,
type ThreadListV2ListItem,
} from "./threadListV2";
/** The sidebar list serves both lists: v1 grouped items or, when the Thread
List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
List v2 beta is on, flat v2 rows with queued tasks spliced in, and a settled
"Show more" pager. */
type SidebarListItem =
| HomeListItem
| {
readonly type: "v2-pending-task";
readonly key: string;
readonly pendingTask: PendingNewTask;
readonly isLast: boolean;
}
| { readonly type: "v2-thread"; readonly key: string; readonly item: ThreadListV2Item }
| ThreadListV2ListItem
| { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
/**
@@ -186,7 +185,7 @@ function ThreadNavigationSidebarPane(
const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const [headerIsOverContent, setHeaderIsOverContent] = useState(false);
const searchInputRef = useRef<TextInput>(null);
@@ -196,10 +195,7 @@ function ThreadNavigationSidebarPane(
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled =
AsyncResult.isSuccess(preferencesResult) &&
preferencesResult.value.threadListV2Enabled === true;
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -218,6 +214,35 @@ function ThreadNavigationSidebarPane(
);
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
useHomeListOptions(availableEnvironmentIds);
const searchEnvironmentIds = useMemo(
() =>
options.selectedEnvironmentId === null
? workspaceEnvironments
.filter((environment) => environment.connectionState === "connected")
.map((environment) => environment.environmentId)
: workspaceEnvironments.some(
(environment) =>
environment.environmentId === options.selectedEnvironmentId &&
environment.connectionState === "connected",
)
? [options.selectedEnvironmentId]
: [],
[options.selectedEnvironmentId, workspaceEnvironments],
);
const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
const threadSearchMatchByKey = useMemo(() => {
const matches = new Map<string, EnvironmentThreadSearchMatch>();
for (const match of threadSearch.matches) {
if (match.source === "user" || match.source === "assistant") {
matches.set(threadSearchMatchKey(match), match);
}
}
return matches;
}, [threadSearch.matches]);
const matchedThreadKeys = useMemo(
() => new Set(threadSearch.matches.map(threadSearchMatchKey)),
[threadSearch.matches],
);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const projectScopes = useMemo(
() =>
@@ -314,11 +339,19 @@ function ThreadNavigationSidebarPane(
pendingTasks: scopedPendingTasks,
environmentId: options.selectedEnvironmentId,
searchQuery: props.searchQuery,
matchedThreadKeys,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
}),
[options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
[
matchedThreadKeys,
options,
props.searchQuery,
scopedPendingTasks,
scopedProjects,
scopedThreads,
],
);
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
@@ -441,6 +474,7 @@ function ThreadNavigationSidebarPane(
environmentId: options.selectedEnvironmentId,
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -454,6 +488,7 @@ function ThreadNavigationSidebarPane(
snoozeWakeTick,
options.selectedEnvironmentId,
props.searchQuery,
matchedThreadKeys,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -477,11 +512,11 @@ function ThreadNavigationSidebarPane(
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const listItems = useMemo<readonly SidebarListItem[]>(() => {
if (!threadListV2Enabled) return listLayout.items;
// Queued offline tasks render above the thread rows (mirrors the
// compact Home v2 list): they are not thread shells, so the v2 item
// builder never sees them, but they must stay visible and deletable
// while their environment is offline. Same environment scope and
// search filter as the list.
// Queued offline tasks are not thread shells, so the v2 item builder
// never sees them; the shared splice puts them below the active block
// (mirrors the compact Home v2 list) where they stay visible and
// deletable while their environment is offline. Same environment scope
// and search filter as the list.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = pendingTasks.filter(
(pendingTask) =>
@@ -494,19 +529,10 @@ function ThreadNavigationSidebarPane(
(v2SearchQuery.length === 0 ||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
const items: SidebarListItem[] = v2PendingTasks.map((pendingTask, index) => ({
type: "v2-pending-task" as const,
key: `v2-pending:${pendingTask.message.messageId}`,
pendingTask,
isLast: index === v2PendingTasks.length - 1,
}));
for (const item of threadListV2Layout.items) {
items.push({
type: "v2-thread" as const,
key: scopedThreadKey(item.thread.environmentId, item.thread.id),
item,
});
}
const items: SidebarListItem[] = buildThreadListV2ListItems({
items: threadListV2Layout.items,
pendingTasks: v2PendingTasks,
});
if (threadListV2Layout.hiddenSettledCount > 0) {
items.push({
type: "v2-show-more",
@@ -694,13 +720,28 @@ function ThreadNavigationSidebarPane(
onScroll: handleScroll,
onScrollBeginDrag: handleScrollBeginDrag,
});
// Project shells load after the first rows draw, so the maps they feed have
// to bust the recycler's memoization — otherwise a row keeps the blank
// favicon and fallback title it was first rendered with.
const listExtraData = useMemo(
() => ({
selectedThreadKey: props.selectedThreadKey ?? "",
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
}),
[props.selectedThreadKey, savedConnectionsById, serverConfigs],
[
props.selectedThreadKey,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
],
);
const sidebarItemsAreEqual = useCallback(
(previous: SidebarListItem, item: SidebarListItem): boolean => {
@@ -715,16 +756,19 @@ function ThreadNavigationSidebarPane(
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
return previous.hiddenCount === item.hiddenCount;
}
if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
if (previous.type === "v2-pending" && item.type === "v2-pending") {
return (
previous.pendingTask === item.pendingTask &&
previous.showPendingDivider === item.showPendingDivider
);
}
if (
previous.type === "v2-thread" ||
previous.type === "v2-show-more" ||
previous.type === "v2-pending-task" ||
previous.type === "v2-pending" ||
item.type === "v2-thread" ||
item.type === "v2-show-more" ||
item.type === "v2-pending-task"
item.type === "v2-pending"
) {
return false;
}
@@ -752,20 +796,29 @@ function ThreadNavigationSidebarPane(
const renderListItem = useCallback(
({ item }: { readonly item: SidebarListItem }) => {
switch (item.type) {
case "v2-pending-task":
case "v2-pending": {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
item.pendingTask.creation.projectId,
);
return (
<PendingTaskListRow
variant="sidebar"
<ThreadListV2PendingRow
pendingTask={item.pendingTask}
project={projectByKey.get(pendingScopeKey) ?? null}
projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
environmentLabel={
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
null
Object.keys(savedConnectionsById).length > 1
? (savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null)
: null
}
isLast={item.isLast}
pane="sidebar"
showPendingDivider={item.showPendingDivider}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
/>
);
}
case "v2-thread": {
const thread = item.item.thread;
const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
@@ -790,6 +843,13 @@ function ThreadNavigationSidebarPane(
? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
: null
}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
pane="sidebar"
selected={
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
@@ -869,6 +929,13 @@ function ThreadNavigationSidebarPane(
null
}
isLast={item.isLast}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
selected={
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
}
@@ -907,10 +974,12 @@ function ThreadNavigationSidebarPane(
projectCwdByKey,
projectTitleByProjectKey,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
props.width,
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -970,13 +1039,15 @@ function ThreadNavigationSidebarPane(
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
? snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
? threadSearch.isPending && snoozedCount === 0
? "Searching thread messages…"
: snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
: snoozedCount > 0
? snoozedCount === 1
? "1 thread snoozed"
@@ -11,6 +11,7 @@ import {
import type { ReactNode } from "react";
import { Platform, useColorScheme } from "react-native";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
@@ -35,10 +36,9 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
headerShadowVisible: false,
headerShown: true,
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? { backgroundColor: "transparent" } : undefined,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
...getCompactBrandHeaderOptions({ fontSize: 18, fontWeight: "800" }),
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED ? SCROLL_EDGE_EFFECTS : undefined,
title: "Threads",
unstable_navigationItemStyle: NATIVE_LIQUID_GLASS_SUPPORTED ? "editor" : undefined,
};
@@ -3,6 +3,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import type { MenuAction } from "@react-native-menu/menu";
import { SymbolView } from "../../components/AppSymbol";
import { memo, useCallback, useMemo, type ComponentProps } from "react";
@@ -14,6 +15,7 @@ import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { cn } from "../../lib/cn";
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -21,6 +23,7 @@ import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadStatus } from "./threadPresentation";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
/**
* Shared presentation for the thread lists: the compact (phone) Home list and
@@ -31,7 +34,7 @@ import { resolveThreadStatus } from "./threadPresentation";
export type ThreadListVariant = "compact" | "sidebar";
/** Left inset that aligns compact secondary rows with the title column. */
export const THREAD_LIST_COMPACT_INSET = 20;
export const THREAD_LIST_COMPACT_INSET = HOME_HORIZONTAL_INSET;
const SIDEBAR_ROW_RADIUS = 12;
function pullRequestTintColor(
@@ -416,6 +419,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly projectCwd: string | null;
readonly searchMatch?: EnvironmentThreadSearchMatch;
readonly searchQuery?: string;
readonly isLast: boolean;
/** Sidebar only: the thread currently open in the detail pane. */
readonly selected?: boolean;
@@ -569,6 +574,13 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
/>
</View>
</View>
{props.searchMatch ? (
<ThreadSearchMatchExcerpt
compact
match={props.searchMatch}
query={props.searchQuery ?? ""}
/>
) : null}
{subtitleRow}
</View>
</View>
@@ -623,6 +635,13 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
</Text>
</View>
</View>
{props.searchMatch ? (
<ThreadSearchMatchExcerpt
match={props.searchMatch}
query={props.searchQuery ?? ""}
selected={selected}
/>
) : null}
{subtitleRow}
</View>
</Pressable>
@@ -2,6 +2,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
@@ -14,9 +15,11 @@ import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
/**
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
@@ -68,7 +71,9 @@ const LEGACY_MENU_ACTIONS: MenuAction[] = [
/** Rounded-row radius shared with the v1 sidebar rows. */
const SIDEBAR_V2_ROW_RADIUS = 12;
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider(props: {
/** Section label + rule: the only structure in an otherwise flat list. */
export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivider(props: {
readonly label: string;
readonly pane?: "screen" | "sidebar";
}) {
const borderColor = useThemeColor("--color-border");
@@ -79,12 +84,127 @@ export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivid
props.pane === "sidebar" ? "px-3" : "px-5",
)}
>
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
<Text className="text-xs font-t3-medium text-foreground-tertiary">{props.label}</Text>
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
</View>
);
});
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
/**
* A queued new task, in the same idiom as an active v2 row: it is work the
* user wrote, so it reads like the threads it will become. "Queued" takes
* the status slot — the state is the one thing that differs — and stays
* uncolored because nothing is asked of the user; the environment is simply
* not reachable yet.
*/
export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props: {
readonly pendingTask: PendingNewTask;
readonly project: EnvironmentProject | null;
readonly projectTitle?: string;
readonly environmentLabel: string | null;
readonly pane?: "screen" | "sidebar";
/** Draws the "Pending" divider above the first queued row. */
readonly showPendingDivider: boolean;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
}) {
const { pendingTask, onSelectPendingTask, onDeletePendingTask } = props;
const drawerColor = useThemeColor("--color-drawer");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const sidebarPane = props.pane === "sidebar";
const projectTitle =
props.projectTitle ?? props.project?.title ?? pendingTask.creation.projectTitle ?? "";
const branch = pendingTask.creation.branch;
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "delete") onDeletePendingTask(pendingTask);
},
[onDeletePendingTask, pendingTask],
);
const rowContent = (
<>
<View className="flex-row items-center gap-1.5">
{props.project ? (
<ProjectFavicon
environmentId={pendingTask.message.environmentId}
size={15}
projectTitle={projectTitle}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
<Text className="flex-1 text-sm font-t3-medium text-foreground-muted" numberOfLines={1}>
{projectTitle}
</Text>
<Text className="text-xs text-foreground-tertiary">Queued</Text>
</View>
{/* One line, unlike the two an active row allows: a queued title is
derived from the whole prompt rather than written as a title, so the
second line is usually a stray word or emoji rather than meaning. */}
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
{pendingTask.title}
</Text>
{branch || props.environmentLabel ? (
<Text className="mt-1 text-xs text-foreground-muted" numberOfLines={1}>
{branch ? (
<Text className="text-xs text-foreground-muted" style={{ fontFamily: MONO_FONT }}>
{branch}
</Text>
) : null}
{branch && props.environmentLabel ? " · " : null}
{props.environmentLabel ? (
<Text className="text-xs text-foreground-tertiary">{props.environmentLabel}</Text>
) : null}
</Text>
) : null}
</>
);
return (
<>
{props.showPendingDivider ? (
<ThreadListV2SectionDivider label="Pending" pane={props.pane} />
) : null}
<ControlPillMenu
actions={PENDING_TASK_MENU_ACTIONS}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
<Pressable
accessibilityHint="Opens the queued task for editing"
accessibilityLabel={pendingTask.title}
accessibilityRole="button"
onPress={() => onSelectPendingTask(pendingTask)}
style={
sidebarPane
? ({ pressed }) => ({
backgroundColor: pressed ? pressedBackgroundColor : drawerColor,
borderRadius: SIDEBAR_V2_ROW_RADIUS,
paddingHorizontal: 12,
paddingVertical: 10,
})
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
}
>
{sidebarPane ? (
rowContent
) : (
<View className="bg-screen">
<View className="px-5 py-2.5">{rowContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
</ControlPillMenu>
</>
);
});
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
@@ -125,6 +245,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
state: "open" | "closed" | "merged" | null,
) => void;
readonly projectCwd?: string | null;
readonly searchMatch?: EnvironmentThreadSearchMatch;
readonly searchQuery?: string;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
@@ -251,6 +373,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
>
{thread.title}
</Text>
{props.searchMatch ? (
<View className="mt-1">
<ThreadSearchMatchExcerpt
match={props.searchMatch}
query={props.searchQuery ?? ""}
selected={selected}
/>
</View>
) : null}
<View className="mt-1 flex-row items-center gap-2">
{status === "failed" && thread.session?.lastError ? (
<Text
@@ -399,15 +530,24 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
/>
</View>
) : null}
<Text
className={cn(
"flex-1 text-base",
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.title}
</Text>
<View className="min-w-0 flex-1">
<Text
className={cn(
"text-base",
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.title}
</Text>
{props.searchMatch ? (
<ThreadSearchMatchExcerpt
match={props.searchMatch}
query={props.searchQuery ?? ""}
selected={selected}
/>
) : null}
</View>
<Text
className={cn(
"text-sm tabular-nums",
@@ -423,7 +563,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
{props.showSettledDivider ? (
<ThreadListV2SectionDivider label="Settled" pane={props.pane} />
) : null}
<ThreadSwipeable
backgroundColor={sidebarPane ? drawerColor : screenColor}
compactActions={variant === "slim"}
@@ -0,0 +1,92 @@
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
function foldAsciiCase(value: string): string {
return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
}
function splitHighlightParts(text: string, query: string) {
const normalizedText = foldAsciiCase(text);
const normalizedQuery = foldAsciiCase(query.trim());
if (normalizedQuery.length === 0) {
return [{ text, highlighted: false, start: 0 }];
}
const parts: Array<{
readonly text: string;
readonly highlighted: boolean;
readonly start: number;
}> = [];
let cursor = 0;
while (cursor < text.length) {
const matchIndex = normalizedText.indexOf(normalizedQuery, cursor);
if (matchIndex === -1) {
parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });
break;
}
if (matchIndex > cursor) {
parts.push({
text: text.slice(cursor, matchIndex),
highlighted: false,
start: cursor,
});
}
parts.push({
text: text.slice(matchIndex, matchIndex + normalizedQuery.length),
highlighted: true,
start: matchIndex,
});
cursor = matchIndex + normalizedQuery.length;
}
return parts;
}
export function ThreadSearchMatchExcerpt(props: {
readonly match: EnvironmentThreadSearchMatch;
readonly query: string;
readonly selected?: boolean;
readonly compact?: boolean;
}) {
const isUser = props.match.source === "user";
const parts = splitHighlightParts(props.match.snippet, props.query);
return (
<Text
className={cn(
props.compact ? "text-sm" : "text-xs",
props.selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
>
<Text
className={cn(
props.compact ? "text-sm font-t3-medium" : "text-xs font-t3-medium",
props.selected
? "text-user-bubble-foreground"
: isUser
? "text-blue-500 dark:text-blue-400"
: "text-emerald-600 dark:text-emerald-400",
)}
>
{isUser ? "You:" : "Agent:"}{" "}
</Text>
{parts.map((part) => (
<Text
className={cn(
props.compact ? "text-sm" : "text-xs",
part.highlighted && "font-t3-bold",
props.selected
? "text-user-bubble-foreground"
: part.highlighted
? "text-foreground"
: "text-foreground-muted",
)}
key={part.start}
>
{part.text}
</Text>
))}
</Text>
);
}
@@ -3,8 +3,10 @@ import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import Animated, { FadeIn } from "react-native-reanimated";
const WORK_LOG_LAYOUT_ANIMATION = {
@@ -77,6 +79,46 @@ function isFreshRow(createdAt: string): boolean {
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
}
// Tool-like activities with a neutral status carry no signal worth a row.
export function visibleWorkLogActivities(
activities: ReadonlyArray<ThreadFeedActivity>,
): ReadonlyArray<ThreadFeedActivity> {
return activities.filter((activity) => !(activity.toolLike && activity.status === "neutral"));
}
// Pre-measurement heights for the feed's getFixedItemSize. Collapsed work-log
// rows are single-line (numberOfLines={1}) inside a min-height that stays
// taller than the text at every supported base font size (text-xs reaches
// 23px at the 22pt maximum, under the 32px min-h-8), so row height is
// deterministic. The "work log" label has no such clamp — its height follows
// the scaled text-2xs line height. Values mirror the classNames below — keep
// them in sync; a mismatch only costs a one-time correction on measure.
const WORK_ROW_HEIGHT = 32; // min-h-8
const WORK_ROW_GAP = 1; // gap-px
const WORK_LOG_HEADER_PADDING = 2; // pb-0.5 under the "work log" label
const WORK_LOG_BOTTOM_MARGIN = 4; // mb-1
export const WORK_GROUP_TOGGLE_HEIGHT = 36; // min-h-8 (32) + mb-1 (4)
export function collapsedWorkLogHeight(
activities: ReadonlyArray<ThreadFeedActivity>,
baseFontSize: number,
): number {
const rows = visibleWorkLogActivities(activities);
if (rows.length === 0) {
return 0;
}
const onlyToolRows = rows.every((row) => row.toolLike);
const headerHeight =
scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.caption, baseFontSize) + WORK_LOG_HEADER_PADDING;
return (
WORK_LOG_BOTTOM_MARGIN +
(onlyToolRows ? 0 : headerHeight) +
rows.length * WORK_ROW_HEIGHT +
(rows.length - 1) * WORK_ROW_GAP
);
}
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
@@ -87,9 +129,10 @@ export function ThreadWorkLog(props: {
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const rows = props.activities
.filter((activity) => !(activity.toolLike && activity.status === "neutral"))
.map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
const rows = visibleWorkLogActivities(props.activities).map((activity) => ({
...activity,
detail: compactActivityDetail(activity.detail),
}));
if (rows.length === 0) {
return null;
@@ -1,9 +1,21 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import {
CommandId,
EnvironmentId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
resolveThreadListV2Enabled,
resolveThreadListV2Status,
sortThreadsForListV2,
} from "./threadListV2";
@@ -38,6 +50,25 @@ function makeThread(
const NOW = "2026-06-02T00:00:00.000Z";
describe("resolveThreadListV2Enabled", () => {
it("defaults on when the device has never chosen", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
true,
);
});
it("honors an explicit device opt-out", () => {
expect(resolveThreadListV2Enabled({ preference: false, preferencesLoaded: true })).toBe(false);
expect(resolveThreadListV2Enabled({ preference: true, preferencesLoaded: true })).toBe(true);
});
it("holds the default while preferences are still loading so the list does not remount", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: false })).toBe(
true,
);
});
});
describe("resolveThreadListV2Status", () => {
it("prioritizes approval over a running session", () => {
const thread = makeThread({
@@ -233,6 +264,27 @@ describe("buildThreadListV2Items", () => {
]);
});
it("includes a thread matched by message content", () => {
const thread = makeThread({
id: ThreadId.make("content-match"),
title: "Unrelated title",
});
const { items } = buildThreadListV2Items({
threads: [thread],
environmentId: null,
searchQuery: "relay reconnect",
matchedThreadKeys: new Set([
threadSearchMatchKey({
environmentId,
threadId: thread.id,
}),
]),
now: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["content-match"]);
});
it("scopes the flat list to one project", () => {
const otherProjectId = ProjectId.make("project-2");
const { items } = buildThreadListV2Items({
@@ -320,3 +372,88 @@ describe("buildThreadListV2Items settled paging", () => {
]);
});
});
function makePendingTask(id: string): PendingNewTask {
return {
message: {
environmentId,
threadId: ThreadId.make(`thread-${id}`),
messageId: MessageId.make(id),
commandId: CommandId.make(`command-${id}`),
text: id,
attachments: [],
createdAt: NOW,
creation: {
projectId: ProjectId.make("project-1"),
workspaceMode: "worktree",
branch: null,
worktreePath: null,
},
},
creation: {
projectId: ProjectId.make("project-1"),
workspaceMode: "worktree",
branch: null,
worktreePath: null,
},
title: id,
};
}
describe("buildThreadListV2ListItems", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "active" }),
makeThread({
id: ThreadId.make("settled"),
title: "settled",
settledOverride: "settled",
settledAt: NOW,
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
it("splices queued tasks between the active block and the settled tail", () => {
const items = buildThreadListV2ListItems({
items: layout.items,
pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
});
expect(
items.map((item) =>
item.type === "v2-pending" ? item.pendingTask.title : item.item.thread.id,
),
).toEqual(["active", "queued-1", "queued-2", "settled"]);
// Only the leading queued row labels the section, exactly like Settled.
expect(
items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
).toHaveLength(1);
});
it("ends the list with queued tasks when nothing has settled yet", () => {
const activeOnly = buildThreadListV2Items({
threads: [makeThread({ id: ThreadId.make("active"), title: "active" })],
environmentId: null,
searchQuery: "",
now: NOW,
});
const items = buildThreadListV2ListItems({
items: activeOnly.items,
pendingTasks: [makePendingTask("queued-1")],
});
expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
});
it("leaves the thread order untouched when nothing is queued", () => {
const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks: [] });
expect(items.map((item) => item.key)).toEqual([
`v2-thread:${environmentId}:active`,
`v2-thread:${environmentId}:settled`,
]);
});
});
@@ -1,7 +1,10 @@
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
/**
* Thread List v2 model, ported from the web sidebar v2
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
@@ -18,6 +21,26 @@ export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
/**
* Thread List v2 is on by default on every app variant; the Settings → Beta
* toggle is an opt-out. Preferences persist as sparse patches, so `undefined`
* genuinely means "never chosen".
*
* `preferencesLoaded` guards the startup window: preferences load
* asynchronously, and rendering one list before the stored choice arrives would
* remount the whole thing a tick later. While loading, hold the default — that
* is where every device without an explicit opt-out lands anyway.
*/
export function resolveThreadListV2Enabled(input: {
readonly preference: boolean | undefined;
readonly preferencesLoaded: boolean;
}): boolean {
if (!input.preferencesLoaded) {
return true;
}
return input.preference ?? true;
}
export function resolveThreadListV2Status(
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
): ThreadListV2Status {
@@ -93,6 +116,60 @@ export interface ThreadListV2Layout {
readonly nextSnoozeWakeAt: string | null;
}
export interface ThreadListV2ThreadListItem {
readonly type: "v2-thread";
readonly key: string;
readonly item: ThreadListV2Item;
}
export interface ThreadListV2PendingListItem {
readonly type: "v2-pending";
readonly key: string;
readonly pendingTask: PendingNewTask;
/** First queued row after the active block draws the PENDING divider. */
readonly showPendingDivider: boolean;
}
export type ThreadListV2ListItem = ThreadListV2ThreadListItem | ThreadListV2PendingListItem;
/**
* Splices queued tasks between the active block and the settled tail, so the
* list reads active → pending → settled. Queued work sits below the live
* threads because nothing can happen to it until its environment returns:
* it is waiting, not asking. Shared by the compact Home list and the iPad
* sidebar so both order and label the sections identically.
*/
export function buildThreadListV2ListItems(input: {
readonly items: ReadonlyArray<ThreadListV2Item>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
}): ThreadListV2ListItem[] {
const threadItems = input.items.map(
(item): ThreadListV2ListItem => ({
type: "v2-thread",
key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
item,
}),
);
if (input.pendingTasks.length === 0) return threadItems;
const pendingItems = input.pendingTasks.map(
(pendingTask, index): ThreadListV2ListItem => ({
type: "v2-pending",
key: `v2-pending:${pendingTask.message.messageId}`,
pendingTask,
showPendingDivider: index === 0,
}),
);
// The settled tail begins at the row that draws the SETTLED divider; with
// no settled rows the queued block simply ends the list.
const settledStart = threadItems.findIndex(
(entry) => entry.type === "v2-thread" && entry.item.showSettledDivider,
);
return settledStart === -1
? [...threadItems, ...pendingItems]
: [...threadItems.slice(0, settledStart), ...pendingItems, ...threadItems.slice(settledStart)];
}
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
@@ -107,6 +184,7 @@ export function buildThreadListV2Items(input: {
readonly projectId: ProjectId;
}> | null;
readonly searchQuery: string;
readonly matchedThreadKeys?: ReadonlySet<string>;
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
/** Environments whose server supports thread.settle/unsettle. Threads on
@@ -146,7 +224,18 @@ export function buildThreadListV2Items(input: {
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
continue;
}
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
if (
query.length > 0 &&
!thread.title.toLocaleLowerCase().includes(query) &&
input.matchedThreadKeys?.has(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
) !== true
) {
continue;
}
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
@@ -0,0 +1,19 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { mobilePreferencesAtom } from "../../state/preferences";
import { resolveThreadListV2Enabled } from "./threadListV2";
/**
* Resolved Thread List v2 state: the device-local preference if the user has
* set one, otherwise the default (on). Every consumer must read through this
* rather than the raw preference, which is undefined until explicitly chosen.
*/
export function useThreadListV2Enabled(): boolean {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferencesResult);
return resolveThreadListV2Enabled({
preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined,
preferencesLoaded: loaded,
});
}
@@ -0,0 +1,252 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
createAppUpdateLaunchCheck,
registerHiddenUpdateTap,
runAppUpdateCheck,
type AppUpdateCheckState,
type AppUpdateClient,
} from "./app-updates";
vi.mock("expo-updates", () => ({
isEnabled: true,
checkForUpdateAsync: vi.fn(),
fetchUpdateAsync: vi.fn(),
reloadAsync: vi.fn(),
}));
function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateClient {
return {
isEnabled: true,
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: false,
isRollBackToEmbedded: false,
})),
fetchUpdateAsync: vi.fn(async () => ({
isNew: true,
isRollBackToEmbedded: false,
})),
reloadAsync: vi.fn(async () => {}),
...overrides,
};
}
describe("runAppUpdateCheck", () => {
it("downloads and restarts when a new update is available", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: true,
isRollBackToEmbedded: false,
})),
});
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({ client, onStateChange: (state) => states.push(state) });
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
expect(client.reloadAsync).toHaveBeenCalledOnce();
expect(states).toEqual(["checking", "downloading", "restarting"]);
});
it("restarts into the embedded bundle for a rollback directive", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: false,
isRollBackToEmbedded: true,
})),
fetchUpdateAsync: vi.fn(async () => ({
isNew: false,
isRollBackToEmbedded: true,
})),
});
await runAppUpdateCheck({ client });
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
expect(client.reloadAsync).toHaveBeenCalledOnce();
});
it("stops quietly when the running bundle is current", async () => {
const client = makeUpdateClient();
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({ client, onStateChange: (state) => states.push(state) });
expect(client.fetchUpdateAsync).not.toHaveBeenCalled();
expect(client.reloadAsync).not.toHaveBeenCalled();
expect(states).toEqual(["checking", "current"]);
});
it("reports manual failures without continuing the update", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => {
throw new Error("offline");
}),
});
const failures: string[] = [];
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({
client,
onFailure: (message) => failures.push(message),
onStateChange: (state) => states.push(state),
});
expect(client.fetchUpdateAsync).not.toHaveBeenCalled();
expect(failures).toEqual(["offline"]);
expect(states).toEqual(["checking", "idle"]);
reportError.mockRestore();
});
it("coalesces overlapping launch and manual checks", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}) => void;
const checkResult = new Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>((resolve) => {
resolveCheck = resolve;
});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(() => checkResult),
});
const checkOnLaunch = createAppUpdateLaunchCheck(client);
const manualStates: AppUpdateCheckState[] = [];
const launchCheck = checkOnLaunch();
const manualCheck = runAppUpdateCheck({
client,
onStateChange: (state) => manualStates.push(state),
});
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(manualStates).toEqual(["checking"]);
resolveCheck({
isAvailable: false,
isRollBackToEmbedded: false,
});
await Promise.all([launchCheck, manualCheck]);
expect(manualStates).toEqual(["checking", "current"]);
await runAppUpdateCheck({ client });
expect(client.checkForUpdateAsync).toHaveBeenCalledTimes(2);
});
it("forwards failures to a manual check coalesced with the launch check", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
let rejectCheck!: (error: Error) => void;
const checkResult = new Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>((_resolve, reject) => {
rejectCheck = reject;
});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(() => checkResult),
});
const checkOnLaunch = createAppUpdateLaunchCheck(client);
const failures: string[] = [];
const manualStates: AppUpdateCheckState[] = [];
const launchCheck = checkOnLaunch();
const manualCheck = runAppUpdateCheck({
client,
onFailure: (message) => failures.push(message),
onStateChange: (state) => manualStates.push(state),
});
rejectCheck(new Error("offline"));
await Promise.all([launchCheck, manualCheck]);
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(failures).toEqual(["offline"]);
expect(manualStates).toEqual(["checking", "idle"]);
reportError.mockRestore();
});
it("publishes the in-flight check before a state callback can re-enter", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}) => void;
const checkResult = new Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>((resolve) => {
resolveCheck = resolve;
});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(() => checkResult),
});
const reentrantStates: AppUpdateCheckState[] = [];
let reentrantCheck: Promise<void> | undefined;
let didReenter = false;
const initialCheck = runAppUpdateCheck({
client,
onStateChange: (state) => {
if (state !== "checking" || didReenter) return;
didReenter = true;
reentrantCheck = runAppUpdateCheck({
client,
onStateChange: (reentrantState) => reentrantStates.push(reentrantState),
});
},
});
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(reentrantCheck).toBeDefined();
expect(reentrantStates).toEqual(["checking"]);
resolveCheck({
isAvailable: false,
isRollBackToEmbedded: false,
});
await Promise.all([initialCheck, reentrantCheck]);
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(reentrantStates).toEqual(["checking", "current"]);
});
});
describe("createAppUpdateLaunchCheck", () => {
it("checks at most once for each JavaScript launch", async () => {
const client = makeUpdateClient();
const checkOnLaunch = createAppUpdateLaunchCheck(client);
const first = checkOnLaunch();
const second = checkOnLaunch();
await first;
expect(second).toBeUndefined();
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
});
it("does nothing when Expo updates are disabled", () => {
const client = makeUpdateClient({ isEnabled: false });
const checkOnLaunch = createAppUpdateLaunchCheck(client);
expect(checkOnLaunch()).toBeUndefined();
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
});
});
describe("registerHiddenUpdateTap", () => {
it("unlocks the manual check on the fifth tap", () => {
let count = 0;
for (let tap = 1; tap <= 5; tap += 1) {
const result = registerHiddenUpdateTap(count);
expect(result.shouldCheck).toBe(tap === 5);
count = result.nextCount;
}
expect(count).toBe(0);
});
});
@@ -0,0 +1,228 @@
import * as Updates from "expo-updates";
import {
type AtomCommandResult,
isAtomCommandInterrupted,
reportAtomCommandResult,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
export type AppUpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
export interface AppUpdateClient {
readonly isEnabled: boolean;
readonly checkForUpdateAsync: () => Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>;
readonly fetchUpdateAsync: () => Promise<{
readonly isNew: boolean;
readonly isRollBackToEmbedded: boolean;
}>;
readonly reloadAsync: () => Promise<void>;
}
interface AppUpdateCheckOptions {
readonly client?: AppUpdateClient;
readonly onFailure?: (message: string) => void;
readonly onStateChange?: (state: AppUpdateCheckState) => void;
}
interface AppUpdateCheckProgress {
failure: string | undefined;
state: AppUpdateCheckState | undefined;
}
interface AppUpdateCheckInFlight {
readonly failureListeners: Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>;
readonly progress: AppUpdateCheckProgress;
readonly promise: Promise<void>;
readonly stateListeners: Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>;
}
interface Deferred {
readonly promise: Promise<void>;
readonly reject: (cause: unknown) => void;
readonly resolve: () => void;
}
const HIDDEN_UPDATE_TAP_COUNT = 5;
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
/**
* Keeps the manual update affordance discoverable only to someone deliberately
* tapping the version row five times.
*/
export function registerHiddenUpdateTap(count: number): {
readonly nextCount: number;
readonly shouldCheck: boolean;
} {
const nextCount = count + 1;
if (nextCount >= HIDDEN_UPDATE_TAP_COUNT) {
return {
nextCount: 0,
shouldCheck: true,
};
}
return {
nextCount,
shouldCheck: false,
};
}
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
const client = options.client ?? Updates;
if (!client.isEnabled) return;
if (appUpdateCheckInFlight) {
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
return;
}
const progress: AppUpdateCheckProgress = {
failure: undefined,
state: undefined,
};
const failureListeners = new Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>();
const stateListeners = new Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>();
if (options.onFailure) failureListeners.add(options.onFailure);
if (options.onStateChange) stateListeners.add(options.onStateChange);
const deferred = createDeferred();
const inFlight: AppUpdateCheckInFlight = {
failureListeners,
progress,
promise: deferred.promise,
stateListeners,
};
// Publish the operation before any state listener can synchronously re-enter.
appUpdateCheckInFlight = inFlight;
const execution = performAppUpdateCheck(client, {
onFailure: (message) => {
progress.failure = message;
notifyListeners(failureListeners, message);
},
onStateChange: (state) => {
progress.state = state;
notifyListeners(stateListeners, state);
},
});
void execution.then(deferred.resolve, deferred.reject);
try {
await deferred.promise;
} finally {
if (appUpdateCheckInFlight === inFlight) {
appUpdateCheckInFlight = undefined;
}
}
}
function createDeferred(): Deferred {
let reject!: Deferred["reject"];
let resolve!: Deferred["resolve"];
const promise = new Promise<void>((resolvePromise, rejectPromise) => {
resolve = () => resolvePromise();
reject = rejectPromise;
});
return { promise, reject, resolve };
}
function notifyListeners<A>(listeners: ReadonlySet<(value: A) => void>, value: A): void {
// A listener can synchronously subscribe another caller. Snapshot so that
// caller receives only observeAppUpdateCheck's explicit current-value replay.
const snapshot = Array.from(listeners);
for (const listener of snapshot) listener(value);
}
async function observeAppUpdateCheck(
inFlight: AppUpdateCheckInFlight,
options: AppUpdateCheckOptions,
): Promise<void> {
const onFailure = options.onFailure;
const onStateChange = options.onStateChange;
if (onFailure) {
inFlight.failureListeners.add(onFailure);
if (inFlight.progress.failure) onFailure(inFlight.progress.failure);
}
if (onStateChange) {
inFlight.stateListeners.add(onStateChange);
if (inFlight.progress.state) onStateChange(inFlight.progress.state);
}
try {
await inFlight.promise;
} finally {
if (onFailure) inFlight.failureListeners.delete(onFailure);
if (onStateChange) inFlight.stateListeners.delete(onStateChange);
}
}
async function performAppUpdateCheck(
client: AppUpdateClient,
options: AppUpdateCheckOptions,
): Promise<void> {
const setState = options.onStateChange ?? (() => {});
setState("checking");
const check = await settlePromise(() => client.checkForUpdateAsync());
if (check._tag === "Failure") {
reportUpdateFailure(check, "Could not check for updates.", options.onFailure);
setState("idle");
return;
}
// A rollback directive (`eas update:rollback`) arrives as isAvailable: false
// with isRollBackToEmbedded: true. The running OTA still has to be dropped.
if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
setState("current");
return;
}
setState("downloading");
const fetched = await settlePromise(() => client.fetchUpdateAsync());
if (fetched._tag === "Failure") {
reportUpdateFailure(fetched, "Could not download the update.", options.onFailure);
setState("idle");
return;
}
// isNew is always false for a rollback, so it cannot be the sole gate.
if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
setState("current");
return;
}
setState("restarting");
const reloaded = await settlePromise(() => client.reloadAsync());
if (reloaded._tag === "Failure") {
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
setState("idle");
}
}
function reportUpdateFailure(
result: AtomCommandResult<unknown, unknown>,
fallback: string,
onFailure: AppUpdateCheckOptions["onFailure"],
): void {
reportAtomCommandResult(result, { label: "app update check" });
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
const error = squashAtomCommandFailure(result);
onFailure?.(error instanceof Error ? error.message : fallback);
}
export function createAppUpdateLaunchCheck(
client: AppUpdateClient = Updates,
): () => Promise<void> | undefined {
let started = false;
return () => {
if (started || !client.isEnabled) return undefined;
started = true;
return runAppUpdateCheck({ client });
};
}
export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();
+16 -1
View File
@@ -198,12 +198,27 @@ export function resolveTextScaleVariables(baseFontSize: number): Record<string,
for (const [name, role] of Object.entries(TEXT_SCALE_VARIABLE_ROLES)) {
variables[name] = Math.max(8, Math.round(role.fontSize * scale));
variables[`${name}--line-height`] = Math.max(10, Math.round(role.lineHeight * scale));
variables[`${name}--line-height`] = scaledTypographyLineHeight(role, baseFontSize);
}
return variables;
}
/**
* The line height a MOBILE_TYPOGRAPHY role renders at under the given base
* font size — the same value resolveTextScaleVariables injects for the role's
* `--text-*--line-height` variable. For layout code that must predict
* text-driven heights (e.g. the thread feed's fixed item sizes) instead of
* measuring them.
*/
export function scaledTypographyLineHeight(
role: { readonly lineHeight: number },
baseFontSize: number,
): number {
const scale = normalizeBaseFontSize(baseFontSize) / DEFAULT_BASE_FONT_SIZE;
return Math.max(10, Math.round(role.lineHeight * scale));
}
export function resolveNativeMarkdownTypography(baseFontSize: number): NativeMarkdownTypography {
const fontSizes = resolveMarkdownFontSizes(baseFontSize);
return {
-8
View File
@@ -65,14 +65,6 @@ export async function pickComposerImages(input: { readonly existingCount: number
};
}
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
if (!permission.granted) {
return {
images: [],
error: "Allow photo library access to attach images.",
};
}
const result = await imagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsMultipleSelection: true,
Loaded 100 of 494 files, more files were not shown because too many files have changed in this diff. Show more