Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7adbc1161 | ||
|
|
95f6b12918 | ||
|
|
926ff9baaa | ||
|
|
843adadac2 | ||
|
|
c010fc3f3f |
No files matched your search
@@ -6,10 +6,6 @@ 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
|
||||
@@ -18,11 +14,6 @@ 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
|
||||
@@ -31,11 +22,6 @@ 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
|
||||
|
||||
@@ -45,9 +31,6 @@ 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
|
||||
|
||||
@@ -64,11 +47,6 @@ 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
|
||||
@@ -77,39 +55,26 @@ 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-6vcpu-macos-26
|
||||
runs-on: blacksmith-12vcpu-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: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
run-install: true
|
||||
|
||||
- name: Install mobile native static analysis tools
|
||||
run: brew bundle install --file apps/mobile/Brewfile
|
||||
@@ -124,20 +89,13 @@ 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: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
run-install: true
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
@@ -38,20 +38,13 @@ 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: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
run-install: true
|
||||
|
||||
- name: Deploy production relay stage
|
||||
id: deploy
|
||||
|
||||
@@ -2,18 +2,13 @@ name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled]
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: |
|
||||
contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment')
|
||||
if: contains(github.event.pull_request.labels.*.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
|
||||
@@ -39,10 +34,6 @@ 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'
|
||||
@@ -50,9 +41,7 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -57,10 +57,6 @@ 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'
|
||||
@@ -68,9 +64,7 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -37,21 +37,13 @@ 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: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
@@ -85,21 +77,13 @@ 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: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
|
||||
@@ -38,10 +38,6 @@ 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
|
||||
@@ -88,10 +84,6 @@ 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
|
||||
@@ -200,10 +192,6 @@ 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
|
||||
@@ -281,19 +269,14 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3...
|
||||
run-install: true
|
||||
|
||||
- name: Build node-pty linux-x64 prebuild
|
||||
shell: bash
|
||||
@@ -343,29 +326,21 @@ 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
|
||||
@@ -376,26 +351,14 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/desktop...
|
||||
- --filter=t3...
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.rust_target }}
|
||||
run-install: true
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -635,19 +598,6 @@ 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:
|
||||
@@ -655,13 +605,6 @@ 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]
|
||||
@@ -681,10 +624,6 @@ 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
|
||||
@@ -720,24 +659,6 @@ 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
|
||||
|
||||
@@ -760,10 +681,6 @@ 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
|
||||
@@ -885,10 +802,6 @@ 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
|
||||
@@ -1003,10 +916,6 @@ 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
|
||||
@@ -1077,10 +986,6 @@ 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,7 +30,6 @@ 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-5
|
||||
model: claude-opus-4-8
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 295 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 310 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 9.3 KiB |
@@ -28,7 +28,7 @@ T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**.
|
||||
|
||||
**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.
|
||||
**Mobile** is a React native app for both iOS and Android. The mobile app allows for connecting to any T3 Code server to control work remotely. It is still in early access (Testflight), but it is pretty close to shipping globally.
|
||||
|
||||
## A note from Theo
|
||||
|
||||
@@ -59,7 +59,7 @@ We need to be on the same page with terminology. When communicating, use this la
|
||||
## 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.
|
||||
2. **Touching the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Read-only inspection is fine. 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
|
||||
@@ -72,7 +72,7 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
- **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`.
|
||||
- **Docs.** `docs/` mirrors this structure. Behavior changes that a user would notice belong in `docs/user/`; architecture changes in `docs/architecture/`; new vocabulary in `docs/reference/encyclopedia.md`.
|
||||
|
||||
## Dev servers
|
||||
|
||||
@@ -85,19 +85,10 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
|
||||
## 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.
|
||||
An empty database is a bad test. Seed your worktree's `.t3` instead of pointing at live state:
|
||||
|
||||
- Copy from `~/.t3/dev`, never from `~/.t3/userdata`.
|
||||
- Copy `state.sqlite` together with its `-wal` and `-shm` siblings, and only while no server has the source open. A live 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.
|
||||
|
||||
@@ -123,13 +114,13 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
|
||||
|
||||
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`
|
||||
Full glossary with file links: `docs/reference/encyclopedia.md`
|
||||
|
||||
## Where code lives
|
||||
|
||||
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code.
|
||||
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` and `docs/operations/effect-fn-checklist.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/contracts` - Effect/Schema contracts. Schema only, no 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.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# T3 Code
|
||||
|
||||
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).
|
||||
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app, [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.
|
||||
|
||||
@@ -17,13 +17,13 @@ We wanted something performant, remote-ready, and truly open. If we ever go the
|
||||
>
|
||||
> - 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 `agent login`
|
||||
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-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`
|
||||
|
||||
### 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+):
|
||||
The easiest way to test T3 Code is to run the server in your terminal:
|
||||
|
||||
```bash
|
||||
npx t3@latest
|
||||
@@ -61,20 +61,17 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be.
|
||||
|
||||
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
|
||||
|
||||
## Documentation
|
||||
|
||||
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).
|
||||
- [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)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.31",
|
||||
"version": "0.0.29",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -55,7 +55,6 @@ 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,
|
||||
|
||||
@@ -30,7 +30,6 @@ describe("DesktopLifecycle", () => {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -49,41 +49,20 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
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;
|
||||
@@ -133,34 +112,26 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
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.beginSession({
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
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))),
|
||||
@@ -168,18 +139,16 @@ describe("DesktopObservability", () => {
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
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(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(output.message, "backend child process output");
|
||||
assert.equal(output.level, "INFO");
|
||||
@@ -188,141 +157,6 @@ 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,9 +24,7 @@ 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 = 1_000;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
@@ -34,14 +32,14 @@ export interface RotatingLogFileWriter {
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
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
|
||||
@@ -129,80 +127,10 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
beginSession: () => Effect.void,
|
||||
writeSessionBoundary: () => 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;
|
||||
@@ -417,93 +345,47 @@ const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
): DesktopBackendOutputLogShape =>
|
||||
Option.match(sink, {
|
||||
onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
|
||||
function* (session: BackendOutputSession, details: string) {
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.runId,
|
||||
runId,
|
||||
instanceId: id,
|
||||
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",
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
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) {
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
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 runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
@@ -530,9 +412,10 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return makeBackendOutputLogShape(environment, id, cached).pipe(
|
||||
Effect.map((outputLog) => [outputLog, cache] as const),
|
||||
);
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
@@ -541,19 +424,11 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return { sink, next };
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
}),
|
||||
Effect.flatMap(({ sink, next }) =>
|
||||
makeBackendOutputLogShape(environment, id, sink).pipe(
|
||||
Effect.map(
|
||||
(outputLog) =>
|
||||
[
|
||||
outputLog,
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -52,7 +52,6 @@ function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
options?: {
|
||||
readonly appPath?: string;
|
||||
readonly dirname?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
@@ -60,7 +59,7 @@ function makeEnvironmentLayer(
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: options?.dirname ?? "/repo/apps/desktop/src",
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: options?.platform ?? "darwin",
|
||||
processArch: "x64",
|
||||
@@ -465,8 +464,6 @@ 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.
|
||||
@@ -716,97 +713,6 @@ 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,44 +141,6 @@ 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;
|
||||
@@ -364,9 +326,7 @@ const buildObservabilityFragment = (observabilitySettings: BackendObservabilityS
|
||||
|
||||
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
|
||||
function* (
|
||||
input: SharedBootstrapInput & {
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
},
|
||||
input: SharedBootstrapInput,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
@@ -385,12 +345,6 @@ 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),
|
||||
};
|
||||
|
||||
@@ -457,10 +411,6 @@ 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),
|
||||
};
|
||||
|
||||
@@ -671,11 +621,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const buildWindowsPrimaryConfig = Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
|
||||
return yield* resolvePrimaryStartConfig(shared).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
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";
|
||||
@@ -24,15 +21,10 @@ 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",
|
||||
@@ -49,8 +41,6 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
bootstrapDelivery: "fd3",
|
||||
extendEnv: true,
|
||||
@@ -62,16 +52,14 @@ 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, PlatformError.PlatformError>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly stdout?: Stream.Stream<Uint8Array>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
@@ -83,7 +71,7 @@ function makeProcess(options?: {
|
||||
kill: options?.kill ?? (() => Effect.void),
|
||||
stdin: Sink.drain,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
|
||||
getOutputFd: () => Stream.empty,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
});
|
||||
}
|
||||
@@ -124,14 +112,7 @@ interface MakeInstanceInput {
|
||||
failure: DesktopBackendManager.PreflightFailure,
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
readonly configResolve?: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
|
||||
readonly desktopTelemetryPublisher?: Partial<
|
||||
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
|
||||
>;
|
||||
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
|
||||
}
|
||||
|
||||
// Helper that constructs a primary backend instance using the factory
|
||||
@@ -141,11 +122,8 @@ interface MakeInstanceInput {
|
||||
// to drive the instance's lifecycle.
|
||||
function makeTestInstance(input: MakeInstanceInput) {
|
||||
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
|
||||
beginSession: () => Effect.void,
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
...input.backendOutputLog,
|
||||
};
|
||||
const servicesLayer = Layer.mergeAll(
|
||||
@@ -157,16 +135,6 @@ 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({
|
||||
@@ -182,12 +150,11 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
}
|
||||
|
||||
describe("DesktopBackendManager", () => {
|
||||
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
|
||||
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
|
||||
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>();
|
||||
@@ -202,10 +169,6 @@ 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({
|
||||
@@ -221,14 +184,12 @@ 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: {
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -249,400 +210,16 @@ 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* () {
|
||||
@@ -679,7 +256,8 @@ describe("DesktopBackendManager", () => {
|
||||
readyCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
|
||||
backendOutputLog: {
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -707,15 +285,9 @@ 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,
|
||||
@@ -724,16 +296,9 @@ describe("DesktopBackendManager", () => {
|
||||
const scope = yield* Scope.Scope;
|
||||
startCount += 1;
|
||||
yield* Queue.offer(startedPids, 123);
|
||||
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,
|
||||
);
|
||||
const close = Effect.sync(() => {
|
||||
closedCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
|
||||
|
||||
yield* Scope.addFinalizer(scope, close);
|
||||
|
||||
@@ -751,28 +316,7 @@ describe("DesktopBackendManager", () => {
|
||||
Effect.andThen(Deferred.succeed(ready, void 0)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
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;
|
||||
}),
|
||||
},
|
||||
onShutdown: Ref.set(backendReadyFlag, false),
|
||||
});
|
||||
assert.isTrue(Option.isNone(yield* instance.currentConfig));
|
||||
|
||||
@@ -786,21 +330,12 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(runningSnapshot.ready, true);
|
||||
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
|
||||
|
||||
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"));
|
||||
yield* instance.stop();
|
||||
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);
|
||||
@@ -808,213 +343,6 @@ 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* () {
|
||||
@@ -1055,7 +383,6 @@ 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(
|
||||
@@ -1075,15 +402,11 @@ 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);
|
||||
@@ -1334,13 +657,6 @@ 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,6 +33,7 @@ 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";
|
||||
@@ -45,13 +46,10 @@ 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);
|
||||
@@ -64,10 +62,7 @@ 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;
|
||||
|
||||
@@ -75,17 +70,13 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export interface BackendProcessContext {
|
||||
readonly executablePath: string;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly httpBaseUrl: URL;
|
||||
}
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
export interface DesktopBackendStartConfig {
|
||||
readonly executablePath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly env: Record<string, string | undefined>;
|
||||
// When true the spawner merges the desktop process.env on top of `env`;
|
||||
// when false `env` is passed verbatim. WSL mode opts out so a leaking
|
||||
@@ -115,122 +106,55 @@ export interface PreflightFailure {
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
url: Schema.instanceOf(URL),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
entryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
override get message() {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
executablePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
override get message() {
|
||||
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
|
||||
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: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -301,8 +225,6 @@ 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 {
|
||||
@@ -344,130 +266,76 @@ const calculateRestartDelay = (attempt: number): Duration.Duration =>
|
||||
|
||||
const closeRun = (
|
||||
run: ActiveBackendRun,
|
||||
parentScope: Scope.Scope,
|
||||
options?: { readonly timeout?: Duration.Duration },
|
||||
): Effect.Effect<boolean> => {
|
||||
): Effect.Effect<void> => {
|
||||
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;
|
||||
|
||||
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)),
|
||||
),
|
||||
);
|
||||
return (
|
||||
options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
export const waitForHttpReady = (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
const waitForHttpReady = (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
return waitForHttpReadyShared({
|
||||
baseUrl: options.httpBaseUrl.href,
|
||||
baseUrl: baseUrl.href,
|
||||
path: BACKEND_READINESS_PATH,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
|
||||
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
|
||||
makeError: ({ cause }) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
|
||||
});
|
||||
};
|
||||
|
||||
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, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
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,
|
||||
}),
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
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({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, 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,
|
||||
@@ -482,131 +350,34 @@ export 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 } : {}),
|
||||
...(options.bootstrapDelivery === "fd3"
|
||||
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
|
||||
: {}),
|
||||
});
|
||||
|
||||
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>> = [];
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
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,
|
||||
);
|
||||
}
|
||||
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* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).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(
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
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;
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
// Factory for one pooled backend instance. The returned instance owns
|
||||
@@ -623,14 +394,12 @@ 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);
|
||||
@@ -675,12 +444,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -699,9 +462,6 @@ 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
|
||||
@@ -801,8 +561,6 @@ 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,
|
||||
},
|
||||
@@ -813,70 +571,54 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
) {
|
||||
yield* mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
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,
|
||||
};
|
||||
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) {
|
||||
return [
|
||||
{
|
||||
isCurrentRun: true,
|
||||
nextState: next,
|
||||
pid: currentRun.pid,
|
||||
exitObserved: currentRun.exitObserved,
|
||||
stopRequested: currentRun.stopRequested,
|
||||
wasReady: latest.ready,
|
||||
isCurrentRun: false,
|
||||
nextState: latest,
|
||||
pid: Option.none<number>(),
|
||||
},
|
||||
next,
|
||||
latest,
|
||||
] 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)) {
|
||||
if (exitObserved && !stopRequested) {
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
} else {
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
}
|
||||
if (wasReady) {
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "END",
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
}
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
}
|
||||
|
||||
if (isCurrentRun && nextState.desiredRunning) {
|
||||
@@ -888,23 +630,16 @@ 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.beginSession({
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
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);
|
||||
@@ -927,16 +662,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
|
||||
}),
|
||||
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,
|
||||
});
|
||||
},
|
||||
),
|
||||
onReadinessFailure: (error) =>
|
||||
logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -1021,92 +750,41 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
|
||||
readonly timeout?: Duration.Duration;
|
||||
}) {
|
||||
const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
|
||||
const { active, restartFiber } = yield* mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
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;
|
||||
});
|
||||
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);
|
||||
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) =>
|
||||
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;
|
||||
}
|
||||
}),
|
||||
onSome: (run) => closeRun(run, options),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,13 +5,11 @@ 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";
|
||||
@@ -58,21 +56,10 @@ function makePoolLayer(
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () =>
|
||||
Effect.succeed({
|
||||
beginSession: () => Effect.void,
|
||||
writeSessionBoundary: () => 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,7 +97,6 @@ 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";
|
||||
|
||||
@@ -177,8 +176,7 @@ export type BackendInstanceFactoryRequirements =
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
|
||||
interface ActiveRegisteredInstance {
|
||||
readonly _tag: "Active";
|
||||
|
||||
@@ -57,7 +57,6 @@ 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,
|
||||
@@ -154,7 +153,6 @@ 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) =>
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
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,7 +24,6 @@ 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";
|
||||
@@ -53,7 +52,6 @@ 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";
|
||||
@@ -115,7 +113,6 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -163,7 +160,6 @@ 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,92 +982,6 @@ 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,17 +671,10 @@ 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.fnUntraced(function* (
|
||||
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
|
||||
webContentsId: number,
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
@@ -859,53 +852,11 @@ 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.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 handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
|
||||
function* (method: string, params: Record<string, unknown>) {
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
},
|
||||
);
|
||||
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
|
||||
runFork(handleDebuggerMessage(method, params));
|
||||
};
|
||||
|
||||
@@ -1,388 +0,0 @@
|
||||
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));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,379 +0,0 @@
|
||||
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,7 +40,6 @@ 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,
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
---
|
||||
import {
|
||||
ANDROID_PLAY_STORE_URL,
|
||||
GITHUB_REPOSITORY_URL,
|
||||
IOS_APP_STORE_URL,
|
||||
MARKETING_STATS,
|
||||
} from "../lib/site";
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
@@ -74,8 +69,6 @@ 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,11 +1,5 @@
|
||||
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,7 +1,6 @@
|
||||
---
|
||||
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.">
|
||||
@@ -58,24 +57,6 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
</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">
|
||||
@@ -92,8 +73,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
|
||||
async function init() {
|
||||
const versionLabel = document.getElementById("version-label");
|
||||
// Only release-asset cards; mobile store cards have no data-asset and keep their href.
|
||||
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card[data-asset]");
|
||||
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
|
||||
|
||||
try {
|
||||
const release = await fetchLatestRelease();
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import {
|
||||
ANDROID_PLAY_STORE_URL,
|
||||
GITHUB_REPOSITORY_URL,
|
||||
IOS_APP_STORE_URL,
|
||||
MARKETING_STATS,
|
||||
} from "../lib/site";
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import { tweets } from "../lib/tweets";
|
||||
|
||||
const desktopEndorsementRows = [
|
||||
@@ -71,12 +66,6 @@ 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">
|
||||
@@ -589,28 +578,6 @@ 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: "")
|
||||
}
|
||||
|
||||
func loadImages(from providers: [NSItemProvider]) {
|
||||
private 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, UITextDropDelegate {
|
||||
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
private let textView = ComposerTextView()
|
||||
private let placeholderLabel = UILabel()
|
||||
private var value = ""
|
||||
@@ -326,7 +326,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
|
||||
clipsToBounds = false
|
||||
textView.delegate = self
|
||||
textView.textDropDelegate = self
|
||||
textView.backgroundColor = .clear
|
||||
textView.textContainerInset = .zero
|
||||
textView.textContainer.lineFragmentPadding = 0
|
||||
@@ -501,41 +500,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3WebSocketModule"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'T3WebSocket'
|
||||
s.version = '1.0.0'
|
||||
s.summary = 'URLSession-backed WebSocket for T3 Code mobile.'
|
||||
s.description = 'WebSocket client backed by URLSessionWebSocketTask so iOS negotiates permessage-deflate, which SocketRocket (React Native default) cannot.'
|
||||
s.author = 'T3 Tools'
|
||||
s.homepage = 'https://t3tools.com'
|
||||
s.platforms = {
|
||||
:ios => '18.0',
|
||||
}
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
}
|
||||
s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
|
||||
end
|
||||
@@ -0,0 +1,210 @@
|
||||
import ExpoModulesCore
|
||||
import Foundation
|
||||
|
||||
// WebSocket client backed by URLSessionWebSocketTask. React Native's built-in
|
||||
// iOS WebSocket (SocketRocket) never offers permessage-deflate, so frames from
|
||||
// the T3 server arrive uncompressed. URLSessionWebSocketTask offers the
|
||||
// extension in its handshake by default, letting the server (which negotiates
|
||||
// permessage-deflate since #4705) compress the JSON RPC stream.
|
||||
//
|
||||
// Only the surface Effect's `Socket.fromWebSocket` needs is exposed: connect,
|
||||
// send text/binary, close, and open/message/close/error events routed by a
|
||||
// JS-assigned connection id.
|
||||
public final class T3WebSocketModule: Module {
|
||||
private let connections = T3WebSocketConnections()
|
||||
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3WebSocket")
|
||||
|
||||
Events("onOpen", "onMessage", "onClose", "onError")
|
||||
|
||||
Function("connect") { (id: Int, url: String, protocols: [String]) throws in
|
||||
guard let parsedUrl = URL(string: url) else {
|
||||
throw Exception(name: "InvalidUrl", description: "Invalid WebSocket URL: \(url)")
|
||||
}
|
||||
self.connections.open(id: id, url: parsedUrl, protocols: protocols) { [weak self] event, payload in
|
||||
self?.sendEvent(event, payload)
|
||||
}
|
||||
}
|
||||
|
||||
Function("sendText") { (id: Int, text: String) in
|
||||
self.connections.send(id: id, message: .string(text))
|
||||
}
|
||||
|
||||
Function("sendBinary") { (id: Int, base64: String) in
|
||||
guard let data = Data(base64Encoded: base64) else { return }
|
||||
self.connections.send(id: id, message: .data(data))
|
||||
}
|
||||
|
||||
Function("close") { (id: Int, code: Int, reason: String) in
|
||||
self.connections.close(id: id, code: code, reason: reason)
|
||||
}
|
||||
|
||||
OnDestroy {
|
||||
self.connections.cancelAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private typealias T3WebSocketEmitter = (_ event: String, _ payload: [String: Any]) -> Void
|
||||
|
||||
private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegate {
|
||||
// Snapshot frames on the socket-fallback path can reach tens of MB; the
|
||||
// URLSession default receive cap is 1 MB, which would abort the connection.
|
||||
private static let maximumMessageSize = 128 * 1024 * 1024
|
||||
|
||||
private let queue = DispatchQueue(label: "com.t3tools.t3code.websocket")
|
||||
private var tasksById: [Int: URLSessionWebSocketTask] = [:]
|
||||
private var idsByTaskIdentifier: [Int: Int] = [:]
|
||||
private var emittersById: [Int: T3WebSocketEmitter] = [:]
|
||||
|
||||
// Held so teardown can invalidate it: URLSession retains its delegate (self)
|
||||
// until invalidated, so skipping that leaks this object and the session on
|
||||
// every module destroy/recreate cycle. Only touched from `queue`.
|
||||
private var activeSession: URLSession?
|
||||
|
||||
private var session: URLSession {
|
||||
if let activeSession { return activeSession }
|
||||
let configuration = URLSessionConfiguration.default
|
||||
// Dev clients (and network debuggers) register custom URLProtocol classes
|
||||
// that intercept URLSession traffic. They do not understand the WebSocket
|
||||
// upgrade and drop the connection right after the 101 (NSURLErrorDomain
|
||||
// -1005). WebSocket traffic has no reason to go through them.
|
||||
configuration.protocolClasses = []
|
||||
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
|
||||
activeSession = session
|
||||
return session
|
||||
}
|
||||
|
||||
func open(id: Int, url: URL, protocols: [String], emitter: @escaping T3WebSocketEmitter) {
|
||||
queue.async {
|
||||
let task = protocols.isEmpty
|
||||
? self.session.webSocketTask(with: url)
|
||||
: self.session.webSocketTask(with: url, protocols: protocols)
|
||||
task.maximumMessageSize = Self.maximumMessageSize
|
||||
self.tasksById[id] = task
|
||||
self.idsByTaskIdentifier[task.taskIdentifier] = id
|
||||
self.emittersById[id] = emitter
|
||||
task.resume()
|
||||
self.receiveLoop(id: id, task: task)
|
||||
}
|
||||
}
|
||||
|
||||
func send(id: Int, message: URLSessionWebSocketTask.Message) {
|
||||
queue.async {
|
||||
guard let task = self.tasksById[id] else { return }
|
||||
task.send(message) { [weak self] error in
|
||||
guard let self, let error else { return }
|
||||
self.queue.async {
|
||||
self.emitLocked(id: id, event: "onError", payload: ["message": error.localizedDescription])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func close(id: Int, code: Int, reason: String) {
|
||||
queue.async {
|
||||
guard let task = self.tasksById[id] else { return }
|
||||
let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: code) ?? .normalClosure
|
||||
task.cancel(with: closeCode, reason: reason.data(using: .utf8))
|
||||
}
|
||||
}
|
||||
|
||||
func cancelAll() {
|
||||
queue.async {
|
||||
for task in self.tasksById.values {
|
||||
task.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
self.tasksById.removeAll()
|
||||
self.idsByTaskIdentifier.removeAll()
|
||||
self.emittersById.removeAll()
|
||||
// Releases the session's reference to this delegate. A later `open` call
|
||||
// builds a fresh session rather than using an invalidated one.
|
||||
self.activeSession?.invalidateAndCancel()
|
||||
self.activeSession = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func receiveLoop(id: Int, task: URLSessionWebSocketTask) {
|
||||
task.receive { [weak self] result in
|
||||
guard let self else { return }
|
||||
self.queue.async {
|
||||
switch result {
|
||||
case .success(let message):
|
||||
switch message {
|
||||
case .string(let text):
|
||||
self.emitLocked(id: id, event: "onMessage", payload: ["data": text, "binary": false])
|
||||
case .data(let data):
|
||||
self.emitLocked(id: id, event: "onMessage", payload: ["data": data.base64EncodedString(), "binary": true])
|
||||
@unknown default:
|
||||
break
|
||||
}
|
||||
guard self.tasksById[id] != nil else { return }
|
||||
self.receiveLoop(id: id, task: task)
|
||||
case .failure:
|
||||
// The delegate close/error callbacks own failure reporting; the loop
|
||||
// just stops so it does not spin on a dead task.
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Must be called on `queue`.
|
||||
private func emitLocked(id: Int, event: String, payload: [String: Any]) {
|
||||
guard let emitter = emittersById[id] else { return }
|
||||
var enriched = payload
|
||||
enriched["id"] = id
|
||||
emitter(event, enriched)
|
||||
}
|
||||
|
||||
private func remove(id: Int, taskIdentifier: Int) {
|
||||
tasksById.removeValue(forKey: id)
|
||||
idsByTaskIdentifier.removeValue(forKey: taskIdentifier)
|
||||
emittersById.removeValue(forKey: id)
|
||||
}
|
||||
|
||||
// MARK: - URLSessionWebSocketDelegate
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
webSocketTask: URLSessionWebSocketTask,
|
||||
didOpenWithProtocol protocol: String?
|
||||
) {
|
||||
queue.async {
|
||||
guard let id = self.idsByTaskIdentifier[webSocketTask.taskIdentifier] else { return }
|
||||
self.emitLocked(id: id, event: "onOpen", payload: ["protocol": `protocol` ?? ""])
|
||||
}
|
||||
}
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
webSocketTask: URLSessionWebSocketTask,
|
||||
didCloseWith closeCode: URLSessionWebSocketTask.CloseCode,
|
||||
reason: Data?
|
||||
) {
|
||||
queue.async {
|
||||
guard let id = self.idsByTaskIdentifier[webSocketTask.taskIdentifier] else { return }
|
||||
let reasonText = reason.flatMap { String(data: $0, encoding: .utf8) } ?? ""
|
||||
self.emitLocked(id: id, event: "onClose", payload: ["code": closeCode.rawValue, "reason": reasonText])
|
||||
self.remove(id: id, taskIdentifier: webSocketTask.taskIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
task: URLSessionTask,
|
||||
didCompleteWithError error: Error?
|
||||
) {
|
||||
queue.async {
|
||||
guard let id = self.idsByTaskIdentifier[task.taskIdentifier] else { return }
|
||||
if let error {
|
||||
self.emitLocked(id: id, event: "onError", payload: ["message": error.localizedDescription])
|
||||
// Abnormal termination: no close frame arrived, mirror the browser's
|
||||
// 1006 so Effect's close-code classification treats it as an error.
|
||||
self.emitLocked(id: id, event: "onClose", payload: ["code": 1006, "reason": error.localizedDescription])
|
||||
}
|
||||
self.remove(id: id, taskIdentifier: task.taskIdentifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/metro-runtime": "~56.0.15",
|
||||
"@expo/ui": "~56.0.18",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
|
||||
@@ -284,15 +284,6 @@ 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;
|
||||
@@ -301,6 +292,7 @@ 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.
|
||||
@@ -328,7 +320,6 @@ function RootStackLayout(props: {
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
import { SymbolView } from "./AppSymbol";
|
||||
import { Image } from "expo-image";
|
||||
import { useLayoutEffect, useMemo, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
getProjectFaviconCacheKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
} from "@t3tools/shared/projectFavicon";
|
||||
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { useAssetUrl } from "../state/assets";
|
||||
import {
|
||||
beginProjectFaviconRequest,
|
||||
createProjectFaviconRequest,
|
||||
hasLoadedProjectFavicon,
|
||||
markProjectFaviconFailed,
|
||||
markProjectFaviconLoaded,
|
||||
} from "./projectFaviconCache";
|
||||
|
||||
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
|
||||
const loadedFaviconUrls = new Set<string>();
|
||||
|
||||
/* ─── Component ──────────────────────────────────────────────────────── */
|
||||
export function ProjectFavicon(props: {
|
||||
@@ -33,15 +26,10 @@ 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={cacheKey}
|
||||
cacheKey={cacheKey}
|
||||
key={faviconUrl}
|
||||
faviconUrl={renderableFaviconUrl}
|
||||
open={props.open}
|
||||
projectTitle={props.projectTitle}
|
||||
@@ -51,32 +39,18 @@ 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">(() =>
|
||||
hasLoadedProjectFavicon(props.cacheKey) ? "loaded" : "loading",
|
||||
props.faviconUrl && loadedFaviconUrls.has(props.faviconUrl) ? "loaded" : "loading",
|
||||
);
|
||||
|
||||
const requestIsActive = faviconRequest !== null && activeFaviconRequest === faviconRequest;
|
||||
const showImage = requestIsActive && status === "loaded";
|
||||
const showImage = props.faviconUrl !== null && status === "loaded";
|
||||
|
||||
return (
|
||||
<View
|
||||
@@ -98,15 +72,11 @@ function ProjectFaviconImage(props: {
|
||||
) : null}
|
||||
|
||||
{/* Favicon image (hidden until loaded) */}
|
||||
{requestIsActive ? (
|
||||
{props.faviconUrl ? (
|
||||
<Image
|
||||
key={faviconRequest.faviconUrl}
|
||||
source={{
|
||||
uri: faviconRequest.faviconUrl,
|
||||
cacheKey: faviconRequest.cacheKey,
|
||||
uri: props.faviconUrl,
|
||||
}}
|
||||
cachePolicy="memory-disk"
|
||||
recyclingKey={faviconRequest.cacheKey}
|
||||
accessibilityLabel={`${props.projectTitle} favicon`}
|
||||
style={{
|
||||
width: props.size,
|
||||
@@ -116,13 +86,10 @@ function ProjectFaviconImage(props: {
|
||||
}}
|
||||
contentFit="contain"
|
||||
onLoad={() => {
|
||||
if (!markProjectFaviconLoaded(faviconRequest)) return;
|
||||
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
|
||||
setStatus("loaded");
|
||||
}}
|
||||
onError={() => {
|
||||
if (!markProjectFaviconFailed(faviconRequest)) return;
|
||||
setStatus("error");
|
||||
}}
|
||||
onError={() => setStatus("error")}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,94 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
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";
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
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);
|
||||
};
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
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();
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,116 +0,0 @@
|
||||
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,
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -30,7 +30,6 @@ 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" {
|
||||
@@ -55,53 +54,27 @@ const connectivityLayer = Connectivity.layer({
|
||||
),
|
||||
changes: Stream.callback((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
let active = true;
|
||||
const networkSubscription = Network.addNetworkStateListener((state) => {
|
||||
Effect.sync(() =>
|
||||
Network.addNetworkStateListener((state) => {
|
||||
Queue.offerUnsafe(queue, networkStatus(state));
|
||||
});
|
||||
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),
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
});
|
||||
|
||||
const wakeupsLayer = Wakeups.layer({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
|
||||
return AppState.addEventListener("change", (state) => {
|
||||
if (state === "background") {
|
||||
backgroundedAtMs = Date.now();
|
||||
return;
|
||||
}
|
||||
Effect.sync(() =>
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));
|
||||
backgroundedAtMs = null;
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
});
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
|
||||
@@ -5,10 +5,6 @@ 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(
|
||||
@@ -21,22 +17,10 @@ type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof snapshotLoaderLayer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof connectionPlatformLayer
|
||||
| typeof mobileBackgroundActivityObserverLayer
|
||||
| typeof mobileBackgroundActivityReporterLayer;
|
||||
| typeof connectionPlatformLayer;
|
||||
|
||||
const providedClientConnectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
runtimeContextLayer,
|
||||
providedConnectionPlatformLayer,
|
||||
mobileBackgroundActivityObserverLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectionLayer = mobileBackgroundActivityReporterLayer.pipe(
|
||||
Layer.provideMerge(providedClientConnectionLayer),
|
||||
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
export const connectionAtomRuntime: Atom.AtomRuntime<
|
||||
|
||||
@@ -29,10 +29,7 @@ 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,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
|
||||
} from "../layout/native-mail-search-toolbar";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
|
||||
|
||||
export interface ArchivedThreadsHeaderEnvironment {
|
||||
@@ -73,8 +70,7 @@ 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 && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
|
||||
const usesCompactMailToolbar = Platform.OS === "ios" && width < 700;
|
||||
const androidFilterActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -276,11 +272,7 @@ function ArchivedThreadsHeader(props: {
|
||||
...(usesNativeChrome
|
||||
? {
|
||||
allowToolbarIntegration: true,
|
||||
// "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: "integratedButton" as const,
|
||||
}
|
||||
: {
|
||||
placement: "stacked" as const,
|
||||
|
||||
@@ -134,14 +134,7 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
|
||||
case "RelayEnvironmentLinkProofInvalidError":
|
||||
return `Relay rejected the environment link proof (${error.reason}).`;
|
||||
case "RelayEnvironmentConnectNotAuthorizedError":
|
||||
// "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.";
|
||||
return "Relay rejected the environment connection request.";
|
||||
case "RelayEnvironmentEndpointUnavailableError":
|
||||
return `Relay could not reach the environment endpoint (${error.reason}).`;
|
||||
case "RelayEnvironmentEndpointTimedOutError":
|
||||
|
||||
@@ -29,10 +29,7 @@ import {
|
||||
useAdaptiveWorkspacePaneRole,
|
||||
useRegisterWorkspaceInspector,
|
||||
} from "../layout/AdaptiveWorkspaceLayout";
|
||||
import {
|
||||
createNativeMailSearchToolbarItem,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
|
||||
} from "../layout/native-mail-search-toolbar";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
|
||||
import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
|
||||
@@ -357,8 +354,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
|
||||
);
|
||||
}
|
||||
|
||||
const usesCompactMailToolbar =
|
||||
Platform.OS === "ios" && !layout.usesSplitView && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
|
||||
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -13,10 +13,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import {
|
||||
createNativeMailSearchToolbarItem,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
|
||||
} from "../layout/native-mail-search-toolbar";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeListFilterMenu,
|
||||
@@ -323,11 +320,9 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
// 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: () => [
|
||||
unstable_headerToolbarItems:
|
||||
Platform.OS === "ios"
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
composeButtonId: "home-new-task",
|
||||
composeSystemImageName: "square.and.pencil",
|
||||
@@ -341,14 +336,14 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
placeholder: "Search",
|
||||
searchTextChangeId: "home-search-text",
|
||||
}),
|
||||
],
|
||||
}
|
||||
: {
|
||||
// Pre-Liquid-Glass iOS: standard pull-down search in the nav
|
||||
// bar; create + sort live in the plain bottom toolbar below.
|
||||
headerSearchBarOptions: {
|
||||
]
|
||||
: undefined,
|
||||
headerSearchBarOptions:
|
||||
Platform.OS === "ios"
|
||||
? undefined
|
||||
: {
|
||||
ref: searchBarRef,
|
||||
autoCapitalize: "none" as const,
|
||||
allowToolbarIntegration: true,
|
||||
hideNavigationBar: false,
|
||||
placeholder: "Search",
|
||||
onCancelButtonPress: () => {
|
||||
@@ -358,11 +353,21 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
},
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
|
||||
{NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED ? null : (
|
||||
{Platform.OS === "ios" ? null : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Open settings"
|
||||
icon="gearshape"
|
||||
onPress={props.onOpenSettings}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
|
||||
{Platform.OS === "ios" ? null : (
|
||||
<NativeHeaderToolbar placement="bottom">
|
||||
<NativeHeaderToolbar.Menu
|
||||
accessibilityLabel="Filter and sort threads"
|
||||
@@ -416,37 +421,35 @@ function IosHomeHeader(props: HomeHeaderProps) {
|
||||
</NativeHeaderToolbar.Menu>
|
||||
) : null}
|
||||
|
||||
{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 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 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 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 flexible />
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="New task"
|
||||
icon="square.and.pencil"
|
||||
|
||||
@@ -11,7 +11,6 @@ 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";
|
||||
@@ -26,35 +25,28 @@ export function HomeRouteScreen() {
|
||||
const { layout } = useAdaptiveWorkspaceLayout();
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
|
||||
const { 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(() => {
|
||||
const connectionStateByEnvironmentId = new Map(
|
||||
workspaceEnvironments.map(
|
||||
(environment) => [environment.environmentId, environment.connectionState] as const,
|
||||
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,
|
||||
),
|
||||
),
|
||||
);
|
||||
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]);
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const availableEnvironmentIds = useMemo(
|
||||
() => new Set(environments.map((environment) => environment.environmentId)),
|
||||
[environments],
|
||||
|
||||
@@ -7,10 +7,6 @@ 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,
|
||||
@@ -26,12 +22,11 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { 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";
|
||||
@@ -77,9 +72,7 @@ interface HomeScreenProps {
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
readonly catalogState: WorkspaceState;
|
||||
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
|
||||
readonly environments: ReadonlyArray<
|
||||
HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
|
||||
>;
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
@@ -109,7 +102,6 @@ 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
|
||||
@@ -197,39 +189,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
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)) {
|
||||
@@ -359,7 +318,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
pendingTasks: scopedPendingTasks,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
threadSortOrder: props.threadSortOrder,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
@@ -370,7 +328,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threadSortOrder,
|
||||
matchedThreadKeys,
|
||||
scopedPendingTasks,
|
||||
scopedProjects,
|
||||
scopedThreads,
|
||||
@@ -559,7 +516,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
@@ -577,7 +533,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
matchedThreadKeys,
|
||||
threadListV2Enabled,
|
||||
v2ScopedProjectGroup,
|
||||
]);
|
||||
@@ -674,13 +629,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
? (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}
|
||||
@@ -712,45 +660,14 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
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 extraData = useMemo(
|
||||
() => ({
|
||||
projectCwdByKey,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
searchQuery: props.searchQuery,
|
||||
threadSearchMatchByKey,
|
||||
}),
|
||||
[projectCwdByKey, props.savedConnectionsById, props.searchQuery, threadSearchMatchByKey],
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
[props.savedConnectionsById, projectCwdByKey],
|
||||
);
|
||||
|
||||
const renderItem = useCallback(
|
||||
@@ -803,13 +720,6 @@ 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}
|
||||
@@ -840,9 +750,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.onNewThreadInProject,
|
||||
props.onSelectPendingTask,
|
||||
props.onSelectThread,
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
threadSearchMatchByKey,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
@@ -882,7 +790,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) + iosBottomToolbarClearance,
|
||||
paddingBottom: Math.max(insets.bottom, 24),
|
||||
paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
|
||||
}}
|
||||
>
|
||||
@@ -935,7 +843,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const v2ListHeader = listHeader;
|
||||
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : selectedProjectScope !== null ? (
|
||||
<EmptyState
|
||||
@@ -958,34 +866,31 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// threads yet" over an inbox that is merely all-snoozed reads as data
|
||||
// loss.
|
||||
const v2SnoozedCount = threadListV2Layout.snoozedCount;
|
||||
const v2ListEmpty =
|
||||
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
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={
|
||||
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
|
||||
}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
const v2ListEmpty = hasSearchQuery ? (
|
||||
v2SnoozedCount > 0 ? (
|
||||
// The snoozed threads already passed this search filter: "No
|
||||
// results" would claim nothing matched when matches are merely
|
||||
// parked.
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
title={v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`}
|
||||
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
|
||||
/>
|
||||
) : (
|
||||
listEmpty
|
||||
);
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
)
|
||||
) : v2SnoozedCount > 0 ? (
|
||||
<EmptyState
|
||||
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
|
||||
detail="Snoozed threads return when their wake time passes."
|
||||
/>
|
||||
) : v2ScopedProjectGroup !== null ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${v2ScopedProjectGroup.title}`}
|
||||
detail="Choose another project or create a new task."
|
||||
/>
|
||||
) : (
|
||||
listEmpty
|
||||
);
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
@@ -995,7 +900,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
extraData={v2ExtraData}
|
||||
extraData={{
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
}}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
@@ -1024,7 +935,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
contentContainerStyle={{
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
|
||||
? Math.max(insets.bottom, 24) + 96
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
}}
|
||||
/>
|
||||
@@ -1065,19 +976,16 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
// Android reserves room for the floating new-task FAB
|
||||
// (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".
|
||||
// (56 button + 16 gap + bottom inset).
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 24 + iosBottomToolbarClearance
|
||||
? Math.max(insets.bottom, 24) + 24
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
}}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios"
|
||||
? {
|
||||
bottom: Math.max(insets.bottom, 16) + 24 + iosBottomToolbarClearance,
|
||||
bottom: Math.max(insets.bottom, 16) + 24,
|
||||
top: 0,
|
||||
}
|
||||
: undefined
|
||||
|
||||
@@ -2,7 +2,6 @@ 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";
|
||||
|
||||
@@ -662,33 +661,6 @@ 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,7 +12,6 @@ import {
|
||||
sortThreads,
|
||||
toSortableTimestamp,
|
||||
} from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ScopedProjectRef,
|
||||
@@ -255,7 +254,6 @@ 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;
|
||||
@@ -352,16 +350,7 @@ 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) ||
|
||||
input.matchedThreadKeys?.has(
|
||||
threadSearchMatchKey({
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
}),
|
||||
) === true,
|
||||
);
|
||||
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
|
||||
const matchingPendingTasks = groupMatches
|
||||
? group.pendingTasks
|
||||
: group.pendingTasks.filter((pendingTask) =>
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
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"
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
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,17 +4,12 @@ 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,
|
||||
@@ -29,7 +24,7 @@ import {
|
||||
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, 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";
|
||||
@@ -51,20 +46,15 @@ import { uuidv4 } from "../../lib/uuid";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
|
||||
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(
|
||||
@@ -237,13 +227,10 @@ function ProjectPathInput(props: {
|
||||
}
|
||||
|
||||
function useBrowsePathInput(environment: EnvironmentOption | null) {
|
||||
const environmentId = environment?.environmentId ?? null;
|
||||
const environmentBaseDirectory = environment?.baseDirectory ?? null;
|
||||
const [pathInput, commitPathInput] = useState(() =>
|
||||
getAddProjectInitialQuery(environmentBaseDirectory),
|
||||
getAddProjectInitialQuery(environment?.baseDirectory),
|
||||
);
|
||||
const previousEnvironmentIdRef = useRef(environmentId);
|
||||
const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
|
||||
const environmentRuntime = useRemoteEnvironmentRuntime(environment?.environmentId ?? null);
|
||||
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
|
||||
reportFailure: false,
|
||||
reportDefect: false,
|
||||
@@ -281,11 +268,10 @@ function useBrowsePathInput(environment: EnvironmentOption | null) {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
|
||||
previousEnvironmentIdRef.current = environmentId;
|
||||
setPathInput(getAddProjectInitialQuery(environmentBaseDirectory));
|
||||
if (environment) {
|
||||
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
|
||||
}
|
||||
}, [environmentBaseDirectory, environmentId, setPathInput]);
|
||||
}, [environment, setPathInput]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
@@ -300,27 +286,19 @@ function useBrowsePathInput(environment: EnvironmentOption | null) {
|
||||
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);
|
||||
}, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
|
||||
}, [savedConnectionsById, serverConfigByEnvironmentId]);
|
||||
}
|
||||
|
||||
function useSelectedEnvironment(): {
|
||||
@@ -331,14 +309,8 @@ function useSelectedEnvironment(): {
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
const environmentOptions = useEnvironmentOptions();
|
||||
const selectedEnvironment =
|
||||
environmentOptions.find(
|
||||
(environment) =>
|
||||
environment.environmentId === selectedEnvironmentId &&
|
||||
canCreateProjectInEnvironment(environment.connectionState),
|
||||
) ??
|
||||
environmentOptions.find((environment) =>
|
||||
canCreateProjectInEnvironment(environment.connectionState),
|
||||
) ??
|
||||
environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ??
|
||||
environmentOptions[0] ??
|
||||
null;
|
||||
|
||||
return {
|
||||
@@ -353,9 +325,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">Environment unavailable</Text>
|
||||
<Text className="text-center text-lg font-t3-bold">No environments connected</Text>
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
Start or reconnect an environment before adding a project.
|
||||
Add an environment before adding a project.
|
||||
</Text>
|
||||
<Pressable
|
||||
onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
|
||||
@@ -435,25 +407,17 @@ export function AddProjectSourceScreen() {
|
||||
|
||||
return (
|
||||
<AddProjectShell>
|
||||
{selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
|
||||
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
|
||||
|
||||
{environmentOptions.length > 1 ? (
|
||||
<>
|
||||
<SectionTitle>Environments</SectionTitle>
|
||||
<SectionTitle>Connected environments</SectionTitle>
|
||||
<ListSection>
|
||||
{environmentOptions.map((environment, index) => (
|
||||
<ListRow
|
||||
key={environment.environmentId}
|
||||
title={environment.label}
|
||||
subtitle={
|
||||
canCreateProjectInEnvironment(environment.connectionState)
|
||||
? environment.environmentId
|
||||
: connectionStatusText({
|
||||
phase: environment.connectionState,
|
||||
error: environment.connectionError,
|
||||
traceId: environment.connectionErrorTraceId,
|
||||
})
|
||||
}
|
||||
subtitle={environment.environmentId}
|
||||
icon={
|
||||
<SymbolView
|
||||
name="server.rack"
|
||||
@@ -463,7 +427,6 @@ export function AddProjectSourceScreen() {
|
||||
/>
|
||||
}
|
||||
selected={environment.environmentId === selectedEnvironment?.environmentId}
|
||||
disabled={!canCreateProjectInEnvironment(environment.connectionState)}
|
||||
isFirst={index === 0}
|
||||
right={
|
||||
environment.environmentId === selectedEnvironment?.environmentId ? (
|
||||
@@ -537,7 +500,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
|
||||
return useCallback(
|
||||
async (workspaceRoot: string) => {
|
||||
if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
|
||||
if (!environment) return;
|
||||
|
||||
const existing = findExistingAddProject({
|
||||
projects,
|
||||
@@ -588,7 +551,11 @@ function useEnvironmentFromParam(
|
||||
): EnvironmentOption | null {
|
||||
const environmentOptions = useEnvironmentOptions();
|
||||
const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
|
||||
return resolveAddProjectEnvironment(environmentOptions, environmentId);
|
||||
return (
|
||||
environmentOptions.find((environment) => environment.environmentId === environmentId) ??
|
||||
environmentOptions[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export function AddProjectRepositoryScreen(props: {
|
||||
@@ -652,32 +619,26 @@ export function AddProjectRepositoryScreen(props: {
|
||||
return (
|
||||
<AddProjectShell>
|
||||
{error ? <ErrorBanner message={error} /> : null}
|
||||
{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 />
|
||||
)}
|
||||
<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}
|
||||
/>
|
||||
</AddProjectShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,10 +9,19 @@ import { SymbolView } from "../../components/AppSymbol";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { Alert, Linking, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Linking,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import {
|
||||
type AtomCommandResult,
|
||||
isAtomCommandInterrupted,
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
@@ -38,11 +47,6 @@ 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";
|
||||
@@ -574,11 +578,12 @@ function BetaSettingsSection() {
|
||||
);
|
||||
}
|
||||
|
||||
type UpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
|
||||
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
|
||||
const [updateState, setUpdateState] = useState<UpdateCheckState>("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
|
||||
@@ -586,11 +591,22 @@ 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.
|
||||
// drop back to the bundle label so the row keeps answering "what am I running?".
|
||||
useEffect(() => {
|
||||
if (updateState !== "current") return;
|
||||
const timer = setTimeout(() => setUpdateState("idle"), 3000);
|
||||
@@ -603,24 +619,12 @@ function AppSettingsSection() {
|
||||
if (updateInFlight.current) return;
|
||||
updateInFlight.current = true;
|
||||
try {
|
||||
await runAppUpdateCheck({
|
||||
onFailure: (message) => Alert.alert("Update failed", message),
|
||||
onStateChange: setUpdateState,
|
||||
});
|
||||
await runUpdateCheck(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…"
|
||||
@@ -630,7 +634,7 @@ function AppSettingsSection() {
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
: bundleLabel;
|
||||
|
||||
const versionRow = (
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
@@ -648,6 +652,21 @@ function AppSettingsSection() {
|
||||
<Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{Updates.isEnabled ? (
|
||||
<View className="w-[22px] items-center">
|
||||
{busy ? (
|
||||
<ActivityIndicator color={icon} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={18}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -657,10 +676,10 @@ function AppSettingsSection() {
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
{Updates.isEnabled ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Version ${versionLabel}`}
|
||||
accessibilityRole="text"
|
||||
accessibilityLabel="Check for updates"
|
||||
accessibilityRole="button"
|
||||
disabled={busy}
|
||||
onPress={handleVersionPress}
|
||||
onPress={() => void checkForUpdate()}
|
||||
>
|
||||
{versionRow}
|
||||
</Pressable>
|
||||
@@ -671,6 +690,52 @@ function AppSettingsSection() {
|
||||
);
|
||||
}
|
||||
|
||||
async function runUpdateCheck(setUpdateState: (state: UpdateCheckState) => void): Promise<void> {
|
||||
setUpdateState("checking");
|
||||
const check = await settlePromise(() => Updates.checkForUpdateAsync());
|
||||
if (check._tag === "Failure") {
|
||||
reportUpdateFailure(check, "Could not check for updates.");
|
||||
setUpdateState("idle");
|
||||
return;
|
||||
}
|
||||
// A rollback directive (`eas update:rollback`) arrives as isAvailable: false
|
||||
// with isRollBackToEmbedded: true — there is nothing newer to install, but the
|
||||
// running OTA still has to be dropped for the embedded bundle.
|
||||
if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
|
||||
setUpdateState("current");
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState("downloading");
|
||||
const fetched = await settlePromise(() => Updates.fetchUpdateAsync());
|
||||
if (fetched._tag === "Failure") {
|
||||
reportUpdateFailure(fetched, "Could not download the update.");
|
||||
setUpdateState("idle");
|
||||
return;
|
||||
}
|
||||
// isNew is always false for a rollback, so it can't be the sole gate here either.
|
||||
if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
|
||||
setUpdateState("current");
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState("restarting");
|
||||
// reloadAsync never resolves on success — the JS context is torn down — so
|
||||
// reaching the failure branch below is the only way this returns.
|
||||
const reloaded = await settlePromise(() => Updates.reloadAsync());
|
||||
if (reloaded._tag === "Failure") {
|
||||
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.");
|
||||
setUpdateState("idle");
|
||||
}
|
||||
}
|
||||
|
||||
function reportUpdateFailure(result: AtomCommandResult<unknown, unknown>, fallback: string): void {
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
Alert.alert("Update failed", error instanceof Error ? error.message : fallback);
|
||||
}
|
||||
|
||||
function capitalize(value: string): string {
|
||||
return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
type IncomingShareDestination,
|
||||
type IncomingShareDraft,
|
||||
} from "./incoming-share-model";
|
||||
import { createIncomingSharePayloadReader } from "./incoming-share-native";
|
||||
import { IncomingShareInbox } from "./incoming-share-inbox";
|
||||
import {
|
||||
loadIncomingShareDrafts,
|
||||
@@ -49,11 +48,6 @@ 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();
|
||||
@@ -127,7 +121,7 @@ const incomingShareInbox = new IncomingShareInbox({
|
||||
loadDrafts: loadIncomingShareDrafts,
|
||||
writeDraft: writeIncomingShareDraft,
|
||||
removeDraft: removeIncomingShareDraft,
|
||||
getPayloads: getIncomingSharePayloads,
|
||||
getPayloads: getSharedPayloads,
|
||||
clearPayloads: clearSharedPayloads,
|
||||
buildDraft: async ({ payloads, id, createdAt }) => {
|
||||
const cleanupUris = new Set<string>();
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
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,14 +54,7 @@ function useShortcutNavigation(): void {
|
||||
}
|
||||
|
||||
function useRecentThreadShortcutSync(state: NavigationState): void {
|
||||
// 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 threadRef = useMemo(() => activeThreadRef(state), [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,11 +946,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const promptEditor = (
|
||||
<ComposerEditor
|
||||
ref={promptInputRef}
|
||||
// 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}
|
||||
autoFocus={!isAndroid}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
multiline
|
||||
scrollEnabled={isExpanded}
|
||||
|
||||
@@ -203,17 +203,13 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
title={screenTitle}
|
||||
subtitle={incomingShareSubtitle}
|
||||
onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
|
||||
actions={
|
||||
catalogState.hasReadyEnvironment
|
||||
? [
|
||||
{
|
||||
accessibilityLabel: "Add project",
|
||||
icon: "plus",
|
||||
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
|
||||
},
|
||||
]
|
||||
: []
|
||||
}
|
||||
actions={[
|
||||
{
|
||||
accessibilityLabel: "Add project",
|
||||
icon: "plus",
|
||||
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
@@ -233,13 +229,11 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
{catalogState.hasReadyEnvironment ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -518,16 +518,14 @@ 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,9 +48,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInUp,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type LayoutAnimationsValues,
|
||||
LinearTransition,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -82,9 +80,7 @@ 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";
|
||||
@@ -95,12 +91,7 @@ import {
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadWorkGroupToggle,
|
||||
ThreadWorkLog,
|
||||
WORK_GROUP_TOGGLE_HEIGHT,
|
||||
} from "./thread-work-log";
|
||||
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
|
||||
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
@@ -118,22 +109,8 @@ 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. 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)
|
||||
// animating the container position turns those jumps into slides.
|
||||
const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180);
|
||||
|
||||
// Entering animations must only play for rows born just now — LegendList
|
||||
// remounts rows when they scroll back into view, and replaying an entrance for
|
||||
@@ -1324,7 +1301,6 @@ 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,
|
||||
);
|
||||
@@ -1434,11 +1410,6 @@ 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
|
||||
@@ -1446,40 +1417,9 @@ 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, nearListEnd],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset],
|
||||
);
|
||||
|
||||
// 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);
|
||||
@@ -1696,38 +1636,6 @@ 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, {
|
||||
@@ -1817,7 +1725,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
itemLayoutAnimation={feedItemLayoutTransition}
|
||||
itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION}
|
||||
// Patched LegendList prop (patches/@[email protected]):
|
||||
// lets its scroll math clamp programmatic scrolls to -headerInset
|
||||
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
|
||||
@@ -1861,10 +1769,6 @@ 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"
|
||||
@@ -1884,11 +1788,6 @@ 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,6 @@ 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";
|
||||
@@ -28,7 +24,6 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { useThreadSearch } from "../../state/queries";
|
||||
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
@@ -185,7 +180,7 @@ function ThreadNavigationSidebarPane(
|
||||
const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [headerIsOverContent, setHeaderIsOverContent] = useState(false);
|
||||
const searchInputRef = useRef<TextInput>(null);
|
||||
@@ -214,35 +209,6 @@ 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(
|
||||
() =>
|
||||
@@ -339,19 +305,11 @@ function ThreadNavigationSidebarPane(
|
||||
pendingTasks: scopedPendingTasks,
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
projectSortOrder: options.projectSortOrder,
|
||||
threadSortOrder: options.threadSortOrder,
|
||||
projectGroupingMode: options.projectGroupingMode,
|
||||
}),
|
||||
[
|
||||
matchedThreadKeys,
|
||||
options,
|
||||
props.searchQuery,
|
||||
scopedPendingTasks,
|
||||
scopedProjects,
|
||||
scopedThreads,
|
||||
],
|
||||
[options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
|
||||
);
|
||||
const [groupDisplayStates, setGroupDisplayStates] = useState<
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
@@ -474,7 +432,6 @@ function ThreadNavigationSidebarPane(
|
||||
environmentId: options.selectedEnvironmentId,
|
||||
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
@@ -488,7 +445,6 @@ function ThreadNavigationSidebarPane(
|
||||
snoozeWakeTick,
|
||||
options.selectedEnvironmentId,
|
||||
props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
settledVisibleCount,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
@@ -731,7 +687,6 @@ function ThreadNavigationSidebarPane(
|
||||
projectTitleByProjectKey,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
}),
|
||||
[
|
||||
props.selectedThreadKey,
|
||||
@@ -740,7 +695,6 @@ function ThreadNavigationSidebarPane(
|
||||
projectTitleByProjectKey,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
],
|
||||
);
|
||||
const sidebarItemsAreEqual = useCallback(
|
||||
@@ -843,13 +797,6 @@ 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
|
||||
@@ -929,13 +876,6 @@ 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
|
||||
}
|
||||
@@ -974,12 +914,10 @@ function ThreadNavigationSidebarPane(
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
props.onNewThreadInProject,
|
||||
props.searchQuery,
|
||||
props.selectedThreadKey,
|
||||
props.width,
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
@@ -1039,15 +977,13 @@ function ThreadNavigationSidebarPane(
|
||||
{catalogState.isLoadingConnections
|
||||
? "Loading threads…"
|
||||
: props.searchQuery.trim().length > 0
|
||||
? 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
|
||||
? // 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,7 +3,6 @@ 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";
|
||||
@@ -22,7 +21,6 @@ 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
|
||||
@@ -418,8 +416,6 @@ 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;
|
||||
@@ -573,13 +569,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{props.searchMatch ? (
|
||||
<ThreadSearchMatchExcerpt
|
||||
compact
|
||||
match={props.searchMatch}
|
||||
query={props.searchQuery ?? ""}
|
||||
/>
|
||||
) : null}
|
||||
{subtitleRow}
|
||||
</View>
|
||||
</View>
|
||||
@@ -634,13 +623,6 @@ 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,7 +2,6 @@ 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";
|
||||
@@ -19,7 +18,6 @@ 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
|
||||
@@ -245,8 +243,6 @@ 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"];
|
||||
@@ -373,15 +369,6 @@ 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
|
||||
@@ -530,24 +517,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<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(
|
||||
"flex-1 text-base",
|
||||
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-sm tabular-nums",
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
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,10 +3,8 @@ 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 = {
|
||||
@@ -79,46 +77,6 @@ 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;
|
||||
@@ -129,10 +87,9 @@ 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 = visibleWorkLogActivities(props.activities).map((activity) => ({
|
||||
...activity,
|
||||
detail: compactActivityDetail(activity.detail),
|
||||
}));
|
||||
const rows = props.activities
|
||||
.filter((activity) => !(activity.toolLike && activity.status === "neutral"))
|
||||
.map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
|
||||
|
||||
if (rows.length === 0) {
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
@@ -264,27 +263,6 @@ 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({
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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";
|
||||
@@ -184,7 +183,6 @@ 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
|
||||
@@ -224,18 +222,7 @@ export function buildThreadListV2Items(input: {
|
||||
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
query.length > 0 &&
|
||||
!thread.title.toLocaleLowerCase().includes(query) &&
|
||||
input.matchedThreadKeys?.has(
|
||||
threadSearchMatchKey({
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
}),
|
||||
) !== true
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,228 +0,0 @@
|
||||
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,27 +198,12 @@ 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`] = scaledTypographyLineHeight(role, baseFontSize);
|
||||
variables[`${name}--line-height`] = Math.max(10, Math.round(role.lineHeight * scale));
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
type Listener = (payload: Record<string, unknown>) => void;
|
||||
const nativeListeners = new Map<string, Listener>();
|
||||
const calls: Array<{ method: string; args: unknown[] }> = [];
|
||||
let platformOS = "ios";
|
||||
let moduleAvailable = true;
|
||||
|
||||
const nativeModule = {
|
||||
connect: (...args: unknown[]) => calls.push({ method: "connect", args }),
|
||||
sendText: (...args: unknown[]) => calls.push({ method: "sendText", args }),
|
||||
sendBinary: (...args: unknown[]) => calls.push({ method: "sendBinary", args }),
|
||||
close: (...args: unknown[]) => calls.push({ method: "close", args }),
|
||||
addListener: (eventName: string, listener: Listener) => {
|
||||
nativeListeners.set(eventName, listener);
|
||||
return { remove: () => nativeListeners.delete(eventName) };
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
calls,
|
||||
nativeListeners,
|
||||
emit: (eventName: string, payload: Record<string, unknown>) => {
|
||||
nativeListeners.get(eventName)?.(payload);
|
||||
},
|
||||
setPlatform: (os: string) => {
|
||||
platformOS = os;
|
||||
},
|
||||
setModuleAvailable: (available: boolean) => {
|
||||
moduleAvailable = available;
|
||||
},
|
||||
getPlatform: () => platformOS,
|
||||
getModule: () => (moduleAvailable ? nativeModule : null),
|
||||
// Native listeners intentionally survive reset: the wrapper attaches them
|
||||
// once per app lifetime, so clearing them here would not match production.
|
||||
reset: () => {
|
||||
calls.length = 0;
|
||||
platformOS = "ios";
|
||||
moduleAvailable = true;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-native", () => ({
|
||||
Platform: {
|
||||
get OS() {
|
||||
return mocks.getPlatform();
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("expo", () => ({
|
||||
requireOptionalNativeModule: () => mocks.getModule(),
|
||||
}));
|
||||
|
||||
import { loadNativeWebSocketConstructor } from "./nativeWebSocket";
|
||||
|
||||
async function openSocket() {
|
||||
const construct = await loadNativeWebSocketConstructor();
|
||||
expect(construct).not.toBeNull();
|
||||
return construct!("wss://example.test/ws");
|
||||
}
|
||||
|
||||
function lastCall(method: string) {
|
||||
const entries = mocks.calls.filter((call) => call.method === method);
|
||||
return entries[entries.length - 1];
|
||||
}
|
||||
|
||||
function connectionIdOf(socket: WebSocket): number {
|
||||
void socket;
|
||||
return lastCall("connect")!.args[0] as number;
|
||||
}
|
||||
|
||||
describe("nativeWebSocketConstructor", () => {
|
||||
beforeEach(() => {
|
||||
mocks.reset();
|
||||
});
|
||||
|
||||
it("resolves null on Android and when the native module is missing", async () => {
|
||||
mocks.setPlatform("android");
|
||||
expect(await loadNativeWebSocketConstructor()).toBeNull();
|
||||
|
||||
mocks.setPlatform("ios");
|
||||
mocks.setModuleAvailable(false);
|
||||
expect(await loadNativeWebSocketConstructor()).toBeNull();
|
||||
});
|
||||
|
||||
it("connects and transitions readyState on open", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
expect(lastCall("connect")!.args).toEqual([id, "wss://example.test/ws", []]);
|
||||
expect(socket.readyState).toBe(0);
|
||||
|
||||
const opened = vi.fn();
|
||||
socket.addEventListener("open", opened, { once: true });
|
||||
mocks.emit("onOpen", { id });
|
||||
expect(socket.readyState).toBe(1);
|
||||
expect(opened).toHaveBeenCalledTimes(1);
|
||||
|
||||
// `once` listeners must not fire again.
|
||||
mocks.emit("onOpen", { id });
|
||||
expect(opened).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("delivers text messages as strings and binary messages as bytes", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
const received: unknown[] = [];
|
||||
socket.addEventListener("message", (event) => {
|
||||
received.push((event as { data: unknown }).data);
|
||||
});
|
||||
|
||||
mocks.emit("onMessage", { id, data: "hello", binary: false });
|
||||
mocks.emit("onMessage", { id, data: btoa("\x01\x02\x03"), binary: true });
|
||||
|
||||
expect(received[0]).toBe("hello");
|
||||
expect(received[1]).toBeInstanceOf(Uint8Array);
|
||||
expect([...(received[1] as Uint8Array)]).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("sends binary data base64-encoded and strings as text", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
|
||||
socket.send("ping");
|
||||
expect(lastCall("sendText")!.args).toEqual([id, "ping"]);
|
||||
|
||||
socket.send(new Uint8Array([1, 2, 3]));
|
||||
expect(lastCall("sendBinary")!.args).toEqual([id, btoa("\x01\x02\x03")]);
|
||||
});
|
||||
|
||||
it("dispatches close once and routes messages by connection id", async () => {
|
||||
const first = await openSocket();
|
||||
const firstId = connectionIdOf(first);
|
||||
const second = await openSocket();
|
||||
const secondId = connectionIdOf(second);
|
||||
expect(firstId).not.toBe(secondId);
|
||||
|
||||
const firstClosed = vi.fn();
|
||||
const secondClosed = vi.fn();
|
||||
first.addEventListener("close", firstClosed);
|
||||
second.addEventListener("close", secondClosed);
|
||||
|
||||
mocks.emit("onClose", { id: firstId, code: 1000, reason: "done" });
|
||||
mocks.emit("onClose", { id: firstId, code: 1000, reason: "done" });
|
||||
|
||||
expect(firstClosed).toHaveBeenCalledTimes(1);
|
||||
expect(first.readyState).toBe(3);
|
||||
expect(secondClosed).not.toHaveBeenCalled();
|
||||
expect(second.readyState).toBe(0);
|
||||
});
|
||||
|
||||
it("close() is idempotent and forwards code and reason", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
|
||||
socket.close(4000, "bye");
|
||||
socket.close(4000, "bye");
|
||||
|
||||
const closeCalls = mocks.calls.filter((call) => call.method === "close");
|
||||
expect(closeCalls).toHaveLength(1);
|
||||
expect(closeCalls[0]!.args).toEqual([id, 4000, "bye"]);
|
||||
expect(socket.readyState).toBe(2);
|
||||
});
|
||||
|
||||
it("ignores a native open that lands after close", async () => {
|
||||
const socket = await openSocket();
|
||||
const id = connectionIdOf(socket);
|
||||
const opened = vi.fn();
|
||||
socket.addEventListener("open", opened);
|
||||
|
||||
// Effect closes while still CONNECTING (open timeout or scope teardown);
|
||||
// the in-flight native connect can still report success afterwards.
|
||||
socket.close(1000, "");
|
||||
mocks.emit("onOpen", { id });
|
||||
|
||||
expect(opened).not.toHaveBeenCalled();
|
||||
expect(socket.readyState).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
import { Platform } from "react-native";
|
||||
|
||||
// URLSession-backed WebSocket for iOS. React Native's built-in WebSocket uses
|
||||
// SocketRocket on iOS, which never offers permessage-deflate, so server frames
|
||||
// arrive uncompressed. URLSessionWebSocketTask offers the extension by default.
|
||||
// Android needs none of this: React Native's OkHttp-backed WebSocket already
|
||||
// negotiates permessage-deflate on its own.
|
||||
//
|
||||
// Only the surface Effect's `Socket.fromWebSocket` drives is implemented:
|
||||
// addEventListener/removeEventListener for open/message/close/error (with
|
||||
// `once` support), `readyState`, `send`, and `close`.
|
||||
|
||||
interface NativeEventSubscription {
|
||||
remove(): void;
|
||||
}
|
||||
|
||||
interface T3WebSocketNativeModule {
|
||||
connect(id: number, url: string, protocols: string[]): void;
|
||||
sendText(id: number, text: string): void;
|
||||
sendBinary(id: number, base64: string): void;
|
||||
close(id: number, code: number, reason: string): void;
|
||||
addListener(
|
||||
eventName: "onOpen" | "onMessage" | "onClose" | "onError",
|
||||
listener: (payload: {
|
||||
id: number;
|
||||
data?: string;
|
||||
binary?: boolean;
|
||||
code?: number;
|
||||
reason?: string;
|
||||
message?: string;
|
||||
}) => void,
|
||||
): NativeEventSubscription;
|
||||
}
|
||||
|
||||
type NativeWebSocketEventType = "open" | "message" | "close" | "error";
|
||||
|
||||
interface ListenerEntry {
|
||||
readonly listener: (event: unknown) => void;
|
||||
readonly once: boolean;
|
||||
}
|
||||
|
||||
const activeSockets = new Map<number, NativeWebSocket>();
|
||||
let nextSocketId = 1;
|
||||
let nativeListenersAttached = false;
|
||||
|
||||
function attachNativeListeners(module: T3WebSocketNativeModule) {
|
||||
if (nativeListenersAttached) {
|
||||
return;
|
||||
}
|
||||
nativeListenersAttached = true;
|
||||
module.addListener("onOpen", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleOpen();
|
||||
});
|
||||
module.addListener("onMessage", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleMessage(payload.data ?? "", payload.binary === true);
|
||||
});
|
||||
module.addListener("onClose", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleClose(payload.code ?? 1006, payload.reason ?? "");
|
||||
});
|
||||
module.addListener("onError", (payload) => {
|
||||
activeSockets.get(payload.id)?.handleError(payload.message ?? "WebSocket error");
|
||||
});
|
||||
}
|
||||
|
||||
function base64ToUint8Array(base64: string): Uint8Array {
|
||||
const binary = atob(base64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array): string {
|
||||
let binary = "";
|
||||
const chunkSize = 8192;
|
||||
for (let index = 0; index < bytes.length; index += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
class NativeWebSocket {
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
|
||||
readyState: number = NativeWebSocket.CONNECTING;
|
||||
|
||||
private readonly id: number;
|
||||
private readonly module: T3WebSocketNativeModule;
|
||||
private readonly listeners = new Map<NativeWebSocketEventType, Set<ListenerEntry>>();
|
||||
|
||||
constructor(module: T3WebSocketNativeModule, url: string, protocols?: string | Array<string>) {
|
||||
this.module = module;
|
||||
this.id = nextSocketId++;
|
||||
activeSockets.set(this.id, this);
|
||||
attachNativeListeners(module);
|
||||
const protocolList =
|
||||
typeof protocols === "string" ? [protocols] : protocols ? [...protocols] : [];
|
||||
try {
|
||||
module.connect(this.id, url, protocolList);
|
||||
} catch (error) {
|
||||
activeSockets.delete(this.id);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
addEventListener(
|
||||
type: NativeWebSocketEventType,
|
||||
listener: (event: unknown) => void,
|
||||
options?: { once?: boolean },
|
||||
): void {
|
||||
let entries = this.listeners.get(type);
|
||||
if (!entries) {
|
||||
entries = new Set();
|
||||
this.listeners.set(type, entries);
|
||||
}
|
||||
entries.add({ listener, once: options?.once === true });
|
||||
}
|
||||
|
||||
removeEventListener(type: NativeWebSocketEventType, listener: (event: unknown) => void): void {
|
||||
const entries = this.listeners.get(type);
|
||||
if (!entries) {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.listener === listener) {
|
||||
entries.delete(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
send(data: string | Uint8Array | ArrayBuffer): void {
|
||||
if (typeof data === "string") {
|
||||
this.module.sendText(this.id, data);
|
||||
return;
|
||||
}
|
||||
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
||||
this.module.sendBinary(this.id, bytesToBase64(bytes));
|
||||
}
|
||||
|
||||
close(code?: number, reason?: string): void {
|
||||
if (this.readyState === NativeWebSocket.CLOSING || this.readyState === NativeWebSocket.CLOSED) {
|
||||
return;
|
||||
}
|
||||
this.readyState = NativeWebSocket.CLOSING;
|
||||
this.module.close(this.id, code ?? 1000, reason ?? "");
|
||||
}
|
||||
|
||||
handleOpen(): void {
|
||||
// `close()` during CONNECTING (an Effect open-timeout or scope teardown)
|
||||
// leaves a native connect in flight, so its `didOpen` can still land. Only
|
||||
// a socket that is still connecting may transition to OPEN; otherwise the
|
||||
// close would be silently undone and open handlers would fire on a socket
|
||||
// the caller already gave up on.
|
||||
if (this.readyState !== NativeWebSocket.CONNECTING) {
|
||||
return;
|
||||
}
|
||||
this.readyState = NativeWebSocket.OPEN;
|
||||
this.dispatch("open", { type: "open" });
|
||||
}
|
||||
|
||||
handleMessage(data: string, binary: boolean): void {
|
||||
this.dispatch("message", {
|
||||
type: "message",
|
||||
data: binary ? base64ToUint8Array(data) : data,
|
||||
});
|
||||
}
|
||||
|
||||
handleClose(code: number, reason: string): void {
|
||||
if (this.readyState === NativeWebSocket.CLOSED) {
|
||||
return;
|
||||
}
|
||||
this.readyState = NativeWebSocket.CLOSED;
|
||||
activeSockets.delete(this.id);
|
||||
this.dispatch("close", { type: "close", code, reason });
|
||||
}
|
||||
|
||||
handleError(message: string): void {
|
||||
this.dispatch("error", new Error(message));
|
||||
}
|
||||
|
||||
private dispatch(type: NativeWebSocketEventType, event: unknown): void {
|
||||
const entries = this.listeners.get(type);
|
||||
if (!entries) {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.once) {
|
||||
entries.delete(entry);
|
||||
}
|
||||
entry.listener(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the WebSocket constructor backed by URLSessionWebSocketTask, resolving
|
||||
* `null` when unavailable (Android, or an iOS binary predating the native
|
||||
* module). Callers fall back to the global WebSocket.
|
||||
*
|
||||
* Async because "expo" is imported lazily: its module-scope setup code assumes
|
||||
* a React Native environment, and this file's importer (runtime.ts) sits in
|
||||
* many test import chains.
|
||||
*/
|
||||
export async function loadNativeWebSocketConstructor(): Promise<
|
||||
((url: string, protocols?: string | Array<string>) => globalThis.WebSocket) | null
|
||||
> {
|
||||
if (Platform.OS !== "ios") {
|
||||
return null;
|
||||
}
|
||||
let module: T3WebSocketNativeModule | null;
|
||||
try {
|
||||
const expo = await import("expo");
|
||||
module = expo.requireOptionalNativeModule<T3WebSocketNativeModule>("T3WebSocket");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!module) {
|
||||
return null;
|
||||
}
|
||||
return (url, protocols) =>
|
||||
new NativeWebSocket(module, url, protocols) as unknown as globalThis.WebSocket;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
@@ -9,6 +10,7 @@ import { managedRelayClientLayer } from "../features/cloud/managedRelayLayer";
|
||||
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
|
||||
import { tracingLayer } from "../features/observability/tracing";
|
||||
import * as Persistence from "../persistence/layer";
|
||||
import { loadNativeWebSocketConstructor } from "./nativeWebSocket";
|
||||
|
||||
function configuredRelayUrl(): string {
|
||||
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
|
||||
@@ -16,6 +18,19 @@ function configuredRelayUrl(): string {
|
||||
|
||||
const httpClientLayer = remoteHttpClientLayer(fetch);
|
||||
|
||||
// iOS swaps in a URLSessionWebSocketTask-backed constructor so the socket
|
||||
// negotiates permessage-deflate (SocketRocket, behind the global WebSocket,
|
||||
// cannot). Android's global WebSocket (OkHttp) already negotiates it.
|
||||
const webSocketConstructorLayer: Layer.Layer<Socket.WebSocketConstructor> = Layer.unwrap(
|
||||
Effect.promise(loadNativeWebSocketConstructor).pipe(
|
||||
Effect.map((nativeConstructor) =>
|
||||
nativeConstructor === null
|
||||
? Socket.layerWebSocketConstructorGlobal
|
||||
: Layer.succeed(Socket.WebSocketConstructor, nativeConstructor),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
type RuntimeLayerSource =
|
||||
| ReturnType<typeof managedRelayClientLayer>
|
||||
| typeof Socket.layerWebSocketConstructorGlobal
|
||||
@@ -26,7 +41,7 @@ type RuntimeLayerSource =
|
||||
|
||||
const runtimeLayer = Layer.merge(
|
||||
managedRelayClientLayer(configuredRelayUrl()),
|
||||
Socket.layerWebSocketConstructorGlobal,
|
||||
webSocketConstructorLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(cryptoLayer),
|
||||
Layer.provideMerge(httpClientLayer),
|
||||
|
||||
@@ -957,11 +957,6 @@ 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.
|
||||
@@ -971,23 +966,24 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
|
||||
|
||||
if (entry.type !== "activity") {
|
||||
grouped.push(entry);
|
||||
openGroupActivities = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (openGroupActivities !== null && openGroupTurnId === entry.turnId) {
|
||||
openGroupActivities.push(entry.activity);
|
||||
const previous = grouped.at(-1);
|
||||
if (previous?.type === "activity-group" && previous.turnId === entry.turnId) {
|
||||
grouped[grouped.length - 1] = {
|
||||
...previous,
|
||||
activities: [...previous.activities, entry.activity],
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
openGroupActivities = [entry.activity];
|
||||
openGroupTurnId = entry.turnId;
|
||||
grouped.push({
|
||||
type: "activity-group",
|
||||
id: entry.id,
|
||||
createdAt: entry.createdAt,
|
||||
turnId: entry.turnId,
|
||||
activities: openGroupActivities,
|
||||
activities: [entry.activity],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1229,24 +1225,13 @@ function appendPresentedFeedEntry(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>,
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
|
||||
for (const activity of sortedActivities) {
|
||||
for (const activity of ordered) {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
@@ -1288,11 +1273,12 @@ export function derivePendingApprovals(
|
||||
}
|
||||
|
||||
export function derivePendingUserInputs(
|
||||
sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingUserInput[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
|
||||
for (const activity of sortedActivities) {
|
||||
for (const activity of ordered) {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
|
||||
@@ -340,8 +340,7 @@ 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;
|
||||
@@ -352,11 +351,6 @@ 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);
|
||||
}
|
||||
});
|
||||
@@ -446,7 +440,6 @@ function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) {
|
||||
NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel";
|
||||
|
||||
function NativeHeaderToolbarSpacer(_props: {
|
||||
readonly flexible?: boolean;
|
||||
readonly sharesBackground?: boolean;
|
||||
readonly width?: number;
|
||||
}) {
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
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";
|
||||
@@ -22,22 +15,7 @@ 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;
|
||||
@@ -67,31 +45,6 @@ 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,23 +88,11 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
return loadPromise;
|
||||
};
|
||||
|
||||
// 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 () => {
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
|
||||
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,
|
||||
@@ -113,15 +101,11 @@ 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
|
||||
@@ -220,7 +204,6 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
serialize,
|
||||
load,
|
||||
enqueue,
|
||||
confirmQueued,
|
||||
update,
|
||||
remove,
|
||||
clearEnvironment,
|
||||
|
||||
@@ -294,111 +294,6 @@ 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,11 +20,6 @@ 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,7 +11,6 @@ import {
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -71,19 +70,14 @@ export function useSelectedThreadRequests() {
|
||||
null,
|
||||
);
|
||||
|
||||
// Sort once; both derivations expect the same lifecycle ordering.
|
||||
const sortedActivities = useMemo(
|
||||
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(sortedActivities),
|
||||
[sortedActivities],
|
||||
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => derivePendingUserInputs(sortedActivities),
|
||||
[sortedActivities],
|
||||
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
@@ -149,36 +148,27 @@ export function useThreadComposerState() {
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
// 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);
|
||||
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) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
});
|
||||
return messageId;
|
||||
return null;
|
||||
}
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
|
||||
@@ -21,11 +21,7 @@ import { toUploadChatImageAttachments } from "../lib/composerImages";
|
||||
import { randomHex } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useProjects, useThreadShells } from "./entities";
|
||||
import {
|
||||
confirmThreadOutboxMessageQueued,
|
||||
ensureThreadOutboxLoaded,
|
||||
removeThreadOutboxMessage,
|
||||
} from "./thread-outbox";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
isQueuedThreadCreationSendable,
|
||||
modelSelectionsEqual,
|
||||
@@ -37,7 +33,7 @@ import {
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { environmentThreadShells, threadEnvironment } from "./threads";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
import {
|
||||
editingQueuedMessageIdsAtom,
|
||||
@@ -353,32 +349,8 @@ export function useThreadOutboxDrain(): void {
|
||||
return false;
|
||||
},
|
||||
);
|
||||
// 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"
|
||||
const delivery =
|
||||
deliveryAction === "remove"
|
||||
? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
|
||||
: creation !== undefined
|
||||
? creationProjectCwd !== null
|
||||
@@ -387,7 +359,6 @@ 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.31",
|
||||
"version": "0.0.29",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -2,13 +2,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
@@ -216,21 +214,12 @@ describe("AssetAccess", () => {
|
||||
prefix: "t3-asset-favicon-",
|
||||
});
|
||||
const faviconPath = path.join(root, "favicon.svg");
|
||||
const initialFavicon = "<svg>a</svg>";
|
||||
const updatedFavicon = "<svg>b</svg>";
|
||||
expect(updatedFavicon).toHaveLength(initialFavicon.length);
|
||||
yield* fileSystem.writeFileString(faviconPath, initialFavicon);
|
||||
yield* fileSystem.writeFileString(faviconPath, "<svg />");
|
||||
const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
|
||||
|
||||
const faviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
expect(
|
||||
yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
}),
|
||||
).toEqual(faviconResult);
|
||||
const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const faviconSeparatorIndex = faviconSuffix.indexOf("/");
|
||||
expect(
|
||||
@@ -240,14 +229,6 @@ describe("AssetAccess", () => {
|
||||
),
|
||||
).toEqual({ kind: "file", path: canonicalFaviconPath });
|
||||
|
||||
yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
|
||||
const updatedFaviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(
|
||||
updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
|
||||
).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
|
||||
|
||||
yield* fileSystem.remove(faviconPath);
|
||||
const fallbackResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
@@ -264,31 +245,6 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("buckets project favicon expiry after content hashing", () =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-expiry-",
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg />");
|
||||
|
||||
const bucketMs = 30 * 60 * 1000;
|
||||
yield* TestClock.setTime(bucketMs - 1);
|
||||
const crossingCrypto = Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size),
|
||||
digest: (algorithm, data) =>
|
||||
TestClock.adjust("2 millis").pipe(Effect.andThen(crypto.digest(algorithm, data))),
|
||||
});
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
}).pipe(Effect.provideService(Crypto.Crypto, crossingCrypto));
|
||||
|
||||
expect(result.expiresAt).toBe(3 * bucketMs);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves structured project favicon resolution causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -21,9 +21,7 @@ import {
|
||||
} from "@t3tools/shared/filePreview";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -46,8 +44,6 @@ export const ASSET_ROUTE_PREFIX = "/api/assets";
|
||||
|
||||
const SIGNING_SECRET_NAME = "asset-access-signing-key";
|
||||
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
|
||||
const PROJECT_FAVICON_VERSION_PREFIX = "v";
|
||||
const PREVIEW_ASSET_EXTENSIONS = new Set([
|
||||
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
@@ -173,7 +169,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
const expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
let claims: AssetClaims;
|
||||
let fileName: string;
|
||||
|
||||
@@ -297,18 +293,18 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
),
|
||||
);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
const canonicalFaviconPath = relativePath
|
||||
? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
if (relativePath && !canonicalFaviconPath) {
|
||||
if (
|
||||
relativePath &&
|
||||
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
))
|
||||
) {
|
||||
return yield* new AssetProjectFaviconNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
@@ -328,31 +324,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
relativePath,
|
||||
expiresAt,
|
||||
};
|
||||
if (relativePath && canonicalFaviconPath) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
|
||||
Effect.map(Encoding.encodeHex),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(relativePath)}`;
|
||||
} else {
|
||||
fileName = PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
}
|
||||
fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -367,13 +339,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (claims.kind === "project-favicon") {
|
||||
const issuedAt = yield* Clock.currentTimeMillis;
|
||||
expiresAt =
|
||||
(Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
|
||||
PROJECT_FAVICON_TOKEN_BUCKET_MS;
|
||||
claims = { ...claims, expiresAt };
|
||||
}
|
||||
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
|
||||
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
|
||||
return {
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import {
|
||||
AuthOrchestrationOperateScope,
|
||||
AuthOrchestrationReadScope,
|
||||
AuthRelayReadScope,
|
||||
AuthRelayWriteScope,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { RPC_REQUIRED_SCOPES, requiredScopeForRpcMethod } from "./RpcAuthorization.ts";
|
||||
|
||||
describe("RPC authorization scopes", () => {
|
||||
it("declares exactly one scope for every RPC in the server group", () => {
|
||||
expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
|
||||
});
|
||||
|
||||
it("authorizes background policy reporting and observation deliberately", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.serverReportClientActivity)).toBe(
|
||||
AuthOrchestrationReadScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.serverReportHostPowerState)).toBe(
|
||||
AuthOrchestrationOperateScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.serverGetBackgroundPolicy)).toBe(
|
||||
AuthOrchestrationReadScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.subscribeBackgroundPolicy)).toBe(
|
||||
AuthOrchestrationReadScope,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows relay status reads without granting relay installation access", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.cloudGetRelayClientStatus)).toBe(
|
||||
AuthRelayReadScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);
|
||||
});
|
||||
|
||||
it("rejects unknown RPC method names", () => {
|
||||
for (const method of ["server.notRegistered", "toString", "constructor"]) {
|
||||
expect(() => requiredScopeForRpcMethod(method)).toThrow(
|
||||
`RPC method ${method} has no declared authorization scope.`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loaded 100 of 392 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user