Compare commits
76
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d7f9bdea4 | ||
|
|
6c4dfc8d80 | ||
|
|
436f8c54b0 | ||
|
|
e4829603ff | ||
|
|
1d77cec991 | ||
|
|
4ba4871af7 | ||
|
|
edc503a7a8 | ||
|
|
323dc321a2 | ||
|
|
6154b46cb8 | ||
|
|
abc409c2d4 | ||
|
|
1877237c7a | ||
|
|
e0513d2983 | ||
|
|
9dd425b223 | ||
|
|
50871eb5de | ||
|
|
4b71a2ae2f | ||
|
|
197d348711 | ||
|
|
5c9358acaa | ||
|
|
cbe8052020 | ||
|
|
69a18ce912 | ||
|
|
f0c6ba9946 | ||
|
|
90f3913a81 | ||
|
|
2652fee49b | ||
|
|
2f466ffc9c | ||
|
|
9146ed2f49 | ||
|
|
f0f16e4f6e | ||
|
|
00da6b57a4 | ||
|
|
6ab2f16809 | ||
|
|
6efcf3e10c | ||
|
|
748203ea19 | ||
|
|
b125b76351 | ||
|
|
758decaa56 | ||
|
|
2d9066e089 | ||
|
|
35a684000d | ||
|
|
9e3e9bb4f0 | ||
|
|
a8e05cbb92 | ||
|
|
e6987965f6 | ||
|
|
fc28abf24b | ||
|
|
85a8986870 | ||
|
|
faea70aeba | ||
|
|
d19039aeef | ||
|
|
49c0d96edf | ||
|
|
3137c2b162 | ||
|
|
c3e8fb67d7 | ||
|
|
72b960fa39 | ||
|
|
08e4932f04 | ||
|
|
1b4830ff06 | ||
|
|
694f8d1c6e | ||
|
|
1b61ce1112 | ||
|
|
60af905e70 | ||
|
|
8650f05f95 | ||
|
|
8fe8f9a9c1 | ||
|
|
936593c258 | ||
|
|
2919147c80 | ||
|
|
1ba3d01bc6 | ||
|
|
5fcdefd057 | ||
|
|
38a6e3ce65 | ||
|
|
f2d2fb2f24 | ||
|
|
8829e2f9b9 | ||
|
|
2deea7abb0 | ||
|
|
b64ae880e0 | ||
|
|
887dd6e455 | ||
|
|
f1a68ac9b0 | ||
|
|
55dd01612e | ||
|
|
3c50a64885 | ||
|
|
9ccfd9dfef | ||
|
|
4f584da0f8 | ||
|
|
362f127922 | ||
|
|
9cf9fc9c5c | ||
|
|
e00781a661 | ||
|
|
d25b15737a | ||
|
|
b0c4992c79 | ||
|
|
dd5ea32488 | ||
|
|
c13a021e43 | ||
|
|
476d69cd1d | ||
|
|
a148e08197 | ||
|
|
831eb66fee |
No files matched your search
@@ -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
|
||||
@@ -38,13 +38,20 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
|
||||
- name: Deploy production relay stage
|
||||
id: deploy
|
||||
|
||||
@@ -2,13 +2,18 @@ name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
types: [opened, reopened, synchronize, labeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
|
||||
if: |
|
||||
contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
concurrency:
|
||||
group: mobile-eas-preview-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
@@ -34,6 +39,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- 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'
|
||||
|
||||
@@ -57,6 +57,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- 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: |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -30,6 +30,7 @@ dist-electron/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
model: claude-opus-5
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
|
||||
@@ -1,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.
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.31",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -55,6 +55,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
@@ -63,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
calls.setDockIcon.push(iconPath);
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
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,
|
||||
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: (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));
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
},
|
||||
|
||||
@@ -49,20 +49,41 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("DesktopObservability", () => {
|
||||
it("advances a retained output offset instead of repeatedly copying a full head chunk", () => {
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const initial = DesktopObservability.appendBoundedOutputChunk(
|
||||
{
|
||||
runId: "test-run",
|
||||
startDetails: "pid=123",
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
},
|
||||
"stderr",
|
||||
new Uint8Array(maxBufferedBytes),
|
||||
);
|
||||
const initialBackingBuffer = initial.chunks[0]?.chunk.buffer;
|
||||
|
||||
const next = DesktopObservability.appendBoundedOutputChunk(initial, "stderr", Uint8Array.of(1));
|
||||
|
||||
assert.equal(next.chunks[0]?.chunk.buffer, initialBackingBuffer);
|
||||
assert.equal(next.chunks[0]?.offset, 1);
|
||||
assert.equal(next.byteLength, maxBufferedBytes);
|
||||
});
|
||||
|
||||
it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -112,26 +133,34 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const tracePath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
yield* outputLog.beginSession({
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
assert.isFalse(yield* fileSystem.exists(logPath));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
yield* outputLog.beginSession({ details: "pid=456" });
|
||||
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n"));
|
||||
yield* outputLog.discardSession;
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
@@ -139,16 +168,18 @@ describe("DesktopObservability", () => {
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
assert.equal(boundary.message, "backend child process session start");
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.instanceId, "primary");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(start.message, "backend child process failure output start");
|
||||
assert.equal(start.level, "ERROR");
|
||||
assert.equal(start.annotations.component, "desktop-backend-child");
|
||||
assert.equal(start.annotations.runId, "test-run");
|
||||
assert.equal(start.annotations.instanceId, "primary");
|
||||
assert.equal(start.annotations.phase, "START");
|
||||
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
assert.equal(output.message, "backend child process output");
|
||||
assert.equal(output.level, "INFO");
|
||||
@@ -157,6 +188,141 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.annotations.instanceId, "primary");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
|
||||
assert.equal(end.message, "backend child process failure output end");
|
||||
assert.equal(end.level, "ERROR");
|
||||
assert.equal(end.annotations.instanceId, "primary");
|
||||
assert.equal(end.annotations.phase, "END");
|
||||
assert.equal(end.annotations.details, "code=1");
|
||||
|
||||
const traceRecords = (yield* fileSystem.readFileString(tracePath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => decodeTraceRecordLine(line));
|
||||
assert.isFalse(
|
||||
traceRecords.some(
|
||||
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps buffering output after a non-terminal failure snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-snapshot-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
|
||||
yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
|
||||
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
);
|
||||
|
||||
const records = yield* Effect.forEach(
|
||||
(yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
|
||||
(line) => decodeDesktopBackendChildLogRecord(line),
|
||||
);
|
||||
assert.equal(
|
||||
records.some((record) => record.annotations.text === "after timeout\n"),
|
||||
true,
|
||||
);
|
||||
assert.equal(records.at(-1)?.annotations.details, "code=1");
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only the last mebibyte of backend child output", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-bound-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const discardedPrefixBytes = 128;
|
||||
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
|
||||
output.fill("x".charCodeAt(0));
|
||||
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stderr", output);
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const text = record.annotations.text;
|
||||
assert.equal(typeof text, "string");
|
||||
if (typeof text !== "string") {
|
||||
return;
|
||||
}
|
||||
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
|
||||
assert.isFalse(text.includes("y"));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds the number of retained backend child output chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-chunks-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
|
||||
}
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
assert.equal(lines.length, 258);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
|
||||
@@ -24,7 +24,9 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
@@ -32,14 +34,14 @@ export interface RotatingLogFileWriter {
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
readonly persistFailureSnapshot: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
// Factory for per-instance backend output logs. `forInstance(id)` returns
|
||||
@@ -127,10 +129,80 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
readonly offset: number;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
export function appendBoundedOutputChunk(
|
||||
session: BackendOutputSession,
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): BackendOutputSession {
|
||||
if (chunk.byteLength === 0) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const retainedChunk =
|
||||
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
|
||||
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
|
||||
: chunk.slice();
|
||||
const chunks = [...session.chunks, { streamName, chunk: retainedChunk, offset: 0 }];
|
||||
let byteLength = session.byteLength + retainedChunk.byteLength;
|
||||
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
|
||||
let firstRetainedIndex = 0;
|
||||
|
||||
while (overflow > 0) {
|
||||
const first = chunks[firstRetainedIndex];
|
||||
if (!first) break;
|
||||
const retainedByteLength = first.chunk.byteLength - first.offset;
|
||||
if (retainedByteLength <= overflow) {
|
||||
overflow -= retainedByteLength;
|
||||
byteLength -= retainedByteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
offset: first.offset + overflow,
|
||||
};
|
||||
byteLength -= overflow;
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
const excessChunks = Math.max(
|
||||
0,
|
||||
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
|
||||
);
|
||||
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
|
||||
const chunk = chunks[index];
|
||||
byteLength -= chunk ? chunk.chunk.byteLength - chunk.offset : 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
@@ -345,47 +417,93 @@ const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): DesktopBackendOutputLogShape =>
|
||||
): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
Option.match(sink, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
Effect.gen(function* () {
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
|
||||
function* (session: BackendOutputSession, details: string) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
phase,
|
||||
phase: "START",
|
||||
details: session.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk.subarray(output.offset)),
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
);
|
||||
return {
|
||||
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* Ref.set(
|
||||
sessionRef,
|
||||
Option.some({
|
||||
runId,
|
||||
startDetails: sanitizeLogValue(details),
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailureSnapshot: Effect.fn(
|
||||
"desktop.observability.backendOutput.persistFailureSnapshot",
|
||||
)(function* ({ details }) {
|
||||
const session = yield* Ref.get(sessionRef);
|
||||
if (Option.isSome(session)) {
|
||||
yield* writeFailure(session.value, details);
|
||||
}
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
|
||||
function* ({ details }) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
|
||||
if (Option.isNone(session)) return;
|
||||
yield* writeFailure(session.value, details);
|
||||
},
|
||||
),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
} satisfies DesktopBackendOutputLogShape;
|
||||
}),
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
@@ -412,10 +530,9 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
return makeBackendOutputLogShape(environment, id, cached).pipe(
|
||||
Effect.map((outputLog) => [outputLog, cache] as const),
|
||||
);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
@@ -424,11 +541,19 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
return { sink, next };
|
||||
}),
|
||||
Effect.flatMap(({ sink, next }) =>
|
||||
makeBackendOutputLogShape(environment, id, sink).pipe(
|
||||
Effect.map(
|
||||
(outputLog) =>
|
||||
[
|
||||
outputLog,
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -4,6 +4,8 @@ import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const {
|
||||
appendSwitchMock,
|
||||
autoUpdaterOnMock,
|
||||
autoUpdaterRemoveListenerMock,
|
||||
exitMock,
|
||||
getAppPathMock,
|
||||
getVersionMock,
|
||||
@@ -23,6 +25,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"),
|
||||
@@ -43,6 +47,10 @@ const {
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
autoUpdater: {
|
||||
on: autoUpdaterOnMock,
|
||||
removeListener: autoUpdaterRemoveListenerMock,
|
||||
},
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
@@ -77,6 +85,8 @@ import * as ElectronApp from "./ElectronApp.ts";
|
||||
describe("ElectronApp", () => {
|
||||
beforeEach(() => {
|
||||
appendSwitchMock.mockClear();
|
||||
autoUpdaterOnMock.mockClear();
|
||||
autoUpdaterRemoveListenerMock.mockClear();
|
||||
exitMock.mockClear();
|
||||
onMock.mockClear();
|
||||
quitMock.mockClear();
|
||||
@@ -153,4 +163,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)),
|
||||
);
|
||||
});
|
||||
@@ -57,6 +57,7 @@ export class ElectronApp extends Context.Service<
|
||||
) => 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 +67,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,
|
||||
@@ -150,6 +154,7 @@ export const make = ElectronApp.of({
|
||||
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 +183,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);
|
||||
@@ -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),
|
||||
);
|
||||
|
||||
|
||||
@@ -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* () {
|
||||
|
||||
@@ -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,388 @@
|
||||
import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
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());
|
||||
@@ -40,11 +40,13 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
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"]);
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
---
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import {
|
||||
ANDROID_PLAY_STORE_URL,
|
||||
GITHUB_REPOSITORY_URL,
|
||||
IOS_APP_STORE_URL,
|
||||
MARKETING_STATS,
|
||||
} from "../lib/site";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
@@ -69,6 +74,8 @@ const {
|
||||
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<a href="/download">Download</a>
|
||||
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS app</a>
|
||||
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android app</a>
|
||||
<a href="/terms-of-service">Terms</a>
|
||||
<a href="/privacy-policy">Privacy</a>
|
||||
<a href="/security-policy">Security</a>
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
|
||||
|
||||
export const IOS_APP_STORE_URL =
|
||||
"https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824";
|
||||
|
||||
export const ANDROID_PLAY_STORE_URL =
|
||||
"https://play.google.com/store/apps/details?id=com.t3tools.t3code";
|
||||
|
||||
export const MARKETING_STATS = {
|
||||
githubStars: "14k+",
|
||||
users: "100,000",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { RELEASES_URL } from "../lib/releases";
|
||||
import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
@@ -57,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 & 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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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:",
|
||||
|
||||
@@ -47,7 +47,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 +189,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 +284,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 +301,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 +328,7 @@ function RootStackLayout(props: {
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
|
||||
@@ -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 ? (
|
||||
|
||||
@@ -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 (
|
||||
<>
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
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 { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
@@ -12,10 +10,13 @@ import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
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 +60,14 @@ 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();
|
||||
// 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);
|
||||
@@ -291,7 +285,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 +323,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 +341,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 +358,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 +416,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"
|
||||
|
||||
@@ -11,6 +11,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 +26,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],
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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";
|
||||
@@ -21,6 +22,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
|
||||
@@ -416,6 +418,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 +573,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 +634,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();
|
||||
@@ -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 {
|
||||
|
||||
@@ -957,6 +957,11 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
|
||||
|
||||
function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
|
||||
const grouped: ThreadFeedEntry[] = [];
|
||||
// Mutable backing array for the trailing group so appending an activity is
|
||||
// O(1) instead of re-copying the group (which made this loop quadratic on
|
||||
// long tool runs). The array is only mutated while it is the trailing group.
|
||||
let openGroupActivities: ThreadFeedActivity[] | null = null;
|
||||
let openGroupTurnId: TurnId | null = null;
|
||||
|
||||
for (const entry of entries) {
|
||||
// Skip empty messages so they don't break activity grouping.
|
||||
@@ -966,24 +971,23 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
|
||||
|
||||
if (entry.type !== "activity") {
|
||||
grouped.push(entry);
|
||||
openGroupActivities = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
const previous = grouped.at(-1);
|
||||
if (previous?.type === "activity-group" && previous.turnId === entry.turnId) {
|
||||
grouped[grouped.length - 1] = {
|
||||
...previous,
|
||||
activities: [...previous.activities, entry.activity],
|
||||
};
|
||||
if (openGroupActivities !== null && openGroupTurnId === entry.turnId) {
|
||||
openGroupActivities.push(entry.activity);
|
||||
continue;
|
||||
}
|
||||
|
||||
openGroupActivities = [entry.activity];
|
||||
openGroupTurnId = entry.turnId;
|
||||
grouped.push({
|
||||
type: "activity-group",
|
||||
id: entry.id,
|
||||
createdAt: entry.createdAt,
|
||||
turnId: entry.turnId,
|
||||
activities: [entry.activity],
|
||||
activities: openGroupActivities,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1225,13 +1229,24 @@ function appendPresentedFeedEntry(
|
||||
});
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
/**
|
||||
* Sorts activities into lifecycle order. `derivePendingApprovals` and
|
||||
* `derivePendingUserInputs` both expect this ordering; sorting once and
|
||||
* passing the result to both avoids re-sorting the full activity history
|
||||
* per derivation.
|
||||
*/
|
||||
export function sortThreadActivities(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
return Arr.sort(activities, activityOrder);
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
|
||||
for (const activity of ordered) {
|
||||
for (const activity of sortedActivities) {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
@@ -1273,12 +1288,11 @@ export function derivePendingApprovals(
|
||||
}
|
||||
|
||||
export function derivePendingUserInputs(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingUserInput[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
|
||||
for (const activity of ordered) {
|
||||
for (const activity of sortedActivities) {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
|
||||
@@ -340,7 +340,8 @@ function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null {
|
||||
return {
|
||||
type: "spacing",
|
||||
spacing: typeof child.props.width === "number" ? child.props.width : 8,
|
||||
};
|
||||
flexible: Boolean(child.props.flexible),
|
||||
} as NativeStackHeaderItem;
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -351,6 +352,11 @@ function collectToolbarItems(children: ReactNode): NativeStackHeaderItem[] {
|
||||
Children.forEach(children, (child) => {
|
||||
const item = convertToolbarChild(child);
|
||||
if (item) {
|
||||
if (item.type === "spacing") {
|
||||
// Native inserts spacing items at `index`, treating a missing index
|
||||
// as 0 — which would move the spacer in front of earlier siblings.
|
||||
(item as { index?: number }).index = items.length;
|
||||
}
|
||||
items.push(item);
|
||||
}
|
||||
});
|
||||
@@ -440,6 +446,7 @@ function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) {
|
||||
NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel";
|
||||
|
||||
function NativeHeaderToolbarSpacer(_props: {
|
||||
readonly flexible?: boolean;
|
||||
readonly sharesBackground?: boolean;
|
||||
readonly width?: number;
|
||||
}) {
|
||||
|
||||
@@ -46,6 +46,7 @@ const MobileDatabaseOperation = Schema.Literals([
|
||||
"load-cache",
|
||||
"save-cache",
|
||||
"remove-cache",
|
||||
"clear-cache-kind",
|
||||
"clear-environment-cache",
|
||||
"clear-all-caches",
|
||||
"inspect-caches",
|
||||
@@ -203,6 +204,10 @@ export class MobileDatabase extends Context.Service<
|
||||
kind: ClientCacheKind,
|
||||
cacheKey: string,
|
||||
) => Effect.Effect<void, MobileDatabaseError>;
|
||||
readonly clearCacheKind: (
|
||||
environmentId: EnvironmentId,
|
||||
kind: ClientCacheKind,
|
||||
) => Effect.Effect<void, MobileDatabaseError>;
|
||||
readonly clearEnvironmentCache: (
|
||||
environmentId: EnvironmentId,
|
||||
) => Effect.Effect<void, MobileDatabaseError>;
|
||||
@@ -322,6 +327,17 @@ const makeAvailable = Effect.gen(function* () {
|
||||
catch: databaseError("remove-cache"),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
clearCacheKind: Effect.fn("MobileDatabase.clearCacheKind")((environmentId, kind) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
database.runAsync(
|
||||
"DELETE FROM client_cache WHERE environment_id = ? AND kind = ?",
|
||||
environmentId,
|
||||
kind,
|
||||
),
|
||||
catch: databaseError("clear-cache-kind"),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")((environmentId) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
@@ -392,6 +408,7 @@ function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"]
|
||||
loadCache: () => fail,
|
||||
saveCache: () => fail,
|
||||
removeCache: () => fail,
|
||||
clearCacheKind: () => fail,
|
||||
clearEnvironmentCache: () => fail,
|
||||
clearAllCaches: fail,
|
||||
inspectCaches: fail,
|
||||
|
||||
@@ -25,8 +25,9 @@ export interface Preferences {
|
||||
readonly projectGroupingEnabled?: boolean;
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
* device.
|
||||
* client-settings sync, so the flat v2 thread list is opted out of per
|
||||
* device. Undefined means the user has never chosen, which resolves to on —
|
||||
* see `resolveThreadListV2Enabled`.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
createThreadSearchResultsAtomFamily,
|
||||
makeThreadSearchKey,
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import * as Option from "effect/Option";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { orchestrationEnvironment } from "./orchestration";
|
||||
@@ -15,7 +22,22 @@ import {
|
||||
|
||||
const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
|
||||
const COMPOSER_PATH_SEARCH_LIMIT = 20;
|
||||
const THREAD_SEARCH_DEBOUNCE_MS = 200;
|
||||
const VCS_REF_LIST_LIMIT = 100;
|
||||
const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
|
||||
const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
|
||||
matches: EMPTY_THREAD_SEARCH_MATCHES,
|
||||
isLoading: false,
|
||||
}).pipe(Atom.withLabel("mobile:thread-search:empty"));
|
||||
|
||||
const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
getSearchAtom: (environmentId, query) =>
|
||||
orchestrationEnvironment.threadSearch({
|
||||
environmentId,
|
||||
input: { query },
|
||||
}),
|
||||
labelPrefix: "mobile:thread-search",
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
@@ -45,6 +67,31 @@ function useDebouncedValue<A>(value: A, delayMs: number): A {
|
||||
return debounced;
|
||||
}
|
||||
|
||||
export function useThreadSearch(
|
||||
environmentIds: ReadonlyArray<EnvironmentId>,
|
||||
query: string,
|
||||
): {
|
||||
readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
|
||||
readonly isPending: boolean;
|
||||
} {
|
||||
const normalizedQuery = query.trim();
|
||||
const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
|
||||
const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
|
||||
const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
|
||||
const searchKey = useMemo(
|
||||
() => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
|
||||
[environmentIds, settledQuery],
|
||||
);
|
||||
const result = useAtomValue(
|
||||
searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
|
||||
);
|
||||
const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
|
||||
return {
|
||||
matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
|
||||
isPending: canSearch && (isDebouncing || result.isLoading),
|
||||
};
|
||||
}
|
||||
|
||||
export function useThreadDetail(
|
||||
environmentId: EnvironmentId | null,
|
||||
threadId: ThreadId | null,
|
||||
|
||||
@@ -88,11 +88,23 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
return loadPromise;
|
||||
};
|
||||
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
|
||||
serialize(async () => {
|
||||
// The queued atom drives the composer's immediate "queued" feedback, so it
|
||||
// is published synchronously; the durable write happens behind it and rolls
|
||||
// the message back out if it fails (durability only matters for crash
|
||||
// recovery, not for the in-session queue).
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> => {
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
]);
|
||||
return serialize(async () => {
|
||||
try {
|
||||
await options.storage.write(message);
|
||||
} catch (cause) {
|
||||
// Roll back by reference, not messageId: a retry enqueue with the same
|
||||
// id may have optimistically replaced this attempt while the write was
|
||||
// in flight, and its entry must survive this attempt's failure.
|
||||
setMessages(currentMessages().filter((candidate) => candidate !== message));
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "enqueue",
|
||||
environmentId: message.environmentId,
|
||||
@@ -101,11 +113,15 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
]);
|
||||
});
|
||||
};
|
||||
|
||||
// Resolves once all pending mutations (including any in-flight enqueue
|
||||
// write) have settled, reporting whether the message is still queued. The
|
||||
// drain awaits this before dispatching so a message whose durable write
|
||||
// later fails can never have been delivered first.
|
||||
const confirmQueued = (message: QueuedThreadMessage): Promise<boolean> =>
|
||||
serialize(async () => currentMessages().some((candidate) => candidate === message));
|
||||
|
||||
// Rewrites an already-queued message. A no-op when the message has been
|
||||
// removed in the meantime (e.g. deleted or delivered), so a trailing editor
|
||||
@@ -204,6 +220,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
serialize,
|
||||
load,
|
||||
enqueue,
|
||||
confirmQueued,
|
||||
update,
|
||||
remove,
|
||||
clearEnvironment,
|
||||
|
||||
@@ -294,6 +294,111 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("publishes an enqueued message before the durable write resolves", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
let releaseWrite!: () => void;
|
||||
const writeBlocked = new Promise<void>((resolve) => {
|
||||
releaseWrite = resolve;
|
||||
});
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => writeBlocked,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
|
||||
const enqueueing = manager.enqueue(message);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
|
||||
releaseWrite();
|
||||
await enqueueing;
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("rolls an enqueued message back out when the durable write fails", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const writeCause = new Error("disk full");
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => {
|
||||
throw writeCause;
|
||||
},
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
|
||||
await expect(manager.enqueue(message)).rejects.toEqual(
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "enqueue",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause: writeCause,
|
||||
}),
|
||||
);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps a same-id retry queued when the first attempt's write fails", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
let failNextWrite = true;
|
||||
let releaseFirstWrite!: () => void;
|
||||
const firstWriteBlocked = new Promise<void>((resolve) => {
|
||||
releaseFirstWrite = resolve;
|
||||
});
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => {
|
||||
if (failNextWrite) {
|
||||
failNextWrite = false;
|
||||
await firstWriteBlocked;
|
||||
throw new Error("disk full");
|
||||
}
|
||||
},
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const retried = { ...message, text: "retried" };
|
||||
|
||||
const first = manager.enqueue(message);
|
||||
const second = manager.enqueue(retried);
|
||||
releaseFirstWrite();
|
||||
await expect(first).rejects.toBeInstanceOf(ThreadOutboxManagerError);
|
||||
await second;
|
||||
|
||||
// The failed first attempt must not roll back the retry that replaced it.
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [retried],
|
||||
});
|
||||
await expect(manager.confirmQueued(retried)).resolves.toBe(true);
|
||||
await expect(manager.confirmQueued(message)).resolves.toBe(false);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("replaces an existing message when an enqueue retry uses the same id", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const manager = createThreadOutboxManager({
|
||||
|
||||
@@ -20,6 +20,11 @@ export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promis
|
||||
return threadOutboxManager.enqueue(message);
|
||||
}
|
||||
|
||||
/** Waits for pending writes to settle; false if the message was rolled back. */
|
||||
export function confirmThreadOutboxMessageQueued(message: QueuedThreadMessage): Promise<boolean> {
|
||||
return threadOutboxManager.confirmQueued(message);
|
||||
}
|
||||
|
||||
/** Rewrite a queued message; no-op (false) if it was removed in the meantime. */
|
||||
export function updateThreadOutboxMessage(message: QueuedThreadMessage): Promise<boolean> {
|
||||
return threadOutboxManager.update(message);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -70,14 +71,19 @@ export function useSelectedThreadRequests() {
|
||||
null,
|
||||
);
|
||||
|
||||
const activePendingApprovals = useMemo(
|
||||
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
|
||||
// Sort once; both derivations expect the same lifecycle ordering.
|
||||
const sortedActivities = useMemo(
|
||||
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
() => derivePendingUserInputs(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
@@ -148,27 +149,36 @@ export function useThreadComposerState() {
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId,
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
} catch (error) {
|
||||
// Enqueue publishes the queued atom synchronously (the durable write
|
||||
// happens behind it), so clearing the draft here gives send feedback on
|
||||
// the tap frame instead of after file I/O. If the write fails the message
|
||||
// is rolled out of the queue and the content is merged back into the
|
||||
// draft, preserving anything typed since.
|
||||
const enqueuePromise = enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId,
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
enqueuePromise.catch((error: unknown) => {
|
||||
// Restore text via merge (idempotent) but attachments via the uncapped
|
||||
// append: the merge path slots existing attachments first and truncates
|
||||
// at the send limit, which would silently drop this message's images if
|
||||
// the user attached new ones while the write was in flight.
|
||||
void mergeComposerDraftContent(threadKey, { text, attachments: [] });
|
||||
appendComposerDraftAttachments(threadKey, attachments);
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
return messageId;
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
|
||||
@@ -21,7 +21,11 @@ import { toUploadChatImageAttachments } from "../lib/composerImages";
|
||||
import { randomHex } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useProjects, useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
confirmThreadOutboxMessageQueued,
|
||||
ensureThreadOutboxLoaded,
|
||||
removeThreadOutboxMessage,
|
||||
} from "./thread-outbox";
|
||||
import {
|
||||
isQueuedThreadCreationSendable,
|
||||
modelSelectionsEqual,
|
||||
@@ -33,7 +37,7 @@ import {
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { environmentThreadShells, threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
import {
|
||||
editingQueuedMessageIdsAtom,
|
||||
@@ -349,8 +353,32 @@ export function useThreadOutboxDrain(): void {
|
||||
return false;
|
||||
},
|
||||
);
|
||||
const delivery =
|
||||
deliveryAction === "remove"
|
||||
// Enqueues publish optimistically before their durable write settles.
|
||||
// Confirm the write landed (and the message wasn't rolled back) before
|
||||
// sending, so a failed write can never chase an already-delivered turn.
|
||||
const delivery = confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) => {
|
||||
if (!queued) {
|
||||
// Rolled back by a failed write; nothing to deliver or retry.
|
||||
return true;
|
||||
}
|
||||
// The guards evaluated before the confirmation await are stale by now:
|
||||
// the thread may have gone busy, or the user may have opened this
|
||||
// message in the editor. Re-read both and defer to the next drain pass
|
||||
// (returning true skips the failure/backoff path) rather than sending
|
||||
// a payload the user is editing or racing an active turn.
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) {
|
||||
return true;
|
||||
}
|
||||
const freshThread = findThread(
|
||||
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
|
||||
nextQueuedMessage,
|
||||
);
|
||||
const freshThreadBusy =
|
||||
freshThread?.session?.status === "running" || freshThread?.session?.status === "starting";
|
||||
if (deliveryAction === "send" && creation === undefined && freshThreadBusy) {
|
||||
return true;
|
||||
}
|
||||
return deliveryAction === "remove"
|
||||
? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
|
||||
: creation !== undefined
|
||||
? creationProjectCwd !== null
|
||||
@@ -359,6 +387,7 @@ export function useThreadOutboxDrain(): void {
|
||||
: thread !== undefined
|
||||
? sendQueuedMessage(nextQueuedMessage, thread)
|
||||
: Promise.resolve(false);
|
||||
});
|
||||
void delivery
|
||||
.then((sent) => {
|
||||
if (sent) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.31",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
Loaded 100 of 475 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user