diff --git a/.agents/skills/test-t3-mobile/SKILL.md b/.agents/skills/test-t3-mobile/SKILL.md index f910fdc2dc..82a1fe6e19 100644 --- a/.agents/skills/test-t3-mobile/SKILL.md +++ b/.agents/skills/test-t3-mobile/SKILL.md @@ -42,11 +42,13 @@ prints one JSON line; on failure it names the next command. Authorized mobile verification includes that step unless the user prohibits it. For a device you opened in an agent-device session elsewhere (a device pool, -cloud, or remote host), run `vp run mobile:install ios --session ` -from the directory you opened the session in. It installs the cached build into -that session (`--metro ` also opens it against Metro), building it here first on a cache miss. Run -`vp run mobile:install ios --prepare` before leasing a device so a -build does not outlast the lease. +cloud, or remote host), run `vp run mobile:install ios --session +--config ` from the directory you opened the session in, passing the +`--config` file from `device_open`'s `targetArgs`. Without it, a device pool's +gateway refuses the install, wrongly saying agent-device is too old. It installs +the cached build into that session (`--metro ` also opens it against Metro). +Without a cached build for this checkout it builds first, which can outlast the +lease, so run `vp run mobile:install ios --prepare` before you open the device. Start `vp run dev:client` from `apps/mobile`, or reuse a healthy Metro belonging to this checkout. Open its printed development-client URL with AgentDevice diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index 7a6a1aa122..d2d9cf5939 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -17,7 +17,7 @@ runs: - name: Cache Vite+ id: vp_cache if: steps.vp.outputs.version != '' - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.vite-plus key: vite-plus-home-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} @@ -35,7 +35,7 @@ runs: - name: Setup Vite+ if: steps.vp_cache.outputs.cache-hit != 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: false @@ -55,7 +55,7 @@ runs: # package across filesystems instead of hard-linking it: install took 28-49s # against 9s plus an 11s restore. - name: Cache full pnpm store - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.pnpm_store.outputs.path }} key: pnpm-full-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d71786cba8..5bc1d53ce8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,7 +40,7 @@ jobs: # Only the package manifests the script reads to build the dependency graph. # Depth 2 brings the base commit the change is diffed against. - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 2 sparse-checkout: | @@ -66,7 +66,7 @@ jobs: timeout-minutes: 20 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -88,7 +88,7 @@ jobs: # electron's install.js (run by ensure:electron) reads this cache before it # downloads from GitHub. The key changes only with the Electron version. - name: Cache Electron download - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/electron key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} @@ -117,7 +117,7 @@ jobs: timeout-minutes: 20 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -145,7 +145,7 @@ jobs: # electron's install.js (run by ensure:electron) reads this cache before it # downloads from GitHub. The key changes only with the Electron version. - name: Cache Electron download - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/electron key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} @@ -197,7 +197,7 @@ jobs: - name: Upload desktop launch check if: ${{ failure() && steps.desktop_launch.outcome == 'failure' }} - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: desktop-launch-check path: ${{ runner.temp }}/desktop-launch-check @@ -215,7 +215,7 @@ jobs: - name: Cache Chromium id: chromium_cache if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.test_web != 'false' }} - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/ms-playwright key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} @@ -260,7 +260,7 @@ jobs: timeout-minutes: 20 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -297,7 +297,7 @@ jobs: # electron's install.js (run by ensure:electron) reads this cache before it # downloads from GitHub. The key changes only with the Electron version. - name: Cache Electron download - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/electron key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} @@ -345,7 +345,7 @@ jobs: shard: [1, 2, 3, 4] steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -364,7 +364,7 @@ jobs: - name: Cache Chromium id: chromium_cache - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/ms-playwright key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} @@ -403,7 +403,7 @@ jobs: steps: # Depth 2 brings the base commit the change is diffed against. - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 2 sparse-checkout: | @@ -432,7 +432,7 @@ jobs: - name: Cache Chromium id: chromium_cache if: steps.changes.outputs.test_server != 'false' - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/ms-playwright key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} @@ -450,12 +450,30 @@ jobs: node apps/server/node_modules/playwright-core/cli.js install-deps chromium fi + # A fresh install starts Vitest's content-keyed module cache empty, so every file + # re-transformed its imports. + # Only pushes to main save it, so pull requests never evict each other's entries. + - name: Restore Vitest module cache + if: steps.changes.outputs.test_server != 'false' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: node_modules/.vitest-cache + key: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} + restore-keys: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}- + - name: Test if: steps.changes.outputs.test_server != 'false' env: T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md run: vp run --filter t3 test --shard ${{ matrix.shard }}/${{ strategy.job-total }} + - name: Save Vitest module cache + if: github.event_name == 'push' && steps.changes.outputs.test_server != 'false' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: node_modules/.vitest-cache + key: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} + # the v2 transfer budget suite writes markdown on one shard # summarize that report when it exists - name: Detect transfer budget report @@ -479,7 +497,7 @@ jobs: - name: Upload transfer budget measurements if: always() && steps.transfer_budget.outputs.present == 'true' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: transfer-budget-report path: ${{ runner.temp }}/t3code-transfer-budget.md @@ -496,7 +514,7 @@ jobs: timeout-minutes: 20 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -505,8 +523,9 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master with: + toolchain: stable components: rustfmt - name: Check Rust formatting @@ -529,7 +548,7 @@ jobs: timeout-minutes: 20 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -537,7 +556,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -581,7 +600,7 @@ jobs: # a run whose server tests ran must have produced the transfer budget report - name: Require transfer budget measurements if: needs.test_server.result == 'success' && needs.changes.outputs.test_server != 'false' - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: transfer-budget-report path: ${{ runner.temp }}/transfer-budget diff --git a/.github/workflows/mobile-fingerprint-check.yml b/.github/workflows/mobile-fingerprint-check.yml index ac15e8f9a1..bdd0a1964e 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -24,7 +24,7 @@ jobs: NODE_OPTIONS: --max-old-space-size=8192 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: # The merge ref can advance after the event is queued. Pin its commit # and compare against its first parent, rather than the event's base. @@ -49,7 +49,7 @@ jobs: - name: Setup Vite+ if: steps.changes.outputs.relevant == 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true diff --git a/.gitignore b/.gitignore index 50dbbbd94a..e754ca8233 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,5 @@ node_modules/ # pnpm content-addressable store; never belongs in the repo. .pnpm-store/ + +/packages/ssh/.ssh-launcher-test-*/ diff --git a/AGENTS.md b/AGENTS.md index faccde20c2..1430d4fbfa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ The principles describe requirements, not verified current behavior or blanket a ## Retained T3 Code guidance -T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs and agents (Codex, Claude Code, Cursor, Grok, OpenCode, Antigravity, Kiro) and serves web, desktop, and mobile clients. +T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs and agents (Codex, Claude Code, Cursor, Grok, OpenCode, Antigravity, Kiro, Pi, Muse Code, fx) and serves web, desktop, and mobile clients. You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor. @@ -76,7 +76,7 @@ The most common defect in this repo is a change that works on the path you teste - **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature. - **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime` -- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, Antigravity, and Kiro each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here". +- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, Antigravity, Kiro, Pi, Muse Code, fx, and ACP Registry each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here". - **Agents.** A capability a user can trigger is usually one an agent should reach through MCP tools, and scheduled tasks run the same paths. That only works when it is a service method, not handler code. - **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. @@ -91,7 +91,8 @@ The most common defect in this repo is a change that works on the path you teste - Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift. - Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, then give that full URL to an unpaired browser. Do not wire up `tailscale serve` by hand, open the URL yourself, or consume the user's pairing link. A browser with the reusable dev cookie can use the bare origin. If a normal one-time token was consumed, mint a fresh one with `node apps/server/src/bin.ts pair`. It carries standard scopes, while the startup URL carries admin scopes needed for Connections settings. - To reuse web dev auth across worktrees, configure one fixed `T3CODE_DEV_AUTH_TOKEN` in the main checkout's gitignored `.env`. The `t3.json` setup links that file into worktrees. Never commit or publish the token or a startup URL. See [Reusable dev credential](docs/operations/development.md#reusable-dev-credential). -- Stop what you started, by the PID you tracked. See rule 1. +- Stop what you started, by the PID you tracked. See rule 1. `vp` does not pass SIGTERM on, so signalling the `vp run dev` PID alone leaves Vite and the server running. Stop the background task with your harness's own stop, which ends the whole tree. +- Run dev servers, Metro, and builds from your own shell so they end with your session. Do not detach them with `systemd-run`, `nohup`, `setsid`, or `tmux` unless the user asks for one that outlives the session. Detached servers ran for weeks and filled RAM and swap. The dev runner stops itself above `--memory-limit-gb` (half of RAM, at most 16 GiB) on Linux. - Need a second checkout? `git worktree add` it next to this worktree, not in `/tmp`. Remove it when done. ## Test data @@ -111,6 +112,7 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real - Use `vp run typecheck`; it caches per package. Each package runs `effect-tsgo tsrs --noEmit`, the Rust TypeScript 7 checker with Effect's diagnostics built in. There is no `typescript` package to run. - Run `node -e` snippets from `apps/server` or the owning package. `effect` does not resolve from the repo root. - Test meaningful logic or observable behavior. Do not render components to static markup to assert props or attributes, or add tests that merely assert callback wiring or mirror the implementation. +- Write a browser test only for behavior that needs a real browser: layout and scrolling, focus and pointer input, real workers, or a component wired to its hooks. Logic a component calls gets a unit test beside it (`*.logic.test.ts`). A browser test file spends seconds in CI loading its module graph before its first test runs; a unit test takes milliseconds. - **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite. - Backend behavior changes ship with focused tests for that behavior. - Proof for a bug fix depends on the bug. Logic, data, state, and protocol bugs get a failing test first (the fewest that fail on `main` for that reason, in the module's existing test file), then the fix. Purely visual bugs (spacing, colour, alignment, a layout shift) get before/after captures as their proof and no test: do not add UI tests for nitpicks, and do not ask for one in review when a capture already shows it. A server-only fix with no visible surface ships the test plus a short runtime transcript. @@ -151,7 +153,7 @@ For authorized mobile verification, a missing or outdated native client is an in ## Pull requests - Never make a PR unless the developer explicitly asks you to do so. -- If `origin` is git.cafe, follow [GitCafe mirror](docs/operations/development.md#gitcafe-mirror-optional): push to `origin`, open and track PRs with `cafe` and their git.cafe URLs, and keep `gh` for merging. +- `origin` is not always GitHub. Check `git remote get-url origin` before your first forge command and use that forge's CLI and skill. See [Forge mirror](docs/operations/development.md#forge-mirror-optional). - Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`. - Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work. - UI changes need before/after images. Motion or timing needs a short video. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 38806aa6bc..7d0e69b534 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.8", + "version": "0.1.9", "private": true, "type": "module", "main": "dist-electron/boot.cjs", @@ -20,7 +20,7 @@ "dbus-next": "0.10.2", "effect": "catalog:", "electron": "44.10.1", - "electron-updater": "^6.8.9", + "electron-updater": "6.8.9", "electron-webauthn": "catalog:", "ffi-rs": "1.3.2", "playwright-core": "1.64.1", @@ -33,6 +33,7 @@ "acorn": "8.16.0", "cross-env": "^10.1.0", "electron-builder": "26.16.1", + "jsdom": "^30.0.1", "tailwindcss": "^4.0.0", "vite-plus": "catalog:" }, diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 07578297f0..122da3f051 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -52,6 +52,8 @@ const childTreeGracePeriodMs = 1_200; const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim(); // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime. const hostPlatform = NodeOS.platform(); +const parentPid = process.ppid; +const parentWatchIntervalMs = 1_000; NodeChildProcess.execFileSync( process.execPath, @@ -271,3 +273,14 @@ process.once("SIGTERM", () => { process.once("SIGHUP", () => { void shutdown(129); }); +// A parent killed without forwarding a signal leaves us reparented (to a subreaper on Linux, not +// necessarily PID 1), and nothing else would ever stop the restart loop. This only notices the +// death of our direct parent, so vite.config.ts launches us without a shell in between. Windows +// never reparents, and reading process.ppid there snapshots the process table. +if (hostPlatform !== "win32") { + setInterval(() => { + if (process.ppid !== parentPid) { + void shutdown(129); + } + }, parentWatchIntervalMs).unref(); +} diff --git a/apps/desktop/scripts/electron-launcher.test.mjs b/apps/desktop/scripts/electron-launcher.test.mjs index fa6e56b580..96fbd626ae 100644 --- a/apps/desktop/scripts/electron-launcher.test.mjs +++ b/apps/desktop/scripts/electron-launcher.test.mjs @@ -118,19 +118,21 @@ describe("electron development launcher", () => { }); }); -async function startupCleanupPattern(desktopDir) { +// Supply inert imports so the real startup runs without launching Electron or signalling processes. +async function runDevElectronStartup({ + desktopDir = "/repo/apps/desktop", + spawnSync, + spawn, + ...context +}) { const source = NodeFS.readFileSync(new URL("./dev-electron.mjs", import.meta.url), "utf8"); - let pattern; - // Supply inert imports so the real startup runs without launching Electron or signalling processes. await NodeVM.runInNewContext( `(async () => { ${source.replace(/^import\s[\s\S]*?;\n/gm, "")} })()`, { NodeChildProcess: { execFileSync: () => undefined, - spawnSync: (command, args) => { - if (command === "pkill" && args.includes("-f")) pattern = args.at(-1); - }, - spawn: () => new NodeEvents.EventEmitter(), + spawnSync: spawnSync ?? (() => undefined), + spawn: spawn ?? (() => new NodeEvents.EventEmitter()), }, NodeFS: { watch: () => ({ close: () => undefined }) }, NodeOS: { platform: () => "linux" }, @@ -140,17 +142,114 @@ async function startupCleanupPattern(desktopDir) { resolveElectronLaunchCommand: (args) => ({ electronPath: "electron", args }), waitForResources: async () => undefined, URL, + ...makeFakeClock(), process: { env: { VITE_DEV_SERVER_URL: "http://localhost:1234" }, execPath: "node", + ppid: 1, once: () => undefined, }, + ...context, }, ); +} + +async function startupCleanupPattern(desktopDir) { + let pattern; + await runDevElectronStartup({ + desktopDir, + spawnSync: (command, args) => { + if (command === "pkill" && args.includes("-f")) pattern = args.at(-1); + }, + }); assert.isString(pattern); return pattern; } +function makeFakeClock() { + let now = 0; + let timers = []; + const schedule = (callback, delay, repeat) => { + const timer = { callback, due: now + (delay ?? 0), repeat: repeat ? (delay ?? 0) : null }; + timer.handle = { unref: () => timer.handle, ref: () => timer.handle }; + timers.push(timer); + return timer.handle; + }; + const clear = (handle) => { + timers = timers.filter((timer) => timer.handle !== handle); + }; + const flushMicrotasks = async () => { + for (let index = 0; index < 50; index += 1) await Promise.resolve(); + }; + return { + setTimeout: (callback, delay) => schedule(callback, delay, false), + setInterval: (callback, delay) => schedule(callback, delay, true), + clearTimeout: clear, + clearInterval: clear, + async advance(ms) { + const end = now + ms; + for (;;) { + await flushMicrotasks(); + const next = timers + .filter((timer) => timer.due <= end) + .toSorted((a, b) => a.due - b.due)[0]; + if (!next) break; + now = next.due; + if (next.repeat === null) clear(next.handle); + else next.due = now + Math.max(next.repeat, 1); + next.callback(); + } + now = end; + await flushMicrotasks(); + }, + }; +} + +it("dev supervisor stops Electron and exits once its parent process goes away", async () => { + const clock = makeFakeClock(); + let ppid = 4242; + const exitCodes = []; + const appSignals = []; + await runDevElectronStartup({ + ...clock, + spawn: () => { + const app = new NodeEvents.EventEmitter(); + app.pid = 5151; + app.kill = (signal) => { + appSignals.push(signal); + app.emit("exit", null, signal); + }; + return app; + }, + process: { + env: { VITE_DEV_SERVER_URL: "http://localhost:1234" }, + execPath: "node", + pid: 4343, + get ppid() { + return ppid; + }, + once: () => undefined, + exit: (code) => { + exitCodes.push(code); + }, + }, + }); + + await clock.advance(5_000); + assert.deepEqual(appSignals, [], "supervisor stopped Electron while its parent was alive"); + + // The launching process died without signalling us; the OS reparented the supervisor. + ppid = 1; + await clock.advance(5_000); + + assert.include( + appSignals, + "SIGTERM", + "supervisor kept Electron running after its parent process went away", + ); + assert.lengthOf(exitCodes, 1, "supervisor did not exit after its parent process went away"); +}); + it // oxlint-disable-next-line t3code/no-global-process-runtime -- Native pgrep is unavailable on Windows. .skipIf(NodeOS.platform() === "win32") diff --git a/apps/desktop/scripts/ensure-electron-runtime.mjs b/apps/desktop/scripts/ensure-electron-runtime.mjs index 933a763dfa..741a2d9ee8 100644 --- a/apps/desktop/scripts/ensure-electron-runtime.mjs +++ b/apps/desktop/scripts/ensure-electron-runtime.mjs @@ -209,6 +209,10 @@ export function ensureElectronRuntime() { return electronPath; } +export function setup() { + ensureElectronRuntime(); +} + // `file://${argv[1]}` never matches on Windows (drive letters need `file:///C:/`). if (process.argv[1] && NodeURL.pathToFileURL(process.argv[1]).href === import.meta.url) { const electronPath = ensureElectronRuntime(); diff --git a/apps/desktop/src/app/CodexAuthCallback.test.ts b/apps/desktop/src/app/CodexAuthCallback.test.ts index d774fb993f..0d53614810 100644 --- a/apps/desktop/src/app/CodexAuthCallback.test.ts +++ b/apps/desktop/src/app/CodexAuthCallback.test.ts @@ -5,13 +5,25 @@ import { codexAuthDeliveryUrl, readCodexAuthDelivery } from "@t3tools/shared/cod import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; import { receiveCodexAuthCallback, cancelCodexAuthCallback } from "./CodexAuthCallback.ts"; +// Holds every probe socket until all ports are read, so one call never returns the same port twice. +async function freePorts(count: number) { + const servers = Array.from({ length: count }, () => NodeHttp.createServer()); + await Promise.all( + servers.map((server) => new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))), + ); + const ports = servers.map((server) => { + const address = server.address(); + if (!address || typeof address === "string") throw new Error("address"); + return address.port; + }); + await Promise.all( + servers.map((server) => new Promise((resolve) => server.close(() => resolve()))), + ); + return ports; +} async function freePort() { - const server = NodeHttp.createServer(); - await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); - const address = server.address(); - if (!address || typeof address === "string") throw new Error("address"); - await new Promise((resolve) => server.close(() => resolve())); - return address.port; + const [port] = await freePorts(1); + return port!; } function request(port: number, state = "a".repeat(43)) { const url = new URL("https://auth.openai.com/api/accounts/authorize"); @@ -37,18 +49,27 @@ function callback(authorizationUrl: string) { } describe("desktop Codex callback helper", () => { - it("binds before opening sign-in, ignores a foreign response, and returns only the code callback", async () => { + it("binds before opening sign-in, ignores a foreign response, and returns only the code callback", async ({ + onTestFinished, + }) => { const authorizationUrl = request(await freePort()); const expected = callback(authorizationUrl); - const received = await receiveCodexAuthCallback(authorizationUrl, async () => { + const opening = Promise.withResolvers(); + onTestFinished(() => opening.resolve(true)); + const checkResponse = async () => { const invalid = new URL(expected); invalid.searchParams.set("state", "foreign"); expect((await fetch(invalid)).status).toBe(400); const response = await fetch(expected); expect(response.headers.get("cache-control")).toBe("no-store"); expect(await response.text()).not.toContain("test-code"); - return true; + }; + let responseChecked!: Promise; + const received = await receiveCodexAuthCallback(authorizationUrl, () => { + responseChecked = checkResponse(); + return responseChecked.then(() => opening.promise); }); + await responseChecked; expect(received).toBe(expected); }); it("returns web to the exact instance and environment without putting the code in its query", async () => { @@ -62,38 +83,57 @@ describe("desktop Codex callback helper", () => { instanceId: ProviderInstanceId.make("work"), flowId: "flow-one", }; + const openBrowser = async () => { + const response = await fetch(expected, { redirect: "manual" }); + expect(response.status).toBe(303); + const delivery = response.headers.get("location")!; + expect(new URL(delivery).searchParams.has("code")).toBe(false); + expect(readCodexAuthDelivery(delivery)?.callbackUrl).toBe(expected); + expect(readCodexAuthDelivery(delivery)?.returnUrl).toBe(input.returnUrl); + return true; + }; + let opening!: Promise; await receiveCodexAuthCallback( authorizationUrl, - async () => { - const response = await fetch(expected, { redirect: "manual" }); - expect(response.status).toBe(303); - const delivery = response.headers.get("location")!; - expect(new URL(delivery).searchParams.has("code")).toBe(false); - expect(readCodexAuthDelivery(delivery)?.callbackUrl).toBe(expected); - expect(readCodexAuthDelivery(delivery)?.returnUrl).toBe(input.returnUrl); - return true; - }, + () => (opening = openBrowser()), (url) => codexAuthDeliveryUrl(input, url), ); + await opening; }); - it("cancels and releases its listener so exact-port reauthorization can run again", async () => { - const authorizationUrl = request(await freePort()); - await expect( - receiveCodexAuthCallback(authorizationUrl, async () => { - cancelCodexAuthCallback(authorizationUrl); - return true; - }), - ).rejects.toThrow("cancelled"); - expect( - await receiveCodexAuthCallback(authorizationUrl, async () => { - await fetch(callback(authorizationUrl)); - return true; - }), - ).toBe(callback(authorizationUrl)); + it("cancels and releases its listener so exact-port reauthorization can run again", async ({ + onTestFinished, + signal, + }) => { + for (const external of [false, true]) { + const authorizationUrl = request(await freePort()); + const abort = new AbortController(); + const opening = Promise.withResolvers(); + onTestFinished(() => opening.resolve(true)); + await expect( + receiveCodexAuthCallback( + authorizationUrl, + async () => { + if (external) abort.abort(); + else cancelCodexAuthCallback(authorizationUrl); + return opening.promise; + }, + undefined, + abort.signal, + ), + ).rejects.toThrow("cancelled"); + if (signal.aborted) return; + expect( + await receiveCodexAuthCallback(authorizationUrl, async () => { + await fetch(callback(authorizationUrl)); + return true; + }), + ).toBe(callback(authorizationUrl)); + } }); it("allows two accounts to complete independently", async () => { - const a = request(await freePort(), "a".repeat(43)); - const b = request(await freePort(), "c".repeat(43)); + const [portA, portB] = await freePorts(2); + const a = request(portA!, "a".repeat(43)); + const b = request(portB!, "c".repeat(43)); const openedA = Promise.withResolvers(); const openedB = Promise.withResolvers(); const receiveA = receiveCodexAuthCallback(a, async () => { diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index 247af473a6..72ba966a37 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -58,6 +58,7 @@ import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore. import * as DesktopIpc from "../ipc/DesktopIpc.ts"; import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts"; import * as DesktopManagedPolicy from "./DesktopManagedPolicy.ts"; +import * as DesktopPrimaryPaste from "./DesktopPrimaryPaste.ts"; import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts"; import * as DesktopWebLinks from "./DesktopWebLinks.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; @@ -82,6 +83,7 @@ it.effect.each([false, true])( const historyStarted = yield* Deferred.make(); const releaseHistory = yield* Deferred.make(); const quitting = yield* Ref.make(false); + const tokenRequested = yield* Deferred.make(); const events: string[] = []; const record = (event: string) => Effect.sync(() => { @@ -105,6 +107,7 @@ it.effect.each([false, true])( platform: "linux", isDevelopment: false, isPackaged: true, + stateDir: "/isolated/userdata", configuredBackendPort: Option.some(3773), defaultDesktopSettings: { serverExposureMode: "local-only" }, } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), @@ -136,7 +139,7 @@ it.effect.each([false, true])( configure: Effect.void, } as PreviewPasskeys.PreviewPasskeys["Service"]), Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { - configure: Effect.void, + configure: record("menu"), }), Effect.provideService(DesktopUpdates.DesktopUpdates, { configure: Effect.void, @@ -215,8 +218,14 @@ it.effect.each([false, true])( Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), Layer.mock(DesktopIpc.DesktopIpc, {}), - Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, {}), + Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { + getBearerToken: record("token").pipe( + Effect.andThen(Deferred.succeed(tokenRequested, undefined)), + Effect.as("token"), + ), + }), Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), @@ -243,7 +252,13 @@ it.effect.each([false, true])( ); yield* Deferred.await(registrationStarted); yield* Deferred.await(windowStarted); - assert.deepEqual(events, ["identity", "ready", "identity", "backend", "window"]); + yield* Deferred.await(tokenRequested); + // The backend spawns before menus, and its token is minted without waiting for the renderer. + assert.deepEqual( + events.filter((event) => event !== "token"), + ["identity", "ready", "identity", "backend", "menu", "window"], + ); + assert.isAbove(events.indexOf("token"), events.indexOf("backend")); assert.isFalse(yield* Deferred.isDone(registrationStopped)); const shutdown = yield* DesktopShutdown.DesktopShutdown; yield* shutdown.request; diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index a689dee77f..28d7cbcd9e 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -21,6 +21,8 @@ import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as PreviewPasskeys from "../preview/Passkeys.ts"; import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; +import * as DesktopHomeOwner from "../backend/DesktopHomeOwner.ts"; +import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts"; import * as DesktopLifecycle from "./DesktopLifecycle.ts"; @@ -168,13 +170,12 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( }, ); -const bootstrap = Effect.gen(function* () { +// Spawns the local backend as soon as the protocol, IPC, and legacy storage that every window needs exist. +const startLocalBackend = Effect.gen(function* () { const state = yield* DesktopState.DesktopState; const environment = yield* DesktopEnvironment.DesktopEnvironment; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; const desktopWindow = yield* DesktopWindow.DesktopWindow; - const snapShot = yield* DesktopSnapShot.DesktopSnapShot; - const appActivation = yield* DesktopAppActivation.DesktopAppActivation; yield* logBootstrapInfo("bootstrap start"); const settings = yield* desktopSettings.get; @@ -192,37 +193,35 @@ const bootstrap = Effect.gen(function* () { yield* (yield* DesktopAppIdentity.DesktopAppIdentity).resolveUserDataPath, ); - yield* snapShot.initialize; - // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has - // no cached one. Without it, the command is left to Settings. - const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch; - yield* Effect.forkScoped( - (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe( - Effect.flatMap((found) => - found || environment.platform === "win32" - ? installCli - : logBootstrapInfo("skipped installing the t3 command without the shell PATH"), - ), - ), - ); - if (!settings.localEnvironmentEnabled) { yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)"); - if (!(yield* Ref.get(state.quitting))) { - yield* desktopWindow.createMainIfBackendReady; - } - return; + return false; } - const pool = yield* DesktopBackendPool.DesktopBackendPool; - const primaryBackend = yield* pool.primary; + const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - const wslBackend = yield* DesktopWslBackend.DesktopWslBackend; if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) { return yield* new DesktopDevelopmentBackendPortRequiredError(); } + // A backend started while another server holds this home's lock can only exit with code 78. + if ( + !(settings.wslOnly && settings.wslBackendEnabled) && + !(yield* DesktopHomeOwner.awaitHomeOwnershipRelease()) + ) { + const owner = yield* DesktopHomeOwner.readLiveHomeOwner(); + yield* logBootstrapWarning("bootstrap found another server owning the T3 home", { + owner: Option.getOrNull(owner), + }); + yield* (yield* ElectronDialog.ElectronDialog).showErrorBox( + "This T3 home is unavailable", + DesktopHomeOwner.homeOwnedMessage(owner), + ); + yield* (yield* ElectronApp.ElectronApp).quit; + return false; + } + const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort); const backendPort = backendPortSelection.port; yield* logBootstrapInfo( @@ -258,29 +257,71 @@ const bootstrap = Effect.gen(function* () { ); } - if (!(yield* Ref.get(state.quitting))) { - if (settings.wslOnly === true && settings.wslBackendEnabled === true) { - yield* desktopWindow.showConnectingSplash; - } - yield* primaryBackend.start; - yield* logBootstrapInfo("bootstrap backend start requested"); - // WSL-only fallback can change the primary endpoint before readiness. - const config = yield* primaryBackend.currentConfig; - if ( - !environment.isDevelopment && - !settings.wslOnly && - Option.isSome(config) && - Option.isNone(config.value.preflightFailure) - ) { - yield* desktopWindow.ensureMain; + if (yield* Ref.get(state.quitting)) { + return false; + } + if (settings.wslOnly === true && settings.wslBackendEnabled === true) { + yield* desktopWindow.showConnectingSplash; + } + yield* primaryBackend.start; + yield* logBootstrapInfo("bootstrap backend start requested"); + // The renderer asks for this token first; minting it at readiness saves a round trip. + yield* Effect.forkScoped( + (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe( + Effect.ignore, + ), + ); + return true; +}).pipe(Effect.withSpan("desktop.startLocalBackend")); + +const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: boolean) { + const state = yield* DesktopState.DesktopState; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; + const desktopWindow = yield* DesktopWindow.DesktopWindow; + const snapShot = yield* DesktopSnapShot.DesktopSnapShot; + const appActivation = yield* DesktopAppActivation.DesktopAppActivation; + const settings = yield* desktopSettings.get; + if (settings.localEnvironmentEnabled && (!backendStarted || (yield* Ref.get(state.quitting)))) { + return; + } + + yield* snapShot.initialize; + // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has + // no cached one. Without it, the command is left to Settings. + const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch; + yield* Effect.forkScoped( + (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe( + Effect.flatMap((found) => + found || environment.platform === "win32" + ? installCli + : logBootstrapInfo("skipped installing the t3 command without the shell PATH"), + ), + ), + ); + + if (!settings.localEnvironmentEnabled) { + if (!(yield* Ref.get(state.quitting))) { + yield* desktopWindow.createMainIfBackendReady; } - yield* appActivation.start.pipe( - Effect.tap(() => logBootstrapInfo("desktop app control socket ready")), - Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })), - ); - yield* Effect.forkScoped(wslBackend.reconcile); + return; + } + + const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary; + const config = yield* primaryBackend.currentConfig; + if ( + !environment.isDevelopment && + Option.isSome(config) && + Option.isNone(config.value.preflightFailure) + ) { + yield* desktopWindow.ensureMain; } -}).pipe(Effect.withSpan("desktop.bootstrap")); + yield* appActivation.start.pipe( + Effect.tap(() => logBootstrapInfo("desktop app control socket ready")), + Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })), + ); + yield* Effect.forkScoped((yield* DesktopWslBackend.DesktopWslBackend).reconcile); +}); const startup = Effect.gen(function* () { const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity; @@ -352,14 +393,20 @@ const startup = Effect.gen(function* () { }); } yield* appIdentity.configure; - yield* previewPasskeys.configure; - yield* applicationMenu.configure; + // Sets canInstallUpdates, which the backend bootstrap payload reads. yield* updates.configure; yield* DesktopRemoteUpdates.listen; yield* DesktopStartupRecovery.listen; + const backendStarted = yield* startLocalBackend.pipe( + Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)), + ); + yield* previewPasskeys.configure; + yield* applicationMenu.configure; // Portal identity is prepared pre-ready; MIME helpers must not gate the backend or window. yield* linuxUrlHandler.register.pipe(Effect.forkScoped); - yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause))); + yield* bootstrap(backendStarted).pipe( + Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)), + ); }).pipe(Effect.withSpan("desktop.startup")); const scopedProgram = Effect.scoped( diff --git a/apps/desktop/src/app/DesktopCliCommand.test.ts b/apps/desktop/src/app/DesktopCliCommand.test.ts index 772f84717a..1f8422fdf6 100644 --- a/apps/desktop/src/app/DesktopCliCommand.test.ts +++ b/apps/desktop/src/app/DesktopCliCommand.test.ts @@ -161,7 +161,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect(yield* fs.exists(upgradedLink)).toBe(false); expect((yield* upgraded.install).installedPath).toBe(upgradedLink); } - }).pipe(Effect.scoped), + }), ); it.effect("never replaces or removes a t3 it did not create", () => @@ -203,7 +203,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect((yield* Effect.flip(command.install)).message).toContain("Could not set up"); yield* command.uninstall; expect(yield* fs.readFileString(launcher)).toBe("npm's t3\n"); - }).pipe(Effect.scoped), + }), ); it.effect("finds and removes a link left by a previous T3 home", () => @@ -260,7 +260,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { ); expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false); expect(yield* fs.readFileString(path.join(home, "bin", "t3.staging"))).toBe("mine"); - }).pipe(Effect.scoped), + }), ); it.effect("refuses to install behind another t3 that runs first", () => @@ -310,7 +310,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { installedPath: path.join(home, ".local", "bin", "t3"), }); expect(installed.shadowedBy).toBeUndefined(); - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( @@ -344,7 +344,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { onPath: true, installedPath: path.join(home, ".local", "bin", "t3"), }); - }).pipe(Effect.scoped), + }), ); it.effect("does not treat its own launcher as another t3 when its folder is first on PATH", () => @@ -373,7 +373,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect(yield* command.state).toEqual(removed); expect(yield* fs.exists(installed.installedPath!)).toBe(false); expect(yield* fs.exists(launcher)).toBe(true); - }).pipe(Effect.scoped), + }), ); it.effect("leaves the Windows PATH alone when it cannot be read", () => @@ -412,7 +412,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { const reader = yield* commandIn({ home, platform: "win32" }, inherited.spawner); yield* reader.install; expect(inherited.registry).toMatchObject({ path: `${userPath};${launcherDir}`, writes: 1 }); - }).pipe(Effect.scoped), + }), ); it.effect("does not claim or remove a Windows PATH entry the user added", () => @@ -442,6 +442,6 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { yield* (yield* commandIn({ home: besideHome, platform: "win32" }, beside.spawner)) .installOnFirstLaunch; expect(beside.registry).toMatchObject({ path: "C:\\Tools", writes: 0 }); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 50fcb08d9c..3e8b4967df 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -39,12 +39,12 @@ const run = (shim: string, args: ReadonlyArray, env: NodeJS.ProcessEnv = }); const REPORTER = - '#!/bin/sh\necho "node=$ELECTRON_RUN_AS_NODE cli=$T3CODE_CLI_PATH home=$T3CODE_HOME"\nprintf "%s\\n" "$@"\nexit 3\n'; + '#!/bin/sh\necho "node=$ELECTRON_RUN_AS_NODE cli=$T3CODE_CLI_PATH home=$T3CODE_HOME appimage=$APPIMAGE"\nprintf "%s\\n" "$@"\nexit 3\n'; -const fakeAppImage = (canMount = true) => { +const fakeAppImage = (canMount = true, app = REPORTER) => { const root = tempRoot(); const image = NodePath.join(root, "image"); - writeExecutable(NodePath.join(image, "t3code"), REPORTER); + writeExecutable(NodePath.join(image, "t3code"), app); const appImage = NodePath.join(root, "T3 Code.AppImage"); writeExecutable( appImage, @@ -53,8 +53,11 @@ const fakeAppImage = (canMount = true) => { `if [ "$1" = --appimage-extract ]; then cp -R '${image}' squashfs-root; exit 0; fi`, '[ "$1" = --appimage-mount ] || exit 9', '[ -n "$APPIMAGE_EXTRACT_AND_RUN" ] && exit 8', + `echo $$ >'${root}/mounter.pid'`, canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1', - `trap 'touch "${root}/unmounted"; exit 0' TERM`, + // Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open. + "trap 'echo unmounted >&3 2>/dev/null; exit 0' TERM HUP INT", + "trap 'echo mounted >&3 2>/dev/null' WINCH", "while :; do sleep 0.05; done", "", ].join("\n"), @@ -63,7 +66,81 @@ const fakeAppImage = (canMount = true) => { return { root, image, appImage, shim }; }; +// Stays up after a signal until the test lets it finish, like a server shutting down. +const SLOW_SERVER = [ + "#!/bin/sh", + "trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP", + "echo ready", + "while :; do sleep 0.05; done", + "", +].join("\n"); + +// The launcher mounts only under setsid, which stock macOS and Windows lack; there it extracts instead. +const hasSetsid = NodeChildProcess.spawnSync("setsid", ["true"]).status === 0; + +const lines = (stream: NodeJS.ReadableStream) => { + const seen: Array = []; + const waiters: Array<() => void> = []; + let buffer = ""; + stream.setEncoding("utf8"); + stream.on("data", (chunk: string) => { + buffer += chunk; + const parts = buffer.split("\n"); + buffer = parts.pop()!; + seen.push(...parts); + for (const wake of waiters.splice(0)) wake(); + }); + const until = async (match: (line: string) => boolean) => { + for (;;) { + const line = seen.find(match); + if (line !== undefined) return line; + await new Promise((resolve) => waiters.push(resolve)); + } + }; + return { seen, until }; +}; + describe("renderCliShim", () => { + it.skipIf(!hasSetsid).each(["SIGTERM", "SIGHUP"] as const)( + "keeps the AppImage mounted until the server exits after %s to the process group", + async (signal) => { + const { root, shim } = fakeAppImage(true, SLOW_SERVER); + const child = NodeChildProcess.spawn(shim, [], { + detached: true, + env: { PATH: process.env.PATH }, + stdio: ["pipe", "pipe", "ignore", "pipe"], + }); + let mounter: number | undefined; + try { + const stdout = lines(child.stdout!); + const events = lines(child.stdio[3] as NodeJS.ReadableStream); + const exited = new Promise((resolve) => child.on("close", resolve)); + await stdout.until((line) => line === "ready"); + mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8")); + + // Ctrl-C in a terminal, a closed SSH session, or a service manager signals the whole group. + process.kill(-child.pid!, signal); + // The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and + // HUP, so a mounter that also got the group signal unmounts before it answers this probe. + process.kill(mounter, "SIGWINCH"); + const mount = await events.until((line) => line === "mounted" || line === "unmounted"); + expect(mount).toBe("mounted"); + + await events.until((line) => line === "stopping"); + child.stdin!.end("go\n"); + await exited; + expect(events.seen.slice(-2)).toEqual(["stopped", "unmounted"]); + } finally { + for (const pid of [-child.pid!, mounter]) { + if (pid === undefined) continue; + try { + process.kill(pid, "SIGKILL"); + } catch {} + } + } + }, + ); + it("extracts the AppImage where it cannot be mounted", () => { const { shim } = fakeAppImage(false); const result = run(shim, ["--version"], { APPIMAGE_EXTRACT_AND_RUN: "1" }); @@ -73,6 +150,14 @@ describe("renderCliShim", () => { ); }); + // The server skips its compile cache only under APPIMAGE; each mount path is new. + it("tells the CLI it runs from the mounted AppImage", () => { + const { appImage, shim } = fakeAppImage(); + const result = run(shim, ["--version"]); + expect(result.status).toBe(3); + expect(result.stdout).toContain(`appimage=${appImage}`); + }); + it("keeps the install's T3 home under sudo, unless one is set", () => { const root = tempRoot(); writeExecutable(NodePath.join(root, "app"), REPORTER); diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 1b40050c31..3e3c41f4b6 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -96,12 +96,13 @@ export const renderCliShim = (input: { ...header, // Extract-and-run would make the runtime start the app instead of mounting it. "unset APPIMAGE_EXTRACT_AND_RUN", - // The runtime stays mounted until killed; traps unmount it because background jobs ignore Ctrl-C. + // Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the + // running server; the traps unmount it after. Without setsid the extract fallback runs. "work=$(mktemp -d) || exit 1", - '"$app" --appimage-mount >"$work/mount" 2>/dev/null &', + 'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &', "mounter=$!", `trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, - "trap 'exit 130' INT TERM", + "trap 'exit 130' INT TERM HUP", "mount=", 'while kill -0 "$mounter" 2>/dev/null; do', ' mount=$(head -n 1 "$work/mount")', @@ -114,6 +115,8 @@ export const renderCliShim = (input: { ' (cd "$work" && "$app" --appimage-extract >/dev/null) || { echo "Could not open $app." >&2; exit 1; }', ' mount="$work/squashfs-root"', "fi", + // The runtime sets this when it launches the app; the CLI skips its path-keyed compile cache on it. + 'export APPIMAGE="$app"', run("$mount"), "", ].join("\n"); diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index dfe75a5761..7e06f6a83b 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -99,7 +99,7 @@ const withStore = ( prefix: "t3-desktop-connection-catalog-test-", }); return yield* effect.pipe(Effect.provide(layerFor(baseDir, encryptionAvailable))); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)); describe("DesktopConnectionCatalogStore", () => { it.effect("persists and reads an encrypted connection catalog", () => @@ -277,6 +277,68 @@ describe("DesktopConnectionCatalogStore", () => { assert.notEqual(error.message, decryptError.message); yield* Ref.set(failDecrypt, false); assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}')); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + const emptyCatalog = + '{"schemaVersion":1,"targets":[],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}'; + const savedFilesHolding = Effect.fn(function* (stateDir: string, contents: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const kept: string[] = []; + for (const name of yield* fileSystem.readDirectory(stateDir)) { + const file = path.join(stateDir, name); + if ((yield* fileSystem.stat(file)).type !== "File") continue; + if ((yield* fileSystem.readFileString(file)) === contents) kept.push(name); + } + return kept; + }); + + it.effect("keeps a catalog this build cannot decode when the next save replaces it", () => + withStore( + Effect.gen(function* () { + const path = yield* Path.Path; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore; + const catalogPath = path.join(environment.stateDir, "connection-catalog.json"); + assert.isTrue( + yield* store.set( + '{"schemaVersion":1,"targets":[{"_tag":"FutureConnectionTarget","environmentId":"remote"}],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}', + ), + ); + const original = yield* fileSystem.readFileString(catalogPath); + + yield* store.get; + assert.isTrue(yield* store.set(emptyCatalog)); + + assert.isNotEmpty(yield* savedFilesHolding(environment.stateDir, original)); + }), + ), + ); + + it.effect("keeps a catalog that no longer decrypts when the next save replaces it", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-connection-catalog-test-", + }); + const failDecrypt = yield* Ref.make(false); + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide(layerFor(baseDir, true, failDecrypt)), + ); + const stateDir = path.join(baseDir, "userdata"); + assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}')); + const original = yield* fileSystem.readFileString( + path.join(stateDir, "connection-catalog.json"), + ); + + yield* Ref.set(failDecrypt, true); + yield* store.get.pipe(Effect.flip); + assert.isTrue(yield* store.set(emptyCatalog)); + + assert.isNotEmpty(yield* savedFilesHolding(stateDir, original)); }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); }); diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts index 90513e2cf1..982e55cffd 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts @@ -12,6 +12,7 @@ import { fromLenientJson } from "@t3tools/shared/schemaJson"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as Clock from "effect/Clock"; import * as Base64 from "effect/encoding/Base64"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -42,6 +43,9 @@ const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString( const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect( RuntimeConnectionCatalogDocumentJson, ); +const decodeRuntimeConnectionCatalogDocumentJson = Schema.decodeEffect( + RuntimeConnectionCatalogDocumentJson, +); const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([ "create-temporary-file-name", @@ -49,6 +53,7 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([ "create-directory", "write-temporary-file", "replace-catalog-file", + "keep-unreadable-catalog", ]); const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([ @@ -364,6 +369,57 @@ export const make = Effect.gen(function* () { ), ); + const decryptDocument = (document: EncryptedConnectionCatalogDocument) => + decodeSecretBytes(catalogPath, document.encryptedCatalog).pipe( + Effect.flatMap((encryptedCatalog) => + safeStorage.decryptString(encryptedCatalog).pipe( + Effect.mapError( + (cause) => + new DesktopConnectionCatalogStoreProtectionError({ + operation: "decrypt-catalog", + catalogPath, + cause, + }), + ), + ), + ), + ); + + // A catalog this build cannot decrypt or decode may still hold another build's saved + // environments and credentials, so a save copies it aside instead of destroying it. + const keepUnreadableCatalog = Effect.gen(function* () { + const readable = yield* readDocument(fileSystem, catalogPath).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(true), + onSome: (document) => + decryptDocument(document).pipe( + Effect.flatMap(decodeRuntimeConnectionCatalogDocumentJson), + Effect.as(true), + ), + }), + ), + Effect.orElseSucceed(() => false), + ); + if (readable) { + return; + } + const keptPath = `${catalogPath}.unreadable-${yield* Clock.currentTimeMillis}`; + yield* fileSystem.copyFile(catalogPath, keptPath).pipe( + Effect.mapError( + (cause) => + new DesktopConnectionCatalogStoreWriteError({ + operation: "keep-unreadable-catalog", + path: keptPath, + cause, + }), + ), + ); + yield* Effect.logWarning("Kept an unreadable connection catalog before replacing it.", { + keptPath, + }); + }); + const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* ( catalog: string, ) { @@ -439,26 +495,13 @@ export const make = Effect.gen(function* () { if (!(yield* encryptionAvailable)) { return Option.none(); } - const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe( - Effect.flatMap((encryptedCatalog) => - safeStorage.decryptString(encryptedCatalog).pipe( - Effect.mapError( - (cause) => - new DesktopConnectionCatalogStoreProtectionError({ - operation: "decrypt-catalog", - catalogPath, - cause, - }), - ), - ), - ), - ); - return Option.some(decrypted); + return Option.some(yield* decryptDocument(document.value)); }).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")), set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) { if (!(yield* encryptionAvailable)) { return false; } + yield* keepUnreadableCatalog; yield* writeCatalog(catalog); return true; }), diff --git a/apps/desktop/src/app/DesktopExitChildren.test.ts b/apps/desktop/src/app/DesktopExitChildren.test.ts new file mode 100644 index 0000000000..800a0f5bd4 --- /dev/null +++ b/apps/desktop/src/app/DesktopExitChildren.test.ts @@ -0,0 +1,62 @@ +// @effect-diagnostics nodeBuiltinImport:off - Spawns a real process tree for /proc. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import { assert, describe, it } from "@effect/vitest"; + +import { stopChildProcessesBeforeExit, stopZygotesBeforeExit } from "./DesktopExitChildren.ts"; + +const isRunning = (pid: number) => { + try { + const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8"); + return !"ZX".includes(stat.charAt(stat.lastIndexOf(")") + 2)); + } catch { + return false; + } +}; + +describe.runIf(NodeFS.existsSync("/proc/self/task"))("stopChildProcessesBeforeExit", () => { + it("terminates every child of the given process before returning", async () => { + const parent = NodeChildProcess.spawn( + "sh", + ["-c", "sleep 60 & echo $!; sleep 60 & echo $!; wait"], + { stdio: ["ignore", "pipe", "ignore"] }, + ); + try { + const childPids = await new Promise>((resolve) => { + let output = ""; + parent.stdout.on("data", (chunk: Buffer) => { + output += chunk.toString(); + const pids = output.split("\n").filter(Boolean).map(Number); + if (pids.length === 2) resolve(pids); + }); + }); + assert.isTrue(childPids.every(isRunning)); + + assert.deepStrictEqual(stopChildProcessesBeforeExit(parent.pid!), []); + + assert.isFalse(childPids.some(isRunning)); + } finally { + parent.kill("SIGKILL"); + } + }); + + it("kills zygote children before returning and leaves other helpers running", async () => { + const spawnTitled = async (title: string) => { + const child = NodeChildProcess.spawn("sleep", ["60"], { argv0: title, stdio: "ignore" }); + await new Promise((resolve) => child.once("spawn", resolve)); + return child; + }; + // Chromium rewrites a zygote's argv into one space-separated title. + const zygote = await spawnTitled("/opt/T3 Code/t3code --type=zygote --no-sandbox"); + const utility = await spawnTitled("/opt/T3 Code/t3code --type=utility"); + try { + stopZygotesBeforeExit(process.pid); + + assert.isFalse(isRunning(zygote.pid!)); + assert.isTrue(isRunning(utility.pid!)); + } finally { + zygote.kill("SIGKILL"); + utility.kill("SIGKILL"); + } + }); +}); diff --git a/apps/desktop/src/app/DesktopExitChildren.ts b/apps/desktop/src/app/DesktopExitChildren.ts new file mode 100644 index 0000000000..9426c1b4ff --- /dev/null +++ b/apps/desktop/src/app/DesktopExitChildren.ts @@ -0,0 +1,87 @@ +// @effect-diagnostics nodeBuiltinImport:off - Runs synchronously in the process "exit" event, where nothing async completes. +import * as NodeFS from "node:fs"; + +// Matches the backend's quit budget: SIGTERM, 5 s grace, SIGKILL, 1 s wait. +const TERMINATE_GRACE_MS = 5_000; +const KILL_WAIT_MS = 1_000; + +const readProc = (path: string): string | undefined => { + try { + return NodeFS.readFileSync(path, "utf8"); + } catch { + return undefined; + } +}; + +// Chromium launches helpers from its own threads, so each thread's children file is read. +const childPids = (pid: number): ReadonlyArray => { + let tasks: ReadonlyArray; + try { + tasks = NodeFS.readdirSync(`/proc/${pid}/task`); + } catch { + return []; + } + return tasks.flatMap((task) => + (readProc(`/proc/${pid}/task/${task}/children`) ?? "") + .split(" ") + .filter((value) => value.trim() !== "") + .map(Number), + ); +}; + +// A zygote rewrites its argv into one space-separated title. +const isZygote = (pid: number): boolean => + (readProc(`/proc/${pid}/cmdline`) ?? "") + .replaceAll("\0", " ") + .split(" ") + .includes("--type=zygote"); + +// A zombie has already released its memory mappings. +const isRunning = (pid: number): boolean => { + const stat = readProc(`/proc/${pid}/stat`); + if (stat === undefined) return false; + const state = stat.charAt(stat.lastIndexOf(")") + 2); + return state !== "Z" && state !== "X"; +}; + +const signal = (pids: ReadonlyArray, name: NodeJS.Signals) => { + for (const pid of pids) { + try { + process.kill(pid, name); + } catch {} + } +}; + +const waitUntilStopped = (pids: ReadonlyArray, maxMs: number): ReadonlyArray => { + const tick = new Int32Array(new SharedArrayBuffer(4)); + let running = pids.filter(isRunning); + for (let waited = 0; waited < maxMs && running.length > 0; waited += 10) { + Atomics.wait(tick, 0, 0, 10); + running = running.filter(isRunning); + } + return running; +}; + +/** + * Stops the main process's children while it is still alive. On an AppImage the image unmounts + * as soon as main exits, so children left running then die with SIGBUS. Linux only (/proc). + * Returns the pids that needed SIGKILL. + */ +export const stopChildProcessesBeforeExit = (pid: number): ReadonlyArray => { + const children = childPids(pid); + signal(children, "SIGTERM"); + const survivors = waitUntilStopped(children, TERMINATE_GRACE_MS); + signal(survivors, "SIGKILL"); + waitUntilStopped(survivors, KILL_WAIT_MS); + return survivors; +}; + +/** + * Chromium's zygotes exit only after main does, so on an AppImage they outlive the mount even on + * an orderly quit. Kills them while main still holds the image mounted. Linux only (/proc). + */ +export const stopZygotesBeforeExit = (pid: number): void => { + const zygotes = childPids(pid).filter(isZygote); + signal(zygotes, "SIGKILL"); + waitUntilStopped(zygotes, KILL_WAIT_MS); +}; diff --git a/apps/desktop/src/app/DesktopInstance.test.ts b/apps/desktop/src/app/DesktopInstance.test.ts index e1cbf38108..3e0bbaeb92 100644 --- a/apps/desktop/src/app/DesktopInstance.test.ts +++ b/apps/desktop/src/app/DesktopInstance.test.ts @@ -378,7 +378,7 @@ it.effect.each(["startup", "open-url", "early-second-instance"] as const)( ), Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks), ); - }).pipe(Effect.scoped), + }), ); it.effect("hands web and app links to the renderer and leaves other links alone", () => @@ -433,5 +433,5 @@ it.effect("hands web and app links to the renderer and leaves other links alone" }), ), ); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/desktop/src/app/DesktopInstance.ts b/apps/desktop/src/app/DesktopInstance.ts index 8fed72fb86..490e0b42ca 100644 --- a/apps/desktop/src/app/DesktopInstance.ts +++ b/apps/desktop/src/app/DesktopInstance.ts @@ -88,11 +88,12 @@ export const make = Effect.gen(function* () { Effect.gen(function* () { yield* electronApp.whenReady; yield* Effect.tryPromise({ - try: () => + try: (signal) => receiveCodexAuthCallback( request.authorizationUrl, (url) => runPromise(shell.openExternal(url)), (callbackUrl) => codexAuthDeliveryUrl(request, callbackUrl), + signal, ), catch: () => new CodexAuthCallbackError({ diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index ed570ba0cf..ea7dd077da 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -118,6 +118,7 @@ describe("DesktopLifecycle", () => { const layerEnvironment = Layer.succeed(DesktopEnvironment.DesktopEnvironment, { platform, isDevelopment: false, + appImagePath: Option.none(), } as DesktopEnvironment.DesktopEnvironment["Service"]); const layer = DesktopLifecycle.layer.pipe( diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts index 598bd5bc04..abad5956c8 100644 --- a/apps/desktop/src/app/DesktopLifecycle.ts +++ b/apps/desktop/src/app/DesktopLifecycle.ts @@ -16,6 +16,7 @@ import type * as Electron from "electron"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; +import { stopChildProcessesBeforeExit, stopZygotesBeforeExit } from "./DesktopExitChildren.ts"; import { makeComponentLogger } from "./DesktopObservability.ts"; import * as DesktopShutdown from "./DesktopShutdown.ts"; import * as ElectronApp from "../electron/ElectronApp.ts"; @@ -95,15 +96,18 @@ function addScopedListener>( target: unknown, eventName: string, listener: (...args: Args) => void, + options: { readonly prepend?: boolean } = {}, ): Effect.Effect { const eventTarget = target as { on: (eventName: string, listener: (...args: Array) => void) => unknown; + prependListener: (eventName: string, listener: (...args: Array) => void) => unknown; removeListener: (eventName: string, listener: (...args: Array) => void) => unknown; }; const untypedListener = listener as unknown as (...args: Array) => void; return Effect.acquireRelease( Effect.sync(() => { - eventTarget.on(eventName, untypedListener); + if (options.prepend) eventTarget.prependListener(eventName, untypedListener); + else eventTarget.on(eventName, untypedListener); }), () => Effect.sync(() => { @@ -334,6 +338,34 @@ export const make = DesktopLifecycle.of({ ); }); + // Electron can exit without before-quit, e.g. when the X11/Wayland connection drops. + // Children (the backend too) get SIGTERM while main still holds an AppImage mount open. + // Prepended so the record is buffered before the trace sink's own exit flush runs. + yield* addScopedListener( + process, + "exit", + (exitCode: number) => { + Effect.runSyncWith(context)( + Effect.gen(function* () { + const shutdown = yield* DesktopShutdown.DesktopShutdown; + // "allowed" without a finished shutdown is the updater's quit; its relaunched app is a child. + if (quit.phase === "allowed" || (yield* shutdown.isComplete)) return; + const attributes = { exitCode, quitPhase: quit.phase }; + yield* Effect.gen(function* () { + yield* logLifecycleError( + "desktop main process exiting before shutdown completed", + attributes, + ); + if (environment.platform !== "linux") return; + const killed = stopChildProcessesBeforeExit(process.pid); + yield* Effect.annotateCurrentSpan({ killedChildPids: killed }); + }).pipe(Effect.withSpan("desktop.lifecycle.exit", { attributes })); + }), + ); + }, + { prepend: true }, + ); + if (environment.platform !== "win32") { yield* addScopedListener(process, "SIGINT", () => { quitFromSignal("SIGINT", runEffect, quit); @@ -342,6 +374,13 @@ export const make = DesktopLifecycle.of({ quitFromSignal("SIGTERM", runEffect, quit); }); } + + // Unscoped: the app scope closes before Electron exits, and every exit path must run this. + if (environment.platform === "linux" && Option.isSome(environment.appImagePath)) { + yield* Effect.sync(() => { + process.once("exit", () => stopZygotesBeforeExit(process.pid)); + }); + } }).pipe(Effect.withSpan("desktop.lifecycle.register")), }); diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts index 16d2f8e241..8e8a2812ab 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts @@ -26,8 +26,11 @@ interface RecordedRegistration { readonly files: Array<{ readonly path: string; readonly content: string }>; readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray }>; readonly copies: Array<{ readonly source: string; readonly destination: string }>; + readonly icons: Array<{ readonly path: string; readonly bytes: ReadonlyArray }>; } +const ICON_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); + const makeEnvironment = (path: Path.Path, overrides: Record = {}) => DesktopEnvironment.DesktopEnvironment.of({ platform: "linux", @@ -69,7 +72,7 @@ const layerHandler = ( readonly writeError?: PlatformError.PlatformError; readonly existingEntry?: string; readonly iconSource?: string; - readonly iconCopyError?: PlatformError.PlatformError; + readonly iconWriteError?: PlatformError.PlatformError; } = {}, ) => DesktopLinuxUrlHandler.layer.pipe( @@ -92,10 +95,25 @@ const layerHandler = ( }), FileSystem.layerNoop({ copyFile: (source, destination) => - input.iconCopyError - ? Effect.fail(input.iconCopyError) + Effect.sync(() => { + recorded.copies.push({ source, destination }); + }), + readFile: (path) => + path === input.iconSource + ? Effect.succeed(ICON_BYTES) + : Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFile", + pathOrDescriptor: path, + }), + ), + writeFile: (path, bytes) => + input.iconWriteError + ? Effect.fail(input.iconWriteError) : Effect.sync(() => { - recorded.copies.push({ source, destination }); + recorded.icons.push({ path, bytes: [...bytes] }); }), readFileString: () => Effect.succeed(input.existingEntry ?? ""), makeDirectory: (path) => @@ -162,6 +180,7 @@ const emptyRecording = (): RecordedRegistration => ({ files: [], commands: [], copies: [], + icons: [], }); describe("DesktopLinuxUrlHandler", () => { @@ -185,6 +204,35 @@ describe("DesktopLinuxUrlHandler", () => { assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png"); }); + it.each([ + { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: true }, + { + from: "T3-Code-0.1.9-nightly.20261110.4449-arm64.AppImage", + to: "T3-Code-Nightly-arm64.AppImage", + restored: true, + }, + { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-0.1.9-x86_64.AppImage", restored: false }, + { from: "t3code.AppImage", to: "T3-Code-x86_64.AppImage", restored: false }, + { from: "T3-Code-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false }, + { from: "../T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false }, + ])("finds the launch path an update from $from to $to removed", ({ from, to, restored }) => { + for (const dir of ["/home/alice/Applications", '/home/al ice/My "100%" $Apps\\x']) { + const previous = dir + "/" + from; + const previousEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({ + displayName: "T3 Code (Beta)", + execTarget: previous, + scheme: "t3code", + }); + assert.equal( + DesktopLinuxUrlHandler.replacedVersionedAppImagePath({ + previousEntry, + appImagePath: dir + "/" + to, + }), + restored ? previous : null, + ); + } + }); + it.effect( "writes the handler entry, refreshes the MIME cache, and claims the scheme default", () => { @@ -290,22 +338,21 @@ describe("DesktopLinuxUrlHandler", () => { }), }); assert.deepEqual(recorded.files, []); - assert.deepEqual(recorded.copies, [ - { source: "/tmp/.mount_T3/resources/icon.png", destination: iconPath }, - ]); + assert.deepEqual(recorded.copies, [], "icon must not be copied out of the app bundle"); + assert.deepEqual(recorded.icons, [{ path: iconPath, bytes: [...ICON_BYTES] }]); assert.equal(recorded.commands.at(-1)?.command, "xdg-mime"); }); }); - it.effect("still registers the handler when copying its icon fails", () => { + it.effect("still registers the handler when installing its icon fails", () => { const recorded = emptyRecording(); return Effect.gen(function* () { yield* runRegister(recorded, { iconSource: "/tmp/.mount_T3/resources/icon.png", - iconCopyError: PlatformError.systemError({ + iconWriteError: PlatformError.systemError({ _tag: "PermissionDenied", module: "FileSystem", - method: "copyFile", + method: "writeFile", description: "read-only icon directory", }), }); @@ -584,7 +631,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { } assert.isFalse(yield* fileSystem.exists(fixture.cachePath)); assert.equal(iconCacheRuns(run), 0); - }).pipe(Effect.scoped), + }), ); it.effect("replaces same-length stale icons and refreshes an existing cache once", () => @@ -616,7 +663,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { run.commands.filter(({ command }) => command === "gtk-update-icon-cache"), [{ command: "gtk-update-icon-cache", args: ["-f", "-t", fixture.hicolorDir] }], ); - }).pipe(Effect.scoped), + }), ); it.effect("refreshes when this launch changed an icon even if the cache looks newer", () => @@ -637,7 +684,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { assert.isTrue(yield* fileSystem.exists(path.join(fixture.appsDir, "com.t3tools.T3Code.png"))); assert.equal(iconCacheRuns(run), 1); - }).pipe(Effect.scoped), + }), ); it.effect("retries a failed icon cache refresh on the next launch", () => @@ -660,7 +707,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { yield* registerWithRealFileSystem(recovering); yield* registerWithRealFileSystem(recovering); assert.equal(iconCacheRuns(recovering), 1); - }).pipe(Effect.scoped), + }), ); it.effect("still registers the handler when the theme icon install fails", () => @@ -684,6 +731,6 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { missingTool.commands.map(({ command }) => command), ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"], ); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts index cfa8498ae6..35fd46dd7a 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts @@ -96,6 +96,38 @@ export function renderUrlHandlerDesktopEntry(input: { ].join("\n"); } +function parseUrlHandlerExecTarget(entry: string): string | null { + const exec = /^Exec=(.*) %U$/mu.exec(entry)?.[1]; + if (exec === undefined) return null; + const unescaped = exec.replace(/\\([\\nrt])/gu, (_, char: string) => + char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? "\t" : char, + ); + const quoted = /^"(.*)"$/su.exec(unescaped)?.[1]; + return ( + quoted === undefined ? unescaped : quoted.replace(/\\([\\`$"])/gu, (_, char: string) => char) + ).replaceAll("%%", "%"); +} + +const APPIMAGE_NAME_VERSION = /\d+\.\d+\.\d+/u; + +// An updater from before version-free AppImage names deletes its own file and installs the update +// beside it under the new name. The previous launch's entry still names the path launchers use. +export function replacedVersionedAppImagePath(input: { + readonly previousEntry: string; + readonly appImagePath: string; +}): string | null { + const previous = parseUrlHandlerExecTarget(input.previousEntry); + if (previous === null) return null; + const previousName = previous.slice(previous.lastIndexOf("/") + 1); + const currentName = input.appImagePath.slice(input.appImagePath.lastIndexOf("/") + 1); + return previous.startsWith("/") && + previous.slice(0, -previousName.length) === input.appImagePath.slice(0, -currentName.length) && + APPIMAGE_NAME_VERSION.test(previousName) && + !APPIMAGE_NAME_VERSION.test(currentName) + ? previous + : null; +} + // Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive. const LINUX_THEME_ICON_SIZE = "256x256"; @@ -298,10 +330,11 @@ export const make = Effect.gen(function* () { if (Option.isNone(png)) return; // The AppImage mount is temporary; the chooser needs the icon after exit. yield* fileSystem.makeDirectory(iconsDir, { recursive: true }); - yield* fileSystem.copyFile(png.value, iconPath); + // Electron's copyFile from app.asar extracts to a temp file it never deletes. + yield* fileSystem.writeFile(iconPath, yield* fileSystem.readFile(png.value)); }).pipe( Effect.catch((error) => - logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }), + logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }), ), ); diff --git a/apps/desktop/src/app/DesktopObservability.test.ts b/apps/desktop/src/app/DesktopObservability.test.ts index ab8ea0b8e9..ceb29b149e 100644 --- a/apps/desktop/src/app/DesktopObservability.test.ts +++ b/apps/desktop/src/app/DesktopObservability.test.ts @@ -281,6 +281,27 @@ describe("DesktopObservability", () => { ), ); + it.effect("startup prunes only canonical rotation suffixes", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-rotating-prune-test-", + }); + const filePath = `${directory}/server-child.log`; + const retained = ["1", "3", "04", "4.0", "4e0", "0x4", "+4", "notes"]; + for (const suffix of [...retained, "4", "50"]) { + yield* fileSystem.writeFileString(`${filePath}.${suffix}`, suffix); + } + + yield* DesktopObservability.makeRotatingLogFileWriter({ filePath, maxFiles: 3 }); + + assert.deepEqual( + (yield* fileSystem.readDirectory(directory)).sort(), + retained.map((suffix) => `server-child.log.${suffix}`).sort(), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("stops every export when the OpenTelemetry SDK is disabled", () => { const requests: Array = []; return Effect.gen(function* () { diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts index 3cd3936a59..16192fff46 100644 --- a/apps/desktop/src/app/DesktopObservability.ts +++ b/apps/desktop/src/app/DesktopObservability.ts @@ -263,8 +263,10 @@ export const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")( const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])); for (const entry of entries) { if (!entry.startsWith(`${baseName}.`)) continue; - const suffix = Number(entry.slice(baseName.length + 1)); - if (!Number.isInteger(suffix) || suffix <= maxFiles) continue; + const suffixText = entry.slice(baseName.length + 1); + const suffix = Number(suffixText); + if (!Number.isInteger(suffix) || String(suffix) !== suffixText || suffix <= maxFiles) + continue; yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore); } }); @@ -654,6 +656,8 @@ const layerTelemetry = Layer.unwrap( maxFiles: DESKTOP_LOG_FILE_MAX_FILES, batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS, }); + // Unscoped: Electron can exit without closing the app scope, e.g. when the display drops. + process.once("exit", sink.flushSync); const delegate = endpoints.traces === undefined ? undefined diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index 3665281cf2..2b903f79b3 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -16,6 +16,7 @@ const { copyFileSyncMock, execFileSyncMock, readFileSyncMock, + symlinkSyncMock, } = vi.hoisted(() => ({ appendSwitchMock: vi.fn(), getSwitchValueMock: vi.fn(), @@ -27,6 +28,7 @@ const { copyFileSyncMock: vi.fn(), execFileSyncMock: vi.fn(), readFileSyncMock: vi.fn(), + symlinkSyncMock: vi.fn(), })); vi.mock("electron", () => ({ @@ -51,6 +53,7 @@ vi.mock("node:fs", () => ({ mkdirSync: mkdirSyncMock, writeFileSync: writeFileSyncMock, copyFileSync: copyFileSyncMock, + symlinkSync: symlinkSyncMock, })); vi.mock("node:child_process", () => ({ @@ -72,6 +75,7 @@ describe("DesktopPreReadyPlatform", () => { copyFileSyncMock.mockReset(); execFileSyncMock.mockReset(); readFileSyncMock.mockReset().mockReturnValue("{}"); + symlinkSyncMock.mockReset(); }); it.effect("persists Linux scaling synchronously across relaunches and settings rewrites", () => { @@ -129,14 +133,19 @@ describe("DesktopPreReadyPlatform", () => { let desktopName = "t3code.desktop"; let desktopEntry = previousEntry; let iconInstalled = false; - copyFileSyncMock.mockImplementation((_source: string, destination: string) => { - iconInstalled = destination === "/xdg/icons/com.t3tools.T3Code.desktop.png"; + const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png"; + const iconPath = "/xdg/icons/com.t3tools.T3Code.desktop.png"; + const iconBytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); + readFileSyncMock.mockImplementation((path: string) => { + if (path === iconSource) return iconBytes; + return "{}"; }); setDesktopNameMock.mockImplementation((name: string) => { desktopName = name; }); - writeFileSyncMock.mockImplementation((path: string, contents: string) => { - if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = contents; + writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => { + if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = String(contents); + if (path === iconPath) iconInstalled = Buffer.compare(Buffer.from(contents), iconBytes) === 0; }); return Effect.scoped( @@ -166,11 +175,57 @@ describe("DesktopPreReadyPlatform", () => { identity.desktopEntry ?? "", "Icon=/xdg/icons/com.t3tools.T3Code.desktop.png", ); - assert.isTrue(identity.iconInstalled); + assert.equal( + copyFileSyncMock.mock.calls.length, + 0, + "icon must not be copied out of the app bundle", + ); + assert.isTrue(identity.iconInstalled, "icon must be written from the bundled bytes"); }), ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); }); + it.effect.each([ + { relaunchedByUpdater: "true", restored: true }, + { relaunchedByUpdater: "", restored: false }, + ])( + "restores the versioned AppImage path an update removed (updater relaunch: $relaunchedByUpdater)", + ({ relaunchedByUpdater, restored }) => { + vi.stubEnv("VITE_DEV_SERVER_URL", ""); + getSwitchValueMock.mockReturnValue(""); + const entryPath = "/xdg/applications/com.t3tools.T3Code.desktop"; + const files = new Map([[entryPath, "Exec=/Applications/T3-Code-0.1.8-x86_64.AppImage %U\n"]]); + readFileSyncMock.mockImplementation((path: string) => files.get(path) ?? "{}"); + writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => { + files.set(path, String(contents)); + }); + + return Effect.scoped( + Effect.gen(function* () { + yield* Layer.build( + DesktopPreReadyPlatform.layer.pipe( + Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), + Layer.provide( + DesktopConfig.layerTest({ + XDG_DATA_HOME: "/xdg", + APPIMAGE: "/Applications/T3-Code-x86_64.AppImage", + APPIMAGE_SILENT_INSTALL: relaunchedByUpdater, + }), + ), + ), + ); + assert.deepEqual( + symlinkSyncMock.mock.calls, + restored + ? [["T3-Code-x86_64.AppImage", "/Applications/T3-Code-0.1.8-x86_64.AppImage"]] + : [], + ); + assert.include(files.get(entryPath), "Exec=/Applications/T3-Code-x86_64.AppImage %U"); + }), + ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); + }, + ); + it.effect("points the early portal entry at a configured distribution launcher", () => { vi.stubEnv("VITE_DEV_SERVER_URL", ""); getSwitchValueMock.mockReturnValue(""); diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index ff8c97b8f8..8ac4654636 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -14,7 +14,10 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts"; import { trimmedString } from "./DesktopConfig.ts"; import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts"; -import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts"; +import { + renderUrlHandlerDesktopEntry, + replacedVersionedAppImagePath, +} from "./DesktopLinuxUrlHandler.ts"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; export interface DesktopPreReadyCommandLineReader { @@ -56,6 +59,8 @@ const LinuxDesktopEntryConfig = Config.all({ xdgDataHome: trimmedString("XDG_DATA_HOME"), launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"), appImagePath: trimmedString("APPIMAGE"), + // electron-updater sets this on the AppImage it relaunches after installing an update. + relaunchedByUpdater: trimmedString("APPIMAGE_SILENT_INSTALL"), }); /** @public */ @@ -104,17 +109,38 @@ export const make = Effect.gen(function* () { if (iconPath !== undefined) { try { NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true }); - NodeFS.copyFileSync( - NodePath.posix.join( - Electron.app.getAppPath(), - "apps/desktop/prod-resources/icon.png", - ), + // Electron's copyFileSync from app.asar extracts to a temp file it never deletes. + NodeFS.writeFileSync( iconPath, + NodeFS.readFileSync( + NodePath.posix.join( + Electron.app.getAppPath(), + "apps/desktop/prod-resources/icon.png", + ), + ), ); } catch {} } + const desktopEntryPath = NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName); + const { appImagePath } = linuxDesktopEntryConfig; + if ( + Option.isSome(appImagePath) && + Option.isNone(linuxDesktopEntryConfig.launcherPath) && + Option.contains(linuxDesktopEntryConfig.relaunchedByUpdater, "true") + ) { + try { + const replacedPath = replacedVersionedAppImagePath({ + previousEntry: NodeFS.readFileSync(desktopEntryPath, "utf8"), + appImagePath: appImagePath.value, + }); + // Relative, so the pair survives a moved folder; symlink never overwrites a file. + if (replacedPath !== null) { + NodeFS.symlinkSync(NodePath.posix.basename(appImagePath.value), replacedPath); + } + } catch {} + } NodeFS.writeFileSync( - NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName), + desktopEntryPath, renderUrlHandlerDesktopEntry({ displayName: resolveDesktopAppBranding({ isDevelopment: linux.isDevelopment, diff --git a/apps/desktop/src/app/DesktopPrimaryPaste.test.ts b/apps/desktop/src/app/DesktopPrimaryPaste.test.ts new file mode 100644 index 0000000000..3bf5c2567d --- /dev/null +++ b/apps/desktop/src/app/DesktopPrimaryPaste.test.ts @@ -0,0 +1,71 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as PlatformError from "effect/PlatformError"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import { readGtkPrimaryPasteEnabled } from "./DesktopPrimaryPaste.ts"; + +const encoder = new TextEncoder(); + +const spawnerWithStdout = (stdout: Stream.Stream) => + ChildProcessSpawner.make(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ); + +const read = (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => + readGtkPrimaryPasteEnabled.pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + +describe("readGtkPrimaryPasteEnabled", () => { + it.effect("is disabled only when gsettings prints false", () => + Effect.gen(function* () { + assert.isFalse(yield* read(spawnerWithStdout(Stream.make(encoder.encode("false\n"))))); + assert.isTrue(yield* read(spawnerWithStdout(Stream.make(encoder.encode("true\n"))))); + // A missing schema prints nothing on stdout. + assert.isTrue(yield* read(spawnerWithStdout(Stream.empty))); + }), + ); + + it.effect("stays enabled when gsettings cannot run", () => + Effect.gen(function* () { + const missing = ChildProcessSpawner.make(() => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "ChildProcess", + method: "spawn", + description: "gsettings not found", + }), + ), + ); + assert.isTrue(yield* read(missing)); + }), + ); + + it.effect("stays enabled when gsettings hangs", () => + Effect.gen(function* () { + const fiber = yield* read(spawnerWithStdout(Stream.never)).pipe(Effect.forkChild); + yield* TestClock.adjust("2 seconds"); + assert.isTrue(yield* Fiber.join(fiber)); + }), + ); +}); diff --git a/apps/desktop/src/app/DesktopPrimaryPaste.ts b/apps/desktop/src/app/DesktopPrimaryPaste.ts new file mode 100644 index 0000000000..0ae8f0d61f --- /dev/null +++ b/apps/desktop/src/app/DesktopPrimaryPaste.ts @@ -0,0 +1,39 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +export class DesktopPrimaryPaste extends Context.Service< + DesktopPrimaryPaste, + { + readonly enabled: boolean; + } +>()("@t3tools/desktop/app/DesktopPrimaryPaste") {} + +// Chrome applies gtk-enable-primary-paste from chrome/, which Electron does not include. +export const readGtkPrimaryPasteEnabled = Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner.string( + ChildProcess.make( + "gsettings", + ["get", "org.gnome.desktop.interface", "gtk-enable-primary-paste"], + { stdin: "ignore", stderr: "ignore" }, + ), + ); + return output.trim() !== "false"; +}).pipe( + Effect.timeout("2 seconds"), + Effect.orElseSucceed(() => true), +); + +const make = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + // Resolved before any window exists so the first preload never sees a provisional value. + const enabled = + platform === "darwin" || platform === "win32" ? true : yield* readGtkPrimaryPasteEnabled; + return DesktopPrimaryPaste.of({ enabled }); +}); + +export const layer = Layer.effect(DesktopPrimaryPaste, make); diff --git a/apps/desktop/src/app/DesktopStartupRecovery.test.ts b/apps/desktop/src/app/DesktopStartupRecovery.test.ts index ae690add75..0b594810a8 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.test.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.test.ts @@ -200,3 +200,74 @@ it.effect.each([ }), ).pipe(Effect.provide(DesktopState.layer)), ); + +it.effect("installs the build the update action downloaded, not the one it offered", () => + Effect.scoped( + Effect.gen(function* () { + const installed = yield* Deferred.make(); + const shown = yield* Deferred.make(); + let navigate: ((event: { preventDefault: () => void }, url: string) => void) | undefined; + const recovery = { + isDestroyed: () => false, + loadURL: () => Promise.resolve(), + once: () => {}, + webContents: { + setWindowOpenHandler: () => {}, + on: (_event: string, listener: typeof navigate) => { + navigate = listener; + Deferred.doneUnsafe(shown, Effect.void); + }, + }, + } as unknown as Electron.BrowserWindow; + const offered = updateState({ status: "available", availableVersion: "0.1.4" }); + const state = yield* DesktopState.DesktopState; + yield* listen.pipe( + Effect.provide( + Layer.mergeAll( + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + appVersion: "0.1.3", + stateDir: "/task/state", + logDir: "/task/logs", + path: { join: (...parts: string[]) => parts.join("/") }, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Layer.succeed(ElectronApp.ElectronApp, { + on: () => Effect.void, + } as unknown as ElectronApp.ElectronApp["Service"]), + Layer.succeed( + ElectronShell.ElectronShell, + {} as ElectronShell.ElectronShell["Service"], + ), + Layer.succeed(ElectronTheme.ElectronTheme, { + shouldUseDarkColors: Effect.succeed(false), + } as ElectronTheme.ElectronTheme["Service"]), + Layer.succeed(ElectronWindow.ElectronWindow, { + main: Effect.succeedNone, + create: () => Effect.succeed(recovery), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + Layer.succeed(DesktopUpdates.DesktopUpdates, { + subscribe: Effect.succeed({ latest: offered, changes: Stream.empty }), + check: () => Effect.void, + getState: Effect.succeed(offered), + // A release published since the offer: the download fetches it instead. + download: Effect.succeed({ + accepted: true, + completed: true, + state: updateState({ status: "downloaded", downloadedVersion: "0.1.5" }), + }), + installPrepared: (version: string) => Deferred.succeed(installed, version), + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + ), + ), + ); + yield* SubscriptionRef.set(state.primaryBackendStartup, { + _tag: "Failing", + reason: "Server failed before readiness", + managedPolicy: false, + output: "Failure details", + }); + yield* Deferred.await(shown); + navigate!({ preventDefault: () => {} }, "https://startup-recovery.invalid/update"); + expect(yield* Deferred.await(installed)).toBe("0.1.5"); + }), + ).pipe(Effect.provide(DesktopState.layer)), +); diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts index 91ddd76fba..ced12899c6 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.ts @@ -185,13 +185,15 @@ export const listen: Effect.Effect< switch (action) { case "update": { if (current._tag !== "Update") return; - const state = yield* updates.getState; - if (state.downloadedVersion === null) { + let { downloadedVersion } = yield* updates.getState; + if (downloadedVersion === null) { + // The download re-checks first, so it can fetch a newer build than the one offered. const download = yield* updates.download; if (!download.completed) return; + downloadedVersion = download.state.downloadedVersion; } - // Waits for a running background check; plain install would refuse. - yield* updates.installPrepared(current.version); + if (downloadedVersion === null) return; + yield* updates.installPrepared(downloadedVersion); return; } case "copy": { diff --git a/apps/desktop/src/app/DesktopState.ts b/apps/desktop/src/app/DesktopState.ts index 3452fd13c0..f869fd335a 100644 --- a/apps/desktop/src/app/DesktopState.ts +++ b/apps/desktop/src/app/DesktopState.ts @@ -17,6 +17,8 @@ export class DesktopState extends Context.Service< { readonly backendReady: Ref.Ref; readonly quitting: Ref.Ref; + // Set by DesktopUpdates.configure, which runs before the first backend start. + readonly canInstallUpdates: Ref.Ref; readonly primaryBackendStartup: SubscriptionRef.SubscriptionRef; } >()("@t3tools/desktop/app/DesktopState") {} @@ -24,6 +26,7 @@ export class DesktopState extends Context.Service< const make = Effect.all({ backendReady: Ref.make(false), quitting: Ref.make(false), + canInstallUpdates: Ref.make(false), primaryBackendStartup: SubscriptionRef.make({ _tag: "Starting" }), }); diff --git a/apps/desktop/src/app/stdioErrors.test.ts b/apps/desktop/src/app/stdioErrors.test.ts new file mode 100644 index 0000000000..ccfa3ed951 --- /dev/null +++ b/apps/desktop/src/app/stdioErrors.test.ts @@ -0,0 +1,22 @@ +import * as NodeOS from "node:os"; +import { assert, it } from "vite-plus/test"; + +import { handleStdioError } from "./stdioErrors.ts"; + +const errorWithCode = (code: string, errno?: number) => + Object.assign(new Error(code), { code, errno }); +const EDQUOT_ERRNO = NodeOS.constants.errno.EDQUOT; + +it.each(["EPIPE", "ENOSPC"])("ignores %s on console output", (code) => { + assert.doesNotThrow(() => handleStdioError(errorWithCode(code))); +}); + +// Node reports EDQUOT as UNKNOWN because libuv has no name for it. +it.skipIf(EDQUOT_ERRNO === undefined)("ignores EDQUOT on console output", () => { + assert.doesNotThrow(() => handleStdioError(errorWithCode("UNKNOWN", -(EDQUOT_ERRNO ?? 0)))); +}); + +it("rethrows other console output errors", () => { + assert.throws(() => handleStdioError(errorWithCode("EIO")), "EIO"); + assert.throws(() => handleStdioError(errorWithCode("UNKNOWN", -5)), "UNKNOWN"); +}); diff --git a/apps/desktop/src/app/stdioErrors.ts b/apps/desktop/src/app/stdioErrors.ts new file mode 100644 index 0000000000..b23c0e89e7 --- /dev/null +++ b/apps/desktop/src/app/stdioErrors.ts @@ -0,0 +1,13 @@ +import * as NodeOS from "node:os"; + +// libuv has no name for EDQUOT, so Node reports it as code "UNKNOWN" with the raw errno. +const EDQUOT_ERRNO = NodeOS.constants.errno.EDQUOT; + +// Redirected console output can fail when its log volume is full. +export function handleStdioError(error: unknown): void { + if (typeof error === "object" && error !== null) { + if ("code" in error && (error.code === "EPIPE" || error.code === "ENOSPC")) return; + if (EDQUOT_ERRNO !== undefined && "errno" in error && error.errno === -EDQUOT_ERRNO) return; + } + throw error; +} diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 1b41e7c343..b425bd0004 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -21,6 +21,7 @@ import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopServerExposure from "./DesktopServerExposure.ts"; +import * as DesktopState from "../app/DesktopState.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts"; @@ -34,7 +35,10 @@ const layerShellEnvironment = (prepared = true) => }); const layerBackendConfiguration = (prepared = true) => - DesktopBackendConfiguration.layer.pipe(Layer.provide(layerShellEnvironment(prepared))); + DesktopBackendConfiguration.layer.pipe( + Layer.provide(layerShellEnvironment(prepared)), + Layer.provide(DesktopState.layer), + ); const layerServerExposure = Layer.succeed(DesktopServerExposure.DesktopServerExposure, { getState: Effect.die("unexpected getState"), @@ -371,7 +375,7 @@ describe("DesktopBackendConfiguration", () => { ); assert.equal(config.runningDistro, "Ubuntu"); - assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]); + assert.deepEqual(config.args.slice(0, 5), ["-d", "Ubuntu", "--cd", "~", "--exec"]); assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]); assert.isTrue(Option.isNone(config.preflightFailure)); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), @@ -383,7 +387,7 @@ describe("DesktopBackendConfiguration", () => { runtimeId: string; sha256: string; }> = []; - const observedProbeRoots: string[] = []; + let probeCount = 0; let legacyCleanupCount = 0; const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64"; const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin"; @@ -404,8 +408,8 @@ describe("DesktopBackendConfiguration", () => { }); return { ok: true, linuxAppRoot }; }, - probeRuntime: (_distro, root) => { - observedProbeRoots.push(root); + probeRuntime: () => { + probeCount += 1; return { ok: true, resolvedPath }; }, ensureNodePty: () => { @@ -426,7 +430,7 @@ describe("DesktopBackendConfiguration", () => { sha256: archiveHash, }, ]); - assert.deepEqual(observedProbeRoots, [linuxAppRoot]); + assert.equal(probeCount, 1); assert.equal( config.entryPath, path.join(baseDir, "server.asar/apps/server/dist/bin.mjs"), @@ -434,6 +438,8 @@ describe("DesktopBackendConfiguration", () => { assert.deepEqual(config.args, [ "-d", "Ubuntu", + "--cd", + "~", "--exec", "env", `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`, @@ -519,10 +525,10 @@ describe("DesktopBackendConfiguration", () => { ); }); - it.effect("resolveWsl retires a staged runtime whose executable does not start", () => { + it.effect("resolveWsl retires a staged runtime whose launch probe fails", () => { const archiveHash = "c".repeat(64); const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`; - const observedProbeRoots: string[] = []; + let probeCount = 0; const observedNodePtyRoots: string[] = []; const invalidatedRuntimeIds: string[] = []; return withPackagedWslHarness( @@ -534,9 +540,9 @@ describe("DesktopBackendConfiguration", () => { Effect.sync(() => { invalidatedRuntimeIds.push(runtimeId); }), - probeRuntime: (_distro, root) => { - observedProbeRoots.push(root); - return { ok: false, reason: `${root}/t3 --version failed (exit 127)` }; + probeRuntime: () => { + probeCount += 1; + return { ok: false, reason: "WSL login-shell PATH could not be resolved" }; }, ensureNodePty: (_distro, root) => { observedNodePtyRoots.push(root); @@ -549,7 +555,7 @@ describe("DesktopBackendConfiguration", () => { const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" }); - assert.deepEqual(observedProbeRoots, [stagedAppRoot]); + assert.equal(probeCount, 1); assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]); assert.include(config.args, "/usr/bin/node"); assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`); @@ -574,7 +580,7 @@ describe("DesktopBackendConfiguration", () => { Effect.sync(() => { invalidatedRuntimeIds.push(runtimeId); }), - probeRuntime: () => ({ ok: false, reason: "t3 --version failed (exit 1)" }), + probeRuntime: () => ({ ok: false, reason: "WSL login-shell PATH could not be resolved" }), ensureNodePty: () => ({ ok: false, reason: "WSL backend preflight timed out while probing for Node.js.", @@ -649,6 +655,8 @@ describe("DesktopBackendConfiguration", () => { assert.deepEqual(config.args, [ "-d", "Ubuntu", + "--cd", + "~", "--exec", "env", "PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin", @@ -681,6 +689,43 @@ describe("DesktopBackendConfiguration", () => { ), ); + it.effect("gives the Windows and WSL backends one host scope that survives a restart", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-backend-config-test-", + }); + const launch = Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const primary = yield* configuration.resolvePrimary; + const wsl = yield* configuration.resolveWsl({ port: 5050, distro: null }); + assert.equal(wsl.env.T3CODE_DESKTOP_HOST_SCOPE, primary.env.T3CODE_DESKTOP_HOST_SCOPE); + assert.include((wsl.env.WSLENV ?? "").split(":"), "T3CODE_DESKTOP_HOST_SCOPE"); + return primary.env.T3CODE_DESKTOP_HOST_SCOPE; + }).pipe( + Effect.provide( + layerBackendConfiguration().pipe( + Layer.provideMerge(layerServerExposure), + Layer.provideMerge(DesktopAppSettings.layerTest()), + Layer.provideMerge(DesktopWslServerTree.layerTest()), + Layer.provideMerge( + DesktopWslEnvironment.layerTest({ + isAvailable: true, + windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), + getDistroIp: () => Option.some("172.27.0.99"), + }), + ), + Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), + ), + ), + ); + + const first = yield* launch; + assert.match(first ?? "", /^[0-9a-f]{32}$/); + assert.equal(yield* launch, first); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("resolveWsl carries the kill switch and resource attributes into the distro", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -743,7 +788,7 @@ describe("DesktopBackendConfiguration", () => { assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf"); assert.equal( config.env.WSLENV, - "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL", + "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:T3CODE_DESKTOP_HOST_SCOPE:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL", ); }).pipe( Effect.provide( diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 83f0440ccc..b4ccc6344f 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -16,6 +16,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as SynchronizedRef from "effect/SynchronizedRef"; @@ -24,6 +25,7 @@ import serverPackageJson from "../../../server/package.json" with { type: "json" import * as DesktopBackendManager from "./DesktopBackendManager.ts"; import * as DesktopCliShim from "../app/DesktopCliShim.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import * as DesktopState from "../app/DesktopState.ts"; import * as DesktopServerExposure from "./DesktopServerExposure.ts"; import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; @@ -244,8 +246,38 @@ interface SharedBootstrapInput { readonly bootstrapToken: string; readonly bootstrapSecret: string; readonly observabilitySettings: BackendObservabilitySettings; + readonly hostScope: string; } +// Matches the server's DESKTOP_HOST_SCOPE_ENV. +const DESKTOP_HOST_SCOPE_ENV = "T3CODE_DESKTOP_HOST_SCOPE"; +const HOST_SCOPE_FILE_NAME = "desktop-host-scope"; +const HOST_SCOPE_PATTERN = /^[0-9a-f]{32}$/; + +/** + * Not a credential: it only tells this install's Windows and WSL servers that + * they run on one machine, so usage both read from one Windows directory counts + * once. Persisted so summaries from earlier launches still match. + */ +const readOrCreateHostScope = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const random = yield* SecureRandom.SecureRandom; + const scopePath = environment.path.join(environment.stateDir, HOST_SCOPE_FILE_NAME); + const existing = (yield* fileSystem + .readFileString(scopePath) + .pipe(Effect.orElseSucceed(() => ""))).trim(); + if (HOST_SCOPE_PATTERN.test(existing)) return existing; + const scope = Hex.encode(yield* random.randomBytes(16).pipe(Effect.orDie)); + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }).pipe( + Effect.andThen(fileSystem.writeFileString(scopePath, scope)), + Effect.catch((cause) => + Effect.logWarning("Could not persist the desktop host scope.", { cause }), + ), + ); + return scope; +}); + type WslPreflightRuntime = | { readonly kind: "executable"; @@ -395,7 +427,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); if (runtime.ok) { // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them. - const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot); + const stagedProbe = yield* wslEnv.probeRuntime(runningDistro); if (stagedProbe.ok) { yield* wslServerTree.cleanupLegacy; return { @@ -408,7 +440,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f } as const; } yield* Effect.logWarning( - "The staged WSL runtime did not start; retrying from the mounted server tree.", + "The staged WSL runtime probe failed; retrying from the mounted server tree.", { reason: stagedProbe.reason }, ); stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason }; @@ -491,6 +523,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv readonly resourceMonitorPath: Option.Option; readonly cliPath: Option.Option; readonly shellEnvironmentPrepared: boolean; + readonly desktopAppUpdate: boolean; }, ): Effect.fn.Return< DesktopBackendManager.DesktopBackendStartConfig, @@ -514,6 +547,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv tailscaleServePort: backendExposure.tailscaleServePort, desktopTelemetryFd: 4, desktopTelemetryControlFd: 5, + desktopAppUpdate: input.desktopAppUpdate, desktopBrowserFd: 6, desktopBrowserControlFd: 7, ...Option.match(input.resourceMonitorPath, { @@ -539,6 +573,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv ELECTRON_RUN_AS_NODE: "1", T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1", T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath), + [DESKTOP_HOST_SCOPE_ENV]: input.hostScope, }, extendEnv: true, bootstrap, @@ -635,8 +670,8 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`); const distroArgs = distroForConfig ? ["-d", distroForConfig] : []; - const forwardedEnv: Record = {}; - const forwardedEnvNames: string[] = []; + const forwardedEnv: Record = { [DESKTOP_HOST_SCOPE_ENV]: input.hostScope }; + const forwardedEnvNames: string[] = [DESKTOP_HOST_SCOPE_ENV]; for (const name of WSL_FORWARDED_ENV_NAMES) { const value = env[name]; if (value !== undefined && value.length > 0) { @@ -707,6 +742,9 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl ...baseConfig, args: [ ...distroArgs, + // WSL otherwise inherits the Windows-mounted desktop working directory. + "--cd", + "~", "--exec", "env", `PATH=${launchPath}`, @@ -729,10 +767,18 @@ export const make = Effect.gen(function* () { const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree; const settings = yield* DesktopAppSettings.DesktopAppSettings; + const desktopState = yield* DesktopState.DesktopState; const mac = yield* Mac.Mac; const random = yield* SecureRandom.SecureRandom; // Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets. const secretRef = yield* SynchronizedRef.make(Option.none()); + const hostScope = yield* Effect.cached( + readOrCreateHostScope.pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), + Effect.provideService(SecureRandom.SecureRandom, random), + ), + ); const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) => Option.match(current, { onSome: (secret) => Effect.succeed([secret, current] as const), @@ -760,6 +806,7 @@ export const make = Effect.gen(function* () { bootstrapToken, bootstrapSecret, observabilitySettings, + hostScope: yield* hostScope, } satisfies SharedBootstrapInput; }); @@ -796,6 +843,7 @@ export const make = Effect.gen(function* () { resourceMonitorPath, cliPath, shellEnvironmentPrepared, + desktopAppUpdate: yield* Ref.get(desktopState.canInstallUpdates), }).pipe( Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure), diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index 3126d12a2e..ff5b7b8c08 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -5,7 +5,13 @@ import { type DesktopBackendBootstrap as DesktopBackendBootstrapValue, DesktopTelemetryControlMessage, } from "@t3tools/contracts"; +import { + DATABASE_MIGRATION_PROGRESS_MESSAGE, + DATABASE_MIGRATIONS_FINISHED_MESSAGE, + DATABASE_MIGRATIONS_STARTED_MESSAGE, +} from "@t3tools/shared/databaseMigrationLog"; import { assert, describe, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -194,129 +200,162 @@ function makeTestInstance(input: MakeInstanceInput) { describe("DesktopBackendManager", () => { it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () => - Effect.scoped( - Effect.gen(function* () { - const probe = yield* Deferred.make(); - const ready = yield* Deferred.make(); - const exit = yield* Deferred.make(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.acquireRelease( - Effect.succeed( - makeProcess({ - exitCode: Deferred.await(exit), - kill: () => - Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), - }), - ), - () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), + Effect.gen(function* () { + const probe = yield* Deferred.make(); + const ready = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.acquireRelease( + Effect.succeed( + makeProcess({ + exitCode: Deferred.await(exit), + kill: () => + Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), + }), ), + () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), ), ), - httpClientLayer: Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => - Deferred.succeed(probe, undefined).pipe( - Effect.andThen(Deferred.await(ready)), - Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))), - ), + ), + httpClientLayer: Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Deferred.succeed(probe, undefined).pipe( + Effect.andThen(Deferred.await(ready)), + Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))), ), ), - }); - yield* instance.start; - yield* Deferred.await(probe); - const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild); - yield* Deferred.succeed(ready, undefined); - assert.isTrue(yield* Fiber.join(waiter)); - yield* instance.stop(); - assert.isFalse(yield* instance.waitForReady(Duration.seconds(15))); - }), - ), + ), + }); + yield* instance.start; + yield* Deferred.await(probe); + const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild); + yield* Deferred.succeed(ready, undefined); + assert.isTrue(yield* Fiber.join(waiter)); + yield* instance.stop(); + assert.isFalse(yield* instance.waitForReady(Duration.seconds(15))); + }), ); - it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () => - Effect.scoped( - Effect.gen(function* () { - let spawnedCommand: ChildProcess.Command | undefined; - let bootstrapJson = ""; - let telemetryJson = ""; - let readyCount = 0; - const ready = yield* Deferred.make(); - const exited = yield* Queue.unbounded(); - - const layerSpawner = Layer.succeed( + it.effect("notices a WSL backend soon after it listens despite slow refused connects", () => + Effect.gen(function* () { + const ready = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + config: { ...baseConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") }, + onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid), + spawnerLayer: Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make((command) => - Effect.gen(function* () { - spawnedCommand = command; - if (command._tag === "StandardCommand") { - const fd3 = command.options.additionalFds?.fd3; - 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); - } + ChildProcessSpawner.make(() => + Effect.acquireRelease( + Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })), + () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), + ), + ), + ), + // Before the server listens at 300 ms, each refused connect takes a second to fail. + httpClientLayer: layerHttpClient((request) => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + now < 300 + ? Effect.sleep(Duration.seconds(1)).pipe( + Effect.as(responseForRequest(request, 503)), + ) + : Effect.succeed(responseForRequest(request, 200)), + ), + ), + ), + }); + yield* instance.start; + yield* TestClock.adjust(Duration.millis(600)); + + assert.isTrue(yield* Deferred.isDone(ready)); + yield* instance.stop(); + }), + ); + + it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () => + Effect.gen(function* () { + let spawnedCommand: ChildProcess.Command | undefined; + let bootstrapJson = ""; + let telemetryJson = ""; + let readyCount = 0; + const ready = yield* Deferred.make(); + const exited = yield* Queue.unbounded(); + + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.gen(function* () { + spawnedCommand = command; + if (command._tag === "StandardCommand") { + const fd3 = command.options.additionalFds?.fd3; + 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({ - exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }); - }), - ), - ); + return makeProcess({ + exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + }); + }), + ), + ); - const instance = yield* makeTestInstance({ - config: { - ...baseConfig, - bootstrap: configWithObservability, - }, - spawnerLayer: layerSpawner, - 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), - }, - }); + const instance = yield* makeTestInstance({ + config: { + ...baseConfig, + bootstrap: configWithObservability, + }, + spawnerLayer: layerSpawner, + 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), + }, + }); - yield* instance.start; - yield* Queue.take(exited); - - assert.equal(readyCount, 1); - assert.isDefined(spawnedCommand); - if (spawnedCommand._tag !== "StandardCommand") { - throw new Error("Expected backend to spawn a standard command."); - } - - assert.equal(spawnedCommand.command, "/electron"); - assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]); - assert.equal(spawnedCommand.options.cwd, "/server"); - assert.equal(spawnedCommand.options.extendEnv, true); - assert.equal(spawnedCommand.options.stdout, "pipe"); - 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)), - 5_000, - ); - - assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability); - assert.equal( - telemetryJson, - '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n', - ); - }), - ), + yield* instance.start; + yield* Queue.take(exited); + + assert.equal(readyCount, 1); + assert.isDefined(spawnedCommand); + if (spawnedCommand._tag !== "StandardCommand") { + throw new Error("Expected backend to spawn a standard command."); + } + + assert.equal(spawnedCommand.command, "/electron"); + assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]); + assert.equal(spawnedCommand.options.cwd, "/server"); + assert.equal(spawnedCommand.options.extendEnv, true); + assert.equal(spawnedCommand.options.stdout, "pipe"); + 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)), + 5_000, + ); + + assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability); + assert.equal( + telemetryJson, + '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n', + ); + }), ); it.effect("reports a SIGKILL exit without an exit code", () => @@ -344,285 +383,308 @@ describe("DesktopBackendManager", () => { ); it.effect("reports child exit before waiting for trailing output to drain", () => - Effect.scoped( - Effect.gen(function* () { - const exitObserved = yield* Deferred.make(); - const finishOutputDrain = yield* Deferred.make(); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - stdout: Stream.fromEffect( - Deferred.await(finishOutputDrain).pipe( - Effect.as(new TextEncoder().encode("trailing output\n")), - ), + Effect.gen(function* () { + const exitObserved = yield* Deferred.make(); + const finishOutputDrain = yield* Deferred.make(); + const layerSpawner = 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)), - }), - ), + ), + 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(layerSpawner, layerHealthyHttpClient)), - 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); - }), - ), + const runFiber = yield* DesktopBackendManager.runBackendProcess({ + ...baseConfig, + desktopTelemetryStream: Stream.empty, + onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid), + }).pipe(Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), 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", () => + it.effect("becomes ready from the server ready line while HTTP probes stall", () => Effect.scoped( Effect.gen(function* () { - const handled = yield* Deferred.make(); - const controlMessage = encodeDesktopTelemetryControl({ - version: 1, - type: "setDiagnosticsDemand", - enabled: true, - }); - const layerSpawner = 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 probeStarted = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const readyLine = encodeDesktopTelemetryControl({ version: 1, type: "serverReady" }); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + getOutputFd: (fd) => + fd === 5 + ? Stream.fromEffect(Deferred.await(probeStarted)).pipe( + Stream.flatMap(() => Stream.encodeText(Stream.make(`${readyLine}\n`))), + ) + : Stream.empty, + exitCode: Deferred.await(exit), + kill: () => + Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), + }), + ), ), ), - ); - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - desktopTelemetryPublisher: { - handleControlForSource: (_sourceId, message) => - message.type === "setDiagnosticsDemand" - ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid) - : Effect.void, - }, + httpClientLayer: layerHttpClient(() => + Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)), + ), }); yield* instance.start; - assert.isTrue(yield* Deferred.await(handled)); + assert.isTrue(yield* instance.waitForReady(Duration.seconds(15))); }), ), ); + it.effect("continues routing desktop telemetry control messages after an invalid line", () => + Effect.gen(function* () { + const handled = yield* Deferred.make(); + const controlMessage = encodeDesktopTelemetryControl({ + version: 1, + type: "setDiagnosticsDemand", + enabled: true, + }); + const layerSpawner = 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: layerSpawner, + desktopTelemetryPublisher: { + handleControlForSource: (_sourceId, 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("stops the scoped process with output still pending", () => - Effect.scoped( - Effect.gen(function* () { - let startCount = 0; - let closedCount = 0; - const closed = yield* Deferred.make(); - const teardownStarted = yield* Deferred.make(); - const finishTeardown = yield* Deferred.make(); - const startedPids = yield* Queue.unbounded(); - const ready = yield* Deferred.make(); - const backendReadyFlag = yield* Ref.make(false); - let shutdownCount = 0; - let persistedFailureCount = 0; - let discardedSessionCount = 0; - let removedTelemetrySources = 0; - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - 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, - ); + Effect.gen(function* () { + let startCount = 0; + let closedCount = 0; + const closed = yield* Deferred.make(); + const teardownStarted = yield* Deferred.make(); + const finishTeardown = yield* Deferred.make(); + const startedPids = yield* Queue.unbounded(); + const ready = yield* Deferred.make(); + const backendReadyFlag = yield* Ref.make(false); + let shutdownCount = 0; + let persistedFailureCount = 0; + let discardedSessionCount = 0; + let removedTelemetrySources = 0; - yield* Scope.addFinalizer(scope, close); + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + 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, + ); + + yield* Scope.addFinalizer(scope, close); + + return makeProcess({ + stdout: Stream.never, + exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + kill: () => close, + }); + }), + ), + ); - return makeProcess({ - stdout: Stream.never, - exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - kill: () => close, - }); + const instance = yield* makeTestInstance({ + spawnerLayer: layerSpawner, + onReady: Ref.set(backendReadyFlag, true).pipe( + Effect.andThen(Deferred.succeed(ready, void 0)), + Effect.asVoid, + ), + onShutdown: Ref.set(backendReadyFlag, false).pipe( + Effect.andThen( + Effect.sync(() => { + shutdownCount += 1; }), ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - onReady: Ref.set(backendReadyFlag, true).pipe( - 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; + ), + backendOutputLog: { + persistFailure: () => + Effect.sync(() => { + persistedFailureCount += 1; }), - }, - desktopTelemetryPublisher: { - removeControlSource: () => - Effect.sync(() => { - removedTelemetrySources += 1; - }), - }, - }); - assert.isTrue(Option.isNone(yield* instance.currentConfig)); - - yield* instance.start; - assert.equal(yield* Queue.take(startedPids), 123); - yield* Deferred.await(ready); - assert.isTrue(yield* Ref.get(backendReadyFlag)); - assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig)); - - const runningSnapshot = yield* instance.snapshot; - 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")); - 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); - }), - ), + discardSession: Effect.sync(() => { + discardedSessionCount += 1; + }), + }, + desktopTelemetryPublisher: { + removeControlSource: () => + Effect.sync(() => { + removedTelemetrySources += 1; + }), + }, + }); + assert.isTrue(Option.isNone(yield* instance.currentConfig)); + + yield* instance.start; + assert.equal(yield* Queue.take(startedPids), 123); + yield* Deferred.await(ready); + assert.isTrue(yield* Ref.get(backendReadyFlag)); + assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig)); + + const runningSnapshot = yield* instance.snapshot; + 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")); + 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); + }), ); it.effect("restarts when start is requested during stop teardown", () => - Effect.scoped( - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - const teardownStarted = yield* Deferred.make(); - const finishTeardown = yield* Deferred.make(); - let startCount = 0; + Effect.gen(function* () { + const starts = yield* Queue.unbounded(); + const teardownStarted = yield* Deferred.make(); + const finishTeardown = yield* Deferred.make(); + let startCount = 0; - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const scope = yield* Scope.Scope; - const closed = yield* Deferred.make(); - 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 layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + const closed = yield* Deferred.make(); + 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: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - }); + const instance = yield* makeTestInstance({ + spawnerLayer: layerSpawner, + httpClientLayer: layerHttpClient(() => Effect.never), + }); - yield* instance.start; - assert.equal(yield* Queue.take(starts), 1); + 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); + 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)); + 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())), - ), + 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("reports state-directory ownership once without scheduling another backend", () => - Effect.scoped( - Effect.gen(function* () { - let startCount = 0; - const refused = yield* Deferred.make(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.sync(() => { - startCount += 1; - return makeProcess({ - exitCode: Effect.succeed( - ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED), - ), - }); - }), - ), + Effect.gen(function* () { + let startCount = 0; + const refused = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.sync(() => { + startCount += 1; + return makeProcess({ + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED), + ), + }); + }), ), - httpClientLayer: layerHttpClient(() => Effect.never), - onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid), - }); - yield* instance.start; - yield* Deferred.await(refused); - const snapshot = yield* instance.snapshot; - assert.isFalse(snapshot.desiredRunning); - assert.isFalse(snapshot.restartScheduled); - yield* TestClock.adjust(Duration.minutes(1)); - assert.equal(startCount, 1); - }).pipe(Effect.provide(TestClock.layer())), - ), + ), + httpClientLayer: layerHttpClient(() => Effect.never), + onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid), + }); + yield* instance.start; + yield* Deferred.await(refused); + const snapshot = yield* instance.snapshot; + assert.isFalse(snapshot.desiredRunning); + assert.isFalse(snapshot.restartScheduled); + yield* TestClock.adjust(Duration.minutes(1)); + assert.equal(startCount, 1); + }).pipe(Effect.provide(TestClock.layer())), ); // A policy refusal is reported on the first exit, since retrying cannot fix it. @@ -632,145 +694,167 @@ describe("DesktopBackendManager", () => { ])( "reports exit $code with the server output after $exits exits", ({ code, exits, managedPolicy }) => - Effect.scoped( - Effect.gen(function* () { - const message = "Error: Cannot find module 'zod/v4' in /Users/René"; - let exitCount = 0; - const firstExit = yield* Deferred.make(); - const reports = yield* Queue.unbounded<{ - readonly exitCount: number; - readonly failure: DesktopBackendManager.BackendStartupFailure; - }>(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut - // lands inside the emoji's surrogate pair. - stderr: Stream.make( - new TextEncoder().encode( - `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`, - ), - new Uint8Array([0xc3]), - new Uint8Array([0xa9]), + Effect.gen(function* () { + const message = "Error: Cannot find module 'zod/v4' in /Users/René"; + let exitCount = 0; + const firstExit = yield* Deferred.make(); + const reports = yield* Queue.unbounded<{ + readonly exitCount: number; + readonly failure: DesktopBackendManager.BackendStartupFailure; + }>(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut + // lands inside the emoji's surrogate pair. + stderr: Stream.make( + new TextEncoder().encode( + `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`, ), - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)), - }), - ), + new Uint8Array([0xc3]), + new Uint8Array([0xa9]), + ), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)), + }), ), ), - httpClientLayer: layerHttpClient(() => Effect.never), - backendOutputLog: { - persistFailure: () => { - exitCount += 1; - return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid); - }, + ), + httpClientLayer: layerHttpClient(() => Effect.never), + backendOutputLog: { + persistFailure: () => { + exitCount += 1; + return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid); }, - onStartupFailure: (failure) => - Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid), - }); - yield* instance.start; - yield* Deferred.await(firstExit); - yield* TestClock.adjust(Duration.minutes(1)); - const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports); - assert.equal(exitsWhenReported, exits); - assert.equal(failure.reason, `The server could not start (code=${code}).`); - assert.equal(failure.managedPolicy, managedPolicy); - assert.isTrue(failure.output.endsWith(message)); - assert.isTrue(failure.output.isWellFormed()); - }).pipe(Effect.provide(TestClock.layer())), - ), + }, + onStartupFailure: (failure) => + Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid), + }); + yield* instance.start; + yield* Deferred.await(firstExit); + yield* TestClock.adjust(Duration.minutes(1)); + const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports); + assert.equal(exitsWhenReported, exits); + assert.equal(failure.reason, `The server could not start (code=${code}).`); + assert.equal(failure.managedPolicy, managedPolicy); + assert.isTrue(failure.output.endsWith(message)); + assert.isTrue(failure.output.isWellFormed()); + }).pipe(Effect.provide(TestClock.layer())), ); it.effect("waits out a slow startup and reports one that never becomes ready", () => - Effect.scoped( - Effect.gen(function* () { - const reports = yield* Queue.unbounded(); - const startInstance = (status: Ref.Ref, onReady?: Effect.Effect) => - makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed(makeProcess({ exitCode: Effect.never })), + Effect.gen(function* () { + const reports = yield* Queue.unbounded(); + const startInstance = (status: Ref.Ref, onReady?: Effect.Effect, stdout = "") => + makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + exitCode: Effect.never, + stdout: Stream.make(new TextEncoder().encode(stdout)), + }), ), ), - httpClientLayer: layerHttpClient((request) => - Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))), - ), - onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid), - ...(onReady ? { onReady } : {}), - }).pipe(Effect.tap((instance) => instance.start)); - - const slowStatus = yield* Ref.make(503); - const ready = yield* Deferred.make(); - yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid)); - yield* TestClock.adjust(Duration.seconds(66)); - yield* Ref.set(slowStatus, 200); - yield* TestClock.adjust(Duration.millis(100)); - yield* Deferred.await(ready); - assert.isTrue(Option.isNone(yield* Queue.poll(reports))); - - yield* startInstance(yield* Ref.make(503)); - yield* TestClock.adjust(Duration.seconds(179)); - assert.isTrue(Option.isNone(yield* Queue.poll(reports))); - yield* TestClock.adjust(Duration.seconds(1)); - const failure = yield* Queue.take(reports); - assert.equal(failure.reason, "The server started but did not become ready in time."); - }).pipe(Effect.provide(TestClock.layer())), - ), + ), + httpClientLayer: layerHttpClient((request) => + Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))), + ), + onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid), + ...(onReady ? { onReady } : {}), + }).pipe(Effect.tap((instance) => instance.start)); + + const slowStatus = yield* Ref.make(503); + const ready = yield* Deferred.make(); + yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid)); + yield* TestClock.adjust(Duration.seconds(66)); + yield* Ref.set(slowStatus, 200); + yield* TestClock.adjust(Duration.millis(100)); + yield* Deferred.await(ready); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + + const migratingStatus = yield* Ref.make(503); + const migrated = yield* Deferred.make(); + yield* startInstance( + migratingStatus, + Deferred.succeed(migrated, undefined).pipe(Effect.asVoid), + // Enough progress lines that the start line scrolls out of the output tail. + `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` + + Array.from( + { length: 80 }, + (_, index) => + `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} migration=${index}_Migration progress="${index + 1} of 80"\n`, + ).join(""), + ); + yield* TestClock.adjust(Duration.minutes(10)); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + yield* Ref.set(migratingStatus, 200); + yield* TestClock.adjust(Duration.millis(100)); + yield* Deferred.await(migrated); + + yield* startInstance( + yield* Ref.make(503), + undefined, + `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATIONS_FINISHED_MESSAGE}\n`, + ); + yield* TestClock.adjust(Duration.seconds(179)); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + yield* TestClock.adjust(Duration.seconds(1)); + const failure = yield* Queue.take(reports); + assert.equal(failure.reason, "The server started but did not become ready in time."); + }).pipe(Effect.provide(TestClock.layer())), ); it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () => - Effect.scoped( - Effect.gen(function* () { - const spawned = yield* Deferred.make(); - const teardownStarted = yield* Deferred.make(); - const teardownFinished = yield* Deferred.make(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const scope = yield* Scope.Scope; - yield* Deferred.succeed(spawned, undefined); - yield* Scope.addFinalizer( - scope, - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Effect.sleep(Duration.seconds(10))), - Effect.andThen(Deferred.succeed(teardownFinished, undefined)), - Effect.asVoid, - ), - ); - return makeProcess({ - exitCode: Deferred.await(teardownFinished).pipe( - Effect.as(ChildProcessSpawner.ExitCode(0)), - ), - }); - }), - ), + Effect.gen(function* () { + const spawned = yield* Deferred.make(); + const teardownStarted = yield* Deferred.make(); + const teardownFinished = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + yield* Deferred.succeed(spawned, undefined); + yield* Scope.addFinalizer( + scope, + Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Effect.sleep(Duration.seconds(10))), + Effect.andThen(Deferred.succeed(teardownFinished, undefined)), + Effect.asVoid, + ), + ); + return makeProcess({ + exitCode: Deferred.await(teardownFinished).pipe( + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + }); + }), ), - httpClientLayer: layerHttpClient(() => Effect.never), - }); - yield* instance.start; - yield* Deferred.await(spawned); - - // App quit and the updater stop every backend with this deadline. - const quitDone = yield* Deferred.make(); - const quitFiber = yield* instance - .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }) - .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild); - - yield* Deferred.await(teardownStarted); - // Past the quit deadline, quit must still wait for the backend to exit. - yield* TestClock.adjust(Duration.seconds(9)); - assert.isFalse(yield* Deferred.isDone(quitDone)); - - yield* TestClock.adjust(Duration.seconds(1)); - yield* Fiber.join(quitFiber); - assert.isTrue(yield* Deferred.isDone(teardownFinished)); - }).pipe(Effect.provide(TestClock.layer())), - ), + ), + httpClientLayer: layerHttpClient(() => Effect.never), + }); + yield* instance.start; + yield* Deferred.await(spawned); + + // App quit and the updater stop every backend with this deadline. + const quitDone = yield* Deferred.make(); + const quitFiber = yield* instance + .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }) + .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild); + + yield* Deferred.await(teardownStarted); + // Past the quit deadline, quit must still wait for the backend to exit. + yield* TestClock.adjust(Duration.seconds(9)); + assert.isFalse(yield* Deferred.isDone(quitDone)); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* Fiber.join(quitFiber); + assert.isTrue(yield* Deferred.isDone(teardownFinished)); + }).pipe(Effect.provide(TestClock.layer())), ); }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index d24b2f52f2..8b4f154b5d 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -1,5 +1,6 @@ import * as Brand from "effect/Brand"; import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -25,6 +26,7 @@ import { DesktopTelemetryControlMessage, type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue, } from "@t3tools/contracts"; +import { isRunningDatabaseMigrations } from "@t3tools/shared/databaseMigrationLog"; import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness"; import * as DesktopObservability from "../app/DesktopObservability.ts"; @@ -204,7 +206,7 @@ interface RunBackendProcessOptions extends DesktopBackendStartConfig { readonly outputDrainTimeout?: Duration.Duration; readonly onStarted?: (pid: number) => Effect.Effect; readonly onExitObserved?: () => Effect.Effect; - readonly onReady?: () => Effect.Effect; + readonly onReady?: (pid: number) => Effect.Effect; readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect; readonly onOutput?: ( streamName: BackendProcessOutputStream, @@ -251,8 +253,8 @@ export interface BackendInstanceSpec { readonly id: BackendInstanceId; readonly label: Effect.Effect; readonly configResolve: Effect.Effect; - /** Receives the ready run's resolved URL; reading current config could race a subsequent restart. */ - readonly onReady?: (httpBaseUrl: URL) => Effect.Effect; + /** Receives the ready run's URL and pid; reading current config could race a subsequent restart. */ + readonly onReady?: (httpBaseUrl: URL, pid: number) => Effect.Effect; readonly onShutdown?: () => Effect.Effect; readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect; readonly onStateDirOwned?: () => Effect.Effect; @@ -342,8 +344,26 @@ const closeRun = ( ); }; +const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]); +// Windows takes about a second to fail a refused connection to a non-loopback address such as a +// WSL distro IP, so one sequential poller notices readiness up to a second late. +const STAGGERED_READINESS_POLLERS = 4; +const READINESS_POLLER_STAGGER = Duration.millis(250); + const waitForHttpReady = ( options: BackendProcessContext & { readonly timeout: Duration.Duration }, +): Effect.Effect => { + const poll = pollHttpReady(options); + if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll; + return Effect.raceAll( + Array.from({ length: STAGGERED_READINESS_POLLERS }, (_, index) => + Effect.sleep(Duration.times(READINESS_POLLER_STAGGER, index)).pipe(Effect.andThen(poll)), + ), + ); +}; + +const pollHttpReady = ( + options: BackendProcessContext & { readonly timeout: Duration.Duration }, ): Effect.Effect => { const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl); return waitForHttpReadyShared({ @@ -483,21 +503,23 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( ), ); const outputFibers: Array> = []; + const serverReady = yield* Deferred.make(); yield* options.onStarted?.(handle.pid) ?? Effect.void; - if ( - options.bootstrap.desktopTelemetryControlFd !== undefined && - options.onDesktopTelemetryControl !== undefined - ) { + if (options.bootstrap.desktopTelemetryControlFd !== undefined) { const controlFd = options.bootstrap.desktopTelemetryControlFd; - const handleControl = options.onDesktopTelemetryControl; + const handleControl = options.onDesktopTelemetryControl ?? (() => Effect.void); 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.flatMap((message) => + message.type === "serverReady" + ? Deferred.succeed(serverReady, undefined) + : handleControl(message), + ), Effect.catchCause((cause) => logBackendProcessWarning("ignored invalid desktop telemetry control message", { fd: controlFd, @@ -569,15 +591,19 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( ); } // Cold WSL boots across /mnt/c can exceed one probe budget; retry while the backend is alive. + // HTTP polling stays as the fallback for backends without the control fd, such as WSL. const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() => - waitForHttpReady({ - executablePath: options.executablePath, - entryPath: options.entryPath, - cwd: options.cwd, - httpBaseUrl: options.httpBaseUrl, - timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT, - }).pipe( - Effect.flatMap(() => options.onReady?.() ?? Effect.void), + Effect.raceFirst( + waitForHttpReady({ + executablePath: options.executablePath, + entryPath: options.entryPath, + cwd: options.cwd, + httpBaseUrl: options.httpBaseUrl, + timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT, + }), + Deferred.await(serverReady), + ).pipe( + Effect.flatMap(() => options.onReady?.(handle.pid) ?? Effect.void), Effect.as(true), Effect.catchTags({ BackendReadinessTimeoutError: (error) => @@ -938,7 +964,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( ...run, exitObserved: true, })), - onReady: Effect.fn("desktop.backendInstance.onReady")(function* () { + onReady: Effect.fn("desktop.backendInstance.onReady")(function* (pid) { const isCurrentRun = yield* SubscriptionRef.modify(state, (latest) => { const activeRun = Option.getOrUndefined(latest.active); if (activeRun?.id !== runId) { @@ -958,7 +984,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( return; } - yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void; + yield* spec.onReady?.(config.value.httpBaseUrl, pid) ?? Effect.void; if ( config.value.runningDistro !== undefined && config.value.wslRuntimeId !== undefined @@ -971,6 +997,12 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( }), onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")( function* (error) { + if (isRunningDatabaseMigrations(yield* Ref.get(outputTail))) { + yield* logInstanceWarning("backend is still migrating its database; waiting", { + error: error.message, + }); + return; + } yield* logInstanceWarning("backend readiness check failed during bootstrap", { error: error.message, }); diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index b4c7827ce1..005a1cde12 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import { DESKTOP_UPDATE_IN_PROGRESS_TTL_MS } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -8,12 +9,15 @@ import * as TestClock from "effect/testing/TestClock"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; +import * as DesktopConfig from "../app/DesktopConfig.ts"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; @@ -106,26 +110,56 @@ const runningConfig = { function layerPool( labelRef: Ref.Ref, - backend?: Effect.Success>, + options: { + readonly config?: DesktopBackendStartConfig; + readonly resolvePrimary?: Effect.Effect; + readonly onMainContentsCommand?: ( + command: DesktopWindow.MainWindowContentsCommand, + ) => Effect.Effect; + readonly fileSystem?: Partial; + readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly httpClient?: HttpClient.HttpClient; + readonly onReady?: Effect.Effect; + readonly backend?: Effect.Success>; + } = {}, ): Layer.Layer { return DesktopBackendPool.layer.pipe( Layer.provideMerge( Layer.mergeAll( - FileSystem.layerNoop({ exists: () => Effect.succeed(true) }), - backend?.layer ?? + DesktopEnvironment.layer({ + dirname: "/repo/apps/desktop/src", + homeDirectory: "/test-home", + platform: "linux", + processArch: "x64", + appVersion: "1.2.3", + appPath: "/repo", + isPackaged: true, + resourcesPath: "/missing/resources", + runningUnderArm64Translation: false, + }).pipe( + Layer.provide( + Layer.mergeAll(Path.layer, DesktopConfig.layerTest({ T3CODE_HOME: "/test-home" })), + ), + Layer.orDie, + ), + FileSystem.layerNoop(options.fileSystem ?? { exists: () => Effect.succeed(true) }), + Path.layer, + options.backend?.layer ?? Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")), + options.spawner ?? + ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")), ), Layer.succeed( HttpClient.HttpClient, - HttpClient.make((request) => - backend === undefined - ? Effect.die("unexpected HTTP request") - : Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })), - ), - ), + options.httpClient ?? + HttpClient.make((request) => + options.backend === undefined + ? Effect.die("unexpected HTTP request") + : Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })), + ), + ), ), Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, { forInstance: () => @@ -150,7 +184,11 @@ function layerPool( }), DesktopBrowserHost.layer, Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, { - resolvePrimary: Effect.die("unexpected primary config resolve"), + resolvePrimary: + options.resolvePrimary ?? + (options.config + ? Effect.succeed(options.config) + : Effect.die("unexpected primary config resolve")), resolvePrimaryLabel: Ref.get(labelRef), resolveWsl: () => Effect.die("unexpected WSL config resolve"), currentBootstrapToken: Effect.die("unexpected bootstrap token read"), @@ -158,7 +196,12 @@ function layerPool( DesktopAppSettings.layerTest(), DesktopState.layer, DesktopWslEnvironment.layerTest(), - ElectronDialog.layer, + Layer.succeed(ElectronDialog.ElectronDialog, { + pickFolder: () => Effect.die("unexpected folder picker"), + pickFiles: () => Effect.die("unexpected file picker"), + showMessageBox: () => Effect.die("unexpected message box"), + showErrorBox: () => Effect.void, + } satisfies ElectronDialog.ElectronDialog["Service"]), ElectronApp.layer, Layer.succeed(DesktopWindow.DesktopWindow, { createMain: Effect.die("unexpected window create"), @@ -167,14 +210,15 @@ function layerPool( activate: Effect.die("unexpected window activate"), createMainIfBackendReady: Effect.die("unexpected window create"), showConnectingSplash: Effect.void, - handleBackendReady: () => Effect.void, + handleBackendReady: () => options.onReady ?? Effect.void, handleBackendNotReady: Effect.void, flushMainWindowBounds: Effect.void, prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.die("unexpected menu action"), dispatchSnapShotEvent: () => Effect.void, zoomMain: () => Effect.die("unexpected zoom"), - runMainContentsCommand: () => Effect.die("unexpected main contents command"), + runMainContentsCommand: + options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")), syncAppearance: Effect.void, } satisfies DesktopWindow.DesktopWindow["Service"]), ), @@ -182,86 +226,334 @@ function layerPool( ); } +const markerPath = "/test-home/runtime/desktop-update-in-progress"; +const runtimePath = "/test-home/userdata/server-runtime.json"; + +const makeUpdateMarkerFixture = () => + Effect.gen(function* () { + const allowReady = yield* Deferred.make(); + const runtimeChecked = yield* Deferred.make(); + const markerRemoved = yield* Deferred.make(); + const readyRuns = yield* Queue.unbounded(); + let nextPid = 123; + const files = new Map([[markerPath, JSON.stringify({ startedAt: 0, expiresAt: 60_000 })]]); + const removed: string[] = []; + const config: DesktopBackendStartConfig = { + executablePath: "/electron", + args: [], + entryPath: "/server/bin.mjs", + cwd: "/server", + env: {}, + bootstrap: { + mode: "desktop", + noBrowser: true, + port: 3774, + t3Home: "/test-home", + host: "127.0.0.1", + desktopBootstrapToken: "token", + tailscaleServeEnabled: false, + tailscaleServePort: 443, + }, + bootstrapDelivery: "fd3", + extendEnv: true, + httpBaseUrl: new URL("http://127.0.0.1:3774"), + captureOutput: false, + preflightFailure: Option.none(), + }; + const layer = layerPool(Ref.makeUnsafe("Local"), { + config, + fileSystem: { + exists: (path) => Effect.succeed(files.has(path) || path === config.entryPath), + readFileString: (path) => + (path === runtimePath ? Deferred.succeed(runtimeChecked, undefined) : Effect.void).pipe( + Effect.andThen(Effect.sync(() => files.get(path) ?? "")), + ), + remove: (path) => + Effect.sync(() => { + removed.push(path); + files.delete(path); + }).pipe( + Effect.andThen( + path === markerPath ? Deferred.succeed(markerRemoved, undefined) : Effect.void, + ), + Effect.asVoid, + ), + }, + spawner: ChildProcessSpawner.make(() => + Effect.gen(function* () { + const exited = yield* Deferred.make(); + const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe( + Effect.asVoid, + ); + // Like the real spawner, closing the run's scope ends the process. + yield* Effect.addFinalizer(() => exit); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(nextPid++), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Deferred.await(exited), + isRunning: Effect.succeed(true), + kill: () => exit, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + }), + ), + httpClient: HttpClient.make((request) => + Deferred.await(allowReady).pipe( + Effect.as(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }))), + ), + ), + onReady: Queue.offer(readyRuns, undefined).pipe(Effect.asVoid), + }); + const publishRuntime = (pid: number) => + files.set( + runtimePath, + JSON.stringify({ + version: 1, + pid, + port: 3774, + origin: "http://127.0.0.1:3774", + startedAt: "2026-10-27T00:00:00.000Z", + }), + ); + return { + layer, + files, + removed, + allowReady, + readyRuns, + runtimeChecked, + markerRemoved, + publishRuntime, + }; + }); + describe("DesktopBackendPool", () => { - it.effect("unregister during pool quit does not interrupt sibling stops", () => - Effect.scoped( + it.effect( + "keeps the update marker after HTTP readiness until the backend publishes its runtime", + () => Effect.gen(function* () { - const backend = yield* makeFakeBackendProcess(); + const fixture = yield* makeUpdateMarkerFixture(); yield* Effect.gen(function* () { const pool = yield* DesktopBackendPool.DesktopBackendPool; - const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); - const ready = yield* Deferred.make(); - const siblingStarted = yield* Deferred.make(); - const finishSibling = yield* Deferred.make(); - let siblingCompleted = false; - const instance = yield* pool.register({ - id, - label: Effect.succeed("WSL (Ubuntu)"), - configResolve: Effect.succeed(runningConfig), - onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid), - }); - yield* instance.start; - yield* backend.started; - yield* Deferred.await(ready); - const quitFiber = yield* Effect.all( - [ - instance.stop({ timeout: Duration.seconds(5) }), - Deferred.succeed(siblingStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishSibling)), - Effect.andThen( - Effect.sync(() => { - siblingCompleted = true; - }), - ), - ), - ], - { concurrency: "unbounded" }, - ).pipe(Effect.forkChild); - yield* Deferred.await(siblingStarted); - assert.equal(yield* Queue.take(backend.signals), "SIGTERM"); - const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild); + const primary = yield* pool.primary; + yield* primary.start; + yield* Deferred.succeed(fixture.allowReady, undefined); + yield* Queue.take(fixture.readyRuns); + assert.isTrue( + fixture.files.has(markerPath), + "a launcher could neither wait nor adopt between readiness and publication", + ); + yield* Deferred.await(fixture.runtimeChecked); yield* TestClock.adjust(Duration.seconds(5)); - assert.equal(yield* Queue.take(backend.signals), "SIGKILL"); - assert.isUndefined(quitFiber.pollUnsafe()); - assert.isUndefined(unregisterFiber.pollUnsafe()); - assert.isTrue(yield* backend.isRunning); - yield* TestClock.adjust(backend.killWait); - yield* Fiber.join(unregisterFiber); - yield* Deferred.succeed(finishSibling, undefined); - yield* Fiber.join(quitFiber); - - assert.isTrue(siblingCompleted); - assert.isFalse(yield* backend.isRunning); - assert.isTrue(Option.isNone((yield* instance.snapshot).activePid)); - assert.isTrue(Option.isNone(yield* pool.get(id))); - }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), backend))); + assert.isTrue(fixture.files.has(markerPath)); + fixture.publishRuntime(456); + yield* TestClock.adjust(Duration.seconds(1)); + assert.isTrue( + fixture.files.has(markerPath), + "another process's runtime is not the replacement", + ); + fixture.publishRuntime(123); + yield* TestClock.adjust(Duration.seconds(1)); + yield* Deferred.await(fixture.markerRemoved); + assert.deepEqual(fixture.removed, [markerPath]); + }).pipe(Effect.provide(fixture.layer)); }), - ), ); - it.effect("unregister stops the registered instance", () => - Effect.scoped( - Effect.gen(function* () { - const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); + it.effect("leaves a replacement update marker written while an earlier wait is pending", () => + Effect.gen(function* () { + const fixture = yield* makeUpdateMarkerFixture(); + yield* Effect.gen(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primary = yield* pool.primary; + yield* primary.start; + yield* Deferred.succeed(fixture.allowReady, undefined); + yield* Queue.take(fixture.readyRuns); + yield* Deferred.await(fixture.runtimeChecked); + yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000)); + const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 }); + fixture.files.set(markerPath, replacement); + yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)); + assert.equal(fixture.files.get(markerPath), replacement); + assert.deepEqual(fixture.removed, []); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + + it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () => + Effect.gen(function* () { + const fixture = yield* makeUpdateMarkerFixture(); + yield* Effect.gen(function* () { const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primary = yield* pool.primary; + yield* primary.start; + yield* Deferred.succeed(fixture.allowReady, undefined); + yield* Queue.take(fixture.readyRuns); + yield* Deferred.await(fixture.runtimeChecked); + yield* TestClock.adjust(Duration.seconds(30)); + yield* primary.stop(); + yield* primary.start; + yield* Queue.take(fixture.readyRuns); + yield* TestClock.adjust(Duration.seconds(31)); + assert.isTrue( + fixture.files.has(markerPath), + "the earlier run's wait must not end the later run's handoff", + ); + assert.deepEqual(fixture.removed, []); + fixture.publishRuntime(124); + yield* TestClock.adjust(Duration.millis(100)); + yield* Deferred.await(fixture.markerRemoved); + assert.deepEqual(fixture.removed, [markerPath]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + + it.effect("unregister during pool quit does not interrupt sibling stops", () => + Effect.gen(function* () { + const backend = yield* makeFakeBackendProcess(); + yield* Effect.gen(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); + const ready = yield* Deferred.make(); + const siblingStarted = yield* Deferred.make(); + const finishSibling = yield* Deferred.make(); + let siblingCompleted = false; const instance = yield* pool.register({ id, label: Effect.succeed("WSL (Ubuntu)"), - configResolve: Effect.succeed({ - ...runningConfig, - preflightFailure: Option.some({ reason: "WSL starting", fatal: false }), - }), + configResolve: Effect.succeed(runningConfig), + onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid), }); yield* instance.start; - assert.equal((yield* instance.snapshot).restartScheduled, true); + yield* backend.started; + yield* Deferred.await(ready); + const quitFiber = yield* Effect.all( + [ + instance.stop({ timeout: Duration.seconds(5) }), + Deferred.succeed(siblingStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishSibling)), + Effect.andThen( + Effect.sync(() => { + siblingCompleted = true; + }), + ), + ), + ], + { concurrency: "unbounded" }, + ).pipe(Effect.forkChild); + yield* Deferred.await(siblingStarted); + assert.equal(yield* Queue.take(backend.signals), "SIGTERM"); + const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild); + yield* TestClock.adjust(Duration.seconds(5)); + assert.equal(yield* Queue.take(backend.signals), "SIGKILL"); + assert.isUndefined(quitFiber.pollUnsafe()); + assert.isUndefined(unregisterFiber.pollUnsafe()); + assert.isTrue(yield* backend.isRunning); + yield* TestClock.adjust(backend.killWait); + yield* Fiber.join(unregisterFiber); + yield* Deferred.succeed(finishSibling, undefined); + yield* Fiber.join(quitFiber); + + assert.isTrue(siblingCompleted); + assert.isFalse(yield* backend.isRunning); + assert.isTrue(Option.isNone((yield* instance.snapshot).activePid)); + assert.isTrue(Option.isNone(yield* pool.get(id))); + }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend }))); + }), + ); + + it.effect("unregister stops the registered instance", () => + Effect.gen(function* () { + const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const instance = yield* pool.register({ + id, + label: Effect.succeed("WSL (Ubuntu)"), + configResolve: Effect.succeed({ + ...runningConfig, + preflightFailure: Option.some({ reason: "WSL starting", fatal: false }), + }), + }); + yield* instance.start; + assert.equal((yield* instance.snapshot).restartScheduled, true); - yield* pool.unregister(id); + yield* pool.unregister(id); - const stopped = yield* instance.snapshot; - assert.equal(stopped.desiredRunning, false); - assert.equal(stopped.restartScheduled, false); - assert.equal(Option.isNone(yield* pool.get(id)), true); - }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))), - ), + const stopped = yield* instance.snapshot; + assert.equal(stopped.desiredRunning, false); + assert.equal(stopped.restartScheduled, false); + assert.equal(Option.isNone(yield* pool.get(id)), true); + }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))), + ); + + it.effect("reloads a main window that read the WSL endpoint before the Windows fallback", () => + Effect.gen(function* () { + const events: string[] = []; + let resolves = 0; + const resolvePrimary = Effect.sync(() => + resolves++ === 0 + ? { + ...runningConfig, + preflightFailure: Option.some({ + reason: "WSL still unavailable", + fatal: false, + retryLimit: 1, + }), + } + : runningConfig, + ); + const ready = yield* Deferred.make(); + yield* Effect.gen(function* () { + const primary = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary; + yield* primary.start; + yield* TestClock.adjust(Duration.seconds(1)); + yield* Deferred.await(ready); + + assert.deepEqual(events, ["reload", "ready"]); + }).pipe( + Effect.provide( + layerPool(Ref.makeUnsafe("WSL"), { + resolvePrimary, + spawner: ChildProcessSpawner.make(() => + Effect.gen(function* () { + const exited = yield* Deferred.make(); + const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe( + Effect.asVoid, + ); + yield* Effect.addFinalizer(() => exit); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Deferred.await(exited), + isRunning: Effect.succeed(true), + kill: () => exit, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + }), + ), + httpClient: HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })), + ), + ), + onMainContentsCommand: (command) => Effect.sync(() => void events.push(command)), + onReady: Effect.sync(() => void events.push("ready")).pipe( + Effect.andThen(Deferred.succeed(ready, undefined)), + Effect.asVoid, + ), + }), + ), + ); + }), ); }); diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index a84e26909f..b45632e7b2 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -1,9 +1,17 @@ +import { + DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE, + DESKTOP_UPDATE_IN_PROGRESS_TTL_MS, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; 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 FiberHandle from "effect/FiberHandle"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as SubscriptionRef from "effect/SubscriptionRef"; @@ -15,6 +23,8 @@ import { ChildProcessSpawner } from "effect/process"; import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; +import * as DesktopHomeOwner from "./DesktopHomeOwner.ts"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; @@ -29,6 +39,10 @@ import { DESKTOP_APP_NAME } from "../fincke/build.ts"; const { logWarning: logBackendPoolWarning } = DesktopObservability.makeComponentLogger("desktop-backend-pool"); +const decodeServerRuntime = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ pid: Schema.Number, port: Schema.Number })), +); + export type BackendInstanceId = DesktopBackendManager.BackendInstanceId; export const BackendInstanceId = DesktopBackendManager.BackendInstanceId; export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID; @@ -104,6 +118,8 @@ type UnregisterAction = export const layer = Layer.effect( DesktopBackendPool, Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; const desktopWindow = yield* DesktopWindow.DesktopWindow; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -113,11 +129,61 @@ export const layer = Layer.effect( // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends. const layerScope = yield* Scope.Scope; const factoryContext = yield* Effect.context(); + const homeOwnerContext = yield* Effect.context< + FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment + >(); + + const updateMarkerPath = environment.path.join( + environment.baseDir, + "runtime", + DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE, + ); + const serverRuntimePath = environment.path.join(environment.stateDir, "server-runtime.json"); + // The server publishes its runtime after HTTP readiness. Until then an SSH launcher + // finds nothing to adopt, so dropping the marker earlier lets it start a competing server. + const releaseUpdateMarker = Effect.fn("desktop.backendPool.releaseUpdateMarker")(function* ( + httpBaseUrl: URL, + pid: number, + ) { + const marker = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option); + if (Option.isNone(marker)) { + return; + } + yield* fileSystem.readFileString(serverRuntimePath).pipe( + Effect.flatMap(decodeServerRuntime), + Effect.map((runtime) => runtime.pid === pid && runtime.port === Number(httpBaseUrl.port)), + Effect.orElseSucceed(() => false), + Effect.repeat({ + until: (published) => published, + schedule: Schedule.spaced(Duration.millis(100)), + }), + Effect.timeoutOption(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)), + ); + // A later update may have replaced the marker; that handoff is not ours to end. + const current = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option); + if (Option.isSome(current) && current.value === marker.value) { + yield* fileSystem.remove(updateMarkerPath, { force: true }).pipe(Effect.ignore); + } + }); + // One wait at a time: each run's shutdown or readiness ends the previous run's wait. + const updateMarkerWait = yield* FiberHandle.make(); + + // The main window loads during startup and reads the primary endpoint once; a Windows fallback + // before the first readiness replaces the WSL endpoint it read. + let primaryWasReady = false; + let reloadMainOnReady = false; + const reloadStaleMain = Effect.suspend(() => { + primaryWasReady = true; + if (!reloadMainOnReady) return Effect.void; + reloadMainOnReady = false; + return desktopWindow.runMainContentsCommand("reload"); + }); // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference. const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")( function* (failure: DesktopBackendManager.PreflightFailure) { const { reason, fatal } = failure; + if (!primaryWasReady) reloadMainOnReady = true; if (!fatal) { yield* logBackendPoolWarning( "primary WSL preflight retry window exhausted; using Windows for this launch", @@ -160,8 +226,10 @@ export const layer = Layer.effect( label: configuration.resolvePrimaryLabel, configResolve: configuration.resolvePrimary, // Absorb window errors so readiness can reset restartAttempt. - onReady: (httpBaseUrl) => - desktopWindow.handleBackendReady(httpBaseUrl).pipe( + onReady: (httpBaseUrl, pid) => + FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe( + Effect.andThen(reloadStaleMain), + Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)), // Only once the main window exists, so the recovery window never closes into nothing. Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })), Effect.catch((error) => @@ -172,15 +240,22 @@ export const layer = Layer.effect( ), onStartupFailure: (failure) => SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }), - onShutdown: () => desktopWindow.handleBackendNotReady, + onShutdown: () => + FiberHandle.clear(updateMarkerWait).pipe( + Effect.andThen(desktopWindow.handleBackendNotReady), + ), onPreflightFailed: handlePrimaryPreflightFailure, onStateDirOwned: () => - electronDialog - .showErrorBox( - "This data directory is unavailable", - `Another ${DESKTOP_APP_NAME} server is using this data directory. Stop that server, then reopen ${DESKTOP_APP_NAME}. You can also set a separate T3CODE_HOME and pair with the running server.`, - ) - .pipe(Effect.andThen(electronApp.quit)), + DesktopHomeOwner.readLiveHomeOwner().pipe( + Effect.flatMap((owner) => + electronDialog.showErrorBox( + "This data directory is unavailable", + DesktopHomeOwner.homeOwnedMessage(owner), + ), + ), + Effect.provideContext(homeOwnerContext), + Effect.andThen(electronApp.quit), + ), }); const instancesRef = yield* SynchronizedRef.make< diff --git a/apps/desktop/src/backend/DesktopHomeOwner.test.ts b/apps/desktop/src/backend/DesktopHomeOwner.test.ts new file mode 100644 index 0000000000..f0b0df1592 --- /dev/null +++ b/apps/desktop/src/backend/DesktopHomeOwner.test.ts @@ -0,0 +1,122 @@ +import * as NodeSqlite from "node:sqlite"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; + +import * as DesktopConfig from "../app/DesktopConfig.ts"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import * as DesktopHomeOwner from "./DesktopHomeOwner.ts"; + +const withTempHome = ( + run: ( + userdata: string, + ) => Effect.Effect< + A, + E, + DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem | Path.Path + >, +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-home-owner-" }); + yield* fs.makeDirectory(`${home}/userdata`, { recursive: true }); + return yield* run(`${home}/userdata`).pipe( + Effect.provide( + DesktopEnvironment.layer({ + dirname: "/repo/apps/desktop/src", + homeDirectory: home, + platform: "linux", + processArch: "x64", + appVersion: "0.0.0", + appPath: "/repo", + isPackaged: true, + resourcesPath: "/missing/resources", + runningUnderArm64Translation: false, + }).pipe( + Layer.provide( + Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: home })), + ), + ), + ), + ); + }).pipe(Effect.provide(NodeServices.layer)); + +const readOwnerWithRuntimeFile = (contents: string | undefined) => + withTempHome((userdata) => + Effect.gen(function* () { + if (contents !== undefined) { + yield* (yield* FileSystem.FileSystem).writeFileString( + `${userdata}/server-runtime.json`, + contents, + ); + } + return yield* DesktopHomeOwner.readLiveHomeOwner(); + }), + ); + +describe("DesktopHomeOwner.readLiveHomeOwner", () => { + it.effect("reports a live server recorded in server-runtime.json", () => + Effect.gen(function* () { + const owner = yield* readOwnerWithRuntimeFile( + JSON.stringify({ + version: 1, + pid: process.pid, + port: 3790, + origin: "http://127.0.0.1:3790", + startedAt: "2026-01-01T00:00:00.000Z", + serverVersion: "1.2.3", + }), + ); + assert.deepStrictEqual( + owner, + Option.some({ pid: process.pid, port: 3790, serverVersion: "1.2.3" }), + ); + assert.include( + DesktopHomeOwner.homeOwnedMessage(owner), + `PID ${process.pid}, port 3790, version 1.2.3`, + ); + }), + ); + + it.effect("ignores a missing, malformed or dead owner record", () => + Effect.gen(function* () { + assert.isTrue(Option.isNone(yield* readOwnerWithRuntimeFile(undefined))); + assert.isTrue(Option.isNone(yield* readOwnerWithRuntimeFile("{not json"))); + assert.isTrue( + Option.isNone(yield* readOwnerWithRuntimeFile(JSON.stringify({ pid: 0, port: 3790 }))), + ); + }), + ); +}); + +describe("DesktopHomeOwner.awaitHomeOwnershipRelease", () => { + it.effect("waits for a shutting-down owner to release the lock, then gives up", () => + withTempHome((userdata) => + Effect.gen(function* () { + assert.isTrue(yield* DesktopHomeOwner.awaitHomeOwnershipRelease()); + + const lock = new NodeSqlite.DatabaseSync(`${userdata}/server-owner.sqlite`); + lock.exec("BEGIN EXCLUSIVE;"); + const released = yield* Effect.forkChild(DesktopHomeOwner.awaitHomeOwnershipRelease()); + yield* TestClock.adjust("5 seconds"); + lock.close(); + yield* TestClock.adjust("1 second"); + assert.isTrue(yield* Fiber.join(released)); + + const held = new NodeSqlite.DatabaseSync(`${userdata}/server-owner.sqlite`); + held.exec("BEGIN EXCLUSIVE;"); + const owned = yield* Effect.forkChild(DesktopHomeOwner.awaitHomeOwnershipRelease()); + yield* TestClock.adjust("1 minute"); + assert.isFalse(yield* Fiber.join(owned)); + held.close(); + }), + ), + ); +}); diff --git a/apps/desktop/src/backend/DesktopHomeOwner.ts b/apps/desktop/src/backend/DesktopHomeOwner.ts new file mode 100644 index 0000000000..7f92176c8d --- /dev/null +++ b/apps/desktop/src/backend/DesktopHomeOwner.ts @@ -0,0 +1,99 @@ +// @effect-diagnostics nodeBuiltinImport:off - Probes the server's native SQLite ownership lock. +import * as NodeSqlite from "node:sqlite"; + +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { DESKTOP_APP_NAME } from "../fincke/build.ts"; +import { BACKEND_QUIT_STOP_TIMEOUT } from "./DesktopBackendManager.ts"; + +// The fields of the server's `server-runtime.json` that identify the owner of a data directory. +const HomeOwnerRuntimeState = Schema.Struct({ + pid: Schema.Int, + port: Schema.Int, + serverVersion: Schema.optional(Schema.String), +}); +export type HomeOwner = typeof HomeOwnerRuntimeState.Type; + +const decodeHomeOwner = Schema.decodeUnknownOption(Schema.fromJsonString(HomeOwnerRuntimeState)); + +/** Signal 0 only probes existence; EPERM still means alive. */ +const isProcessAlive = (pid: number): boolean => { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return error instanceof Error && "code" in error && error.code === "EPERM"; + } +}; + +/** + * Whether a server holds the T3 home's ownership lock (an exclusive transaction on + * `server-owner.sqlite`). A read-only read is refused with SQLITE_BUSY only while it is held. + */ +const isHomeOwnershipLocked = Effect.fn("DesktopHomeOwner.isHomeOwnershipLocked")(function* () { + const path = yield* Path.Path; + const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment; + const lockPath = path.join(stateDir, "server-owner.sqlite"); + return yield* Effect.sync(() => { + try { + const db = new NodeSqlite.DatabaseSync(lockPath, { readOnly: true }); + try { + db.exec("PRAGMA busy_timeout = 0"); + db.prepare("SELECT count(*) FROM sqlite_master").get(); + return false; + } finally { + db.close(); + } + } catch (cause) { + // Anything but SQLITE_BUSY (a missing file included) leaves the decision to the backend. + return cause instanceof Error && "errcode" in cause && cause.errcode === 5; + } + }); +}); + +// A quitting app's backend holds the lock until it exits, which can outlast the relaunch of an update. +const HOME_OWNERSHIP_RELEASE_GRACE = Duration.sum(BACKEND_QUIT_STOP_TIMEOUT, Duration.seconds(3)); +const HOME_OWNERSHIP_RELEASE_POLL_INTERVAL = Duration.millis(250); + +/** Whether the ownership lock is free, or frees within the grace a shutting-down server needs. */ +export const awaitHomeOwnershipRelease = Effect.fn("DesktopHomeOwner.awaitHomeOwnershipRelease")( + function* () { + while (yield* isHomeOwnershipLocked()) { + yield* Effect.sleep(HOME_OWNERSHIP_RELEASE_POLL_INTERVAL); + } + return true; + }, + Effect.timeoutOrElse({ + duration: HOME_OWNERSHIP_RELEASE_GRACE, + orElse: () => Effect.succeed(false), + }), +); + +/** The live server recorded as owning the desktop's T3 home. Only call once the ownership lock is known held: a live PID alone may be reused. */ +export const readLiveHomeOwner = Effect.fn("DesktopHomeOwner.readLiveHomeOwner")(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment; + const raw = yield* fs + .readFileString(path.join(stateDir, "server-runtime.json")) + .pipe(Effect.option); + return Option.flatMap(raw, decodeHomeOwner).pipe( + Option.filter((owner) => isProcessAlive(owner.pid)), + ); +}); + +export const homeOwnedMessage = (owner: Option.Option): string => { + const detail = Option.match(owner, { + onNone: () => "", + onSome: (owner) => + ` (PID ${owner.pid}, port ${owner.port}${owner.serverVersion ? `, version ${owner.serverVersion}` : ""})`, + }); + return `Another ${DESKTOP_APP_NAME} server is using this data directory${detail}. Stop that server, then reopen ${DESKTOP_APP_NAME}. You can also set a separate T3CODE_HOME and pair with the running server.`; +}; diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index e82e3afea7..c15ce3932b 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -1,11 +1,13 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, describe, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; +import * as Result from "effect/Result"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; @@ -238,4 +240,34 @@ describe("DesktopLocalEnvironmentAuth", () => { assert.strictEqual(yield* Ref.get(requestCount), 1); }).pipe(Effect.provide(TestClock.layer())), ); + + it.effect("waits through a backend that stalls for 30 seconds after it is ready", () => + Effect.gen(function* () { + const requestCount = yield* Ref.make(0); + const layerHttpClient = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.gen(function* () { + yield* Ref.update(requestCount, (count) => count + 1); + const now = yield* Clock.currentTimeMillis; + return now < 30_000 ? yield* Effect.never : tokenResponse(request); + }), + ), + ); + const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe( + Effect.provide( + DesktopLocalEnvironmentAuth.layer.pipe( + Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)), + ), + ), + ); + + const fiber = yield* auth.getBearerToken.pipe(Effect.result, Effect.forkChild); + yield* TestClock.adjust(Duration.seconds(45)); + const result = yield* Fiber.join(fiber); + + assert.isTrue(Result.isSuccess(result)); + assert.strictEqual(yield* Ref.get(requestCount), 4); + }).pipe(Effect.provide(TestClock.layer())), + ); }); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts index be2ce66265..0947c29c00 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -18,7 +18,8 @@ import * as HttpClient from "effect/http/HttpClient"; import * as DesktopBackendPool from "./DesktopBackendPool.ts"; import { DESKTOP_APP_NAME } from "../fincke/build.ts"; -const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(15); +// Each /oauth/token attempt may take 10 s, so a backend busy after ready needs several attempts. +const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(60); const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500); const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]); diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts index 054655917c..397a757704 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts @@ -1,7 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import { HttpClient } from "effect/http"; +import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts"; @@ -79,4 +79,41 @@ describe("tailscale endpoint provider", () => { ); }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), ); + + it.effect("offers Tailscale HTTPS only when Serve reaches this desktop's backend", () => + Effect.gen(function* () { + const magicDnsStatus = (servedEnvironmentId: string) => + resolveTailscaleAdvertisedEndpoints({ + port: 3773, + serveEnabled: true, + networkInterfaces: {}, + statusJson: `{"Self":{"DNSName":"desktop.example.ts.net.","TailscaleIPs":[]}}`, + }).pipe( + Effect.map((endpoints) => endpoints.map((endpoint) => endpoint.status)), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ + environmentId: + new URL(request.url).hostname === "127.0.0.1" + ? "desktop-backend" + : servedEnvironmentId, + label: "T3 server", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.1.9", + capabilities: { repositoryIdentity: true }, + }), + ), + ), + ), + ), + ); + + assert.deepEqual(yield* magicDnsStatus("desktop-backend"), ["available"]); + assert.deepEqual(yield* magicDnsStatus("another-server"), ["unavailable"]); + }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), + ); }); diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.ts index f305f501ad..5e4a2fd969 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.ts @@ -1,5 +1,9 @@ import { createAdvertisedEndpoint } from "@t3tools/shared/advertisedEndpoint"; -import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts"; +import { + ExecutionEnvironmentDescriptor, + type AdvertisedEndpoint, + type AdvertisedEndpointProvider, +} from "@t3tools/contracts"; import { buildTailscaleHttpsBaseUrl, isTailscaleIpv4Address, @@ -11,6 +15,7 @@ import { import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts"; @@ -71,10 +76,20 @@ function resolveTailscaleIpAdvertisedEndpoints(input: { return endpoints; } +// The backend may run elsewhere (WSL), so ask it for its id instead of reading the state dir. +const probeServesThisBackend = (localHttpUrl: string) => (baseUrl: string) => + HttpClient.get(new URL("/.well-known/t3/environment", localHttpUrl)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)), + Effect.flatMap(({ environmentId }) => probeTailscaleHttpsEndpoint({ baseUrl, environmentId })), + Effect.orElseSucceed(() => false), + ); + const resolveTailscaleMagicDnsAdvertisedEndpoint = Effect.fn( "resolveTailscaleMagicDnsAdvertisedEndpoint", )(function* (input: { readonly dnsName: string | null; + readonly localHttpUrl: string; readonly serveEnabled: boolean; readonly servePort?: number; readonly probe?: (baseUrl: string) => Effect.Effect; @@ -87,11 +102,7 @@ const resolveTailscaleMagicDnsAdvertisedEndpoint = Effect.fn( magicDnsName: input.dnsName, ...(input.servePort === undefined ? {} : { servePort: input.servePort }), }); - const probe = - input.probe?.(httpBaseUrl) ?? - probeTailscaleHttpsEndpoint({ - baseUrl: httpBaseUrl, - }); + const probe = (input.probe ?? probeServesThisBackend(input.localHttpUrl))(httpBaseUrl); const isReachable = input.serveEnabled ? yield* probe : false; return Option.some( @@ -139,6 +150,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints({ ...input, status }); const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({ dnsName: status?.magicDnsName ?? null, + localHttpUrl: `http://127.0.0.1:${input.port}`, serveEnabled: input.serveEnabled === true, ...(input.servePort === undefined ? {} : { servePort: input.servePort }), ...(input.probe === undefined ? {} : { probe: input.probe }), diff --git a/apps/desktop/src/electron/ElectronAudio.test.ts b/apps/desktop/src/electron/ElectronAudio.test.ts new file mode 100644 index 0000000000..b38d7bbb3a --- /dev/null +++ b/apps/desktop/src/electron/ElectronAudio.test.ts @@ -0,0 +1,60 @@ +import * as Effect from "effect/Effect"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { app } from "electron"; +import { expect, vi } from "vite-plus/test"; +import { it } from "@effect/vitest"; +import * as Fiber from "effect/Fiber"; + +const { getAppMetrics, kill } = vi.hoisted(() => ({ getAppMetrics: vi.fn(), kill: vi.fn() })); +vi.mock("node:process", () => ({ kill })); +vi.mock("electron", async () => { + const { EventEmitter } = await import("node:events"); + return { app: Object.assign(new EventEmitter(), { getAppMetrics }) }; +}); + +import { restart } from "./ElectronAudio.ts"; + +const audio = { pid: 42, type: "Utility", serviceName: "audio.mojom.AudioService" }; + +it.effect("coalesces recovery and waits for its own audio utility to exit", () => + Effect.gen(function* () { + getAppMetrics.mockReturnValue([ + { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" }, + { pid: 2, type: "Browser", serviceName: audio.serviceName }, + audio, + ]); + const started = Promise.withResolvers(); + kill.mockReset().mockImplementation(() => { + started.resolve(); + }); + const pending = yield* Effect.forkChild( + Effect.all([restart(), restart()], { concurrency: "unbounded" }), + ); + yield* Effect.promise(() => started.promise); + app.emit( + "child-process-gone", + {}, + { type: "Utility", serviceName: "network.mojom.NetworkService" }, + ); + expect(app.listenerCount("child-process-gone")).toBe(1); + app.emit("child-process-gone", {}, audio); + expect(yield* Fiber.join(pending)).toEqual([true, true]); + expect(kill.mock.calls).toEqual([[42, "SIGTERM"]]); + expect(app.listenerCount("child-process-gone")).toBe(0); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), +); + +it.effect.each(["linux", "darwin", "win32"] as const)( + "leaves other processes alone on %s", + (platform) => + Effect.gen(function* () { + getAppMetrics.mockReturnValue([ + { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" }, + ]); + kill.mockReset(); + expect(yield* restart().pipe(Effect.provideService(HostProcess.Platform, platform))).toBe( + false, + ); + expect(kill).not.toHaveBeenCalled(); + }), +); diff --git a/apps/desktop/src/electron/ElectronAudio.ts b/apps/desktop/src/electron/ElectronAudio.ts new file mode 100644 index 0000000000..6a7f290d6f --- /dev/null +++ b/apps/desktop/src/electron/ElectronAudio.ts @@ -0,0 +1,62 @@ +// @effect-diagnostics globalTimers:off -- The shared native restart deadline must outlive individual IPC callers. +// @effect-diagnostics nodeBuiltinImport:off -- Only Electron's main process can restart its Chromium audio utility. +import * as NodeProcess from "node:process"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { app, type Details, type Event } from "electron"; + +class AudioServiceRestartError extends Schema.TaggedError()( + "AudioServiceRestartError", + { cause: Schema.Defect() }, +) {} + +let pendingRestart: Promise | undefined; + +export const restart = Effect.fn("ElectronAudio.restart")(function* () { + if ((yield* HostProcess.Platform) !== "linux") return false; + return yield* Effect.tryPromise({ + try: () => { + if (pendingRestart) return pendingRestart; + const audio = app + .getAppMetrics() + .find( + (metric) => + metric.type === "Utility" && metric.serviceName === "audio.mojom.AudioService", + ); + if (!audio) return Promise.resolve(false); + // A failed PulseAudio context survives new getUserMedia calls; Chromium reconnects when its utility exits. + pendingRestart = new Promise((resolve, reject) => { + const cleanup = () => { + clearTimeout(timer); + app.removeListener("child-process-gone", onGone); + }; + const onGone = (_event: Event, details: Details) => { + if (details.type === "Utility" && details.serviceName === audio.serviceName) { + cleanup(); + resolve(true); + } + }; + const timer = setTimeout(() => { + cleanup(); + resolve(false); + }, 5_000); + app.on("child-process-gone", onGone); + try { + NodeProcess.kill(audio.pid, "SIGTERM"); + } catch (cause) { + cleanup(); + reject(cause); + } + }).finally(() => { + pendingRestart = undefined; + }); + return pendingRestart; + }, + catch: (cause) => new AudioServiceRestartError({ cause }), + }).pipe( + Effect.catch((cause) => + Effect.logWarning("Could not restart the audio service", cause).pipe(Effect.as(false)), + ), + ); +}); diff --git a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts new file mode 100644 index 0000000000..0a37f621dd --- /dev/null +++ b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Fake Electron net request and response emitters. +import * as NodeEvents from "node:events"; +import { ElectronHttpExecutor } from "electron-updater/out/electronHttpExecutor.js"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +function startRequest() { + const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn() }); + const response = new NodeEvents.EventEmitter(); + const reject = vi.fn(); + new ElectronHttpExecutor().addErrorAndTimeoutHandlers(request, reject); + // Electron's net.ClientRequest emits these as soon as the request body is sent, before any response. + request.emit("finish"); + request.emit("close"); + return { request, response, reject }; +} + +describe("ElectronHttpExecutor idle timeout", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it("aborts a request that receives no response for 60 seconds", () => { + const { request, reject } = startRequest(); + + vi.advanceTimersByTime(59_999); + expect(reject).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + + expect(request.abort).toHaveBeenCalledOnce(); + expect(reject).toHaveBeenCalledWith(new Error("Request timed out")); + }); + + it("keeps a slow download alive while data keeps arriving", () => { + const { request, response, reject } = startRequest(); + request.emit("response", response); + + for (let elapsed = 0; elapsed < 180_000; elapsed += 30_000) { + vi.advanceTimersByTime(30_000); + response.emit("data", Buffer.alloc(1)); + } + + expect(request.abort).not.toHaveBeenCalled(); + expect(reject).not.toHaveBeenCalled(); + }); + + it("stops the timer once the response ends", () => { + const { request, response, reject } = startRequest(); + request.emit("response", response); + + response.emit("end"); + vi.advanceTimersByTime(600_000); + + expect(request.abort).not.toHaveBeenCalled(); + expect(reject).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 4ff3df6bf1..540326346e 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -1,4 +1,4 @@ -import type { ContextMenuItem } from "@t3tools/contracts"; +import type { ContextMenuItem, ContextMenuSource } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -17,6 +17,7 @@ export interface ElectronMenuContextInput { readonly window: Electron.BrowserWindow; readonly items: readonly ContextMenuItem[]; readonly position: Option.Option; + readonly source: Option.Option; } export interface ElectronMenuTemplateInput { @@ -259,7 +260,11 @@ export const make = Effect.gen(function* () { callback: () => complete(Option.none()), }), }); - menu.popup(popupOptions); + menu.popup( + Option.isSome(input.source) + ? { ...popupOptions, sourceType: input.source.value } + : popupOptions, + ); } catch (cause) { if (completed) { return; diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.ts index 8d553aaa55..72939ea79c 100644 --- a/apps/desktop/src/electron/ElectronProtocol.test.ts +++ b/apps/desktop/src/electron/ElectronProtocol.test.ts @@ -62,7 +62,7 @@ describe("ElectronProtocol", () => { assert.equal((yield* request("/%invalid")).status, 400); assert.equal((yield* request("/", { method: "POST" })).status, 405); assert.equal(netFetchMock.mock.calls.length, 0); - }).pipe(Effect.provide(Layer.merge(layerProtocol, NodeServices.layer)), Effect.scoped), + }).pipe(Effect.provide(Layer.merge(layerProtocol, NodeServices.layer))), ); it.effect("proxies the stable renderer origin to the current app server", () => diff --git a/apps/desktop/src/electron/ElectronShell.test.ts b/apps/desktop/src/electron/ElectronShell.test.ts index 9864c19b0d..e8618b4f5c 100644 --- a/apps/desktop/src/electron/ElectronShell.test.ts +++ b/apps/desktop/src/electron/ElectronShell.test.ts @@ -54,18 +54,30 @@ describe("ElectronShell", () => { }).pipe(Effect.provide(ElectronShell.layer)), ); - it.effect("opens only the bare Grok Bot launch link", () => + it.effect("opens only the Grok Bot prompt link", () => Effect.gen(function* () { openExternalMock.mockResolvedValue(undefined); + const prompt = "grokbot://app/v1/prompt?text=Add%20the%20MCP%20server"; const electronShell = yield* ElectronShell.ElectronShell; const results = yield* Effect.forEach( - ["grokbot://app", "grokbot://app/v1/prompt?id=bot&text=hi", "grokbot://"], + [ + prompt, + "grokbot://app", + "grokbot://app/v1/prompt?id=bot&text=hi", + "grokbot://app/v1/prompt?text=a&text=b", + "grokbot://app/v1/other?text=hi", + "grokbot://app/v1/prompt?text=hi#x", + "grokbot://:secret@app/v1/prompt?text=hi", + "grokbot://user@app/v1/prompt?text=hi", + "grokbot://other/v1/prompt?text=hi", + "other://app/v1/prompt?text=hi", + ], (url) => electronShell.openExternal(url), ); - assert.deepEqual(results, [true, false, false]); - assert.deepEqual(openExternalMock.mock.calls, [["grokbot://app"]]); + assert.deepEqual(results, [true, ...Array(9).fill(false)]); + assert.deepEqual(openExternalMock.mock.calls, [[prompt]]); }).pipe(Effect.provide(ElectronShell.layer)), ); diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.ts index e342361750..d27c51d57c 100644 --- a/apps/desktop/src/electron/ElectronShell.ts +++ b/apps/desktop/src/electron/ElectronShell.ts @@ -21,9 +21,16 @@ const REMOTE_EDITOR_PROTOCOLS = new Set( }), ); -// "Use T3 Code in another app" opens these apps (apps/web/src/components/mcp/mcpApps.ts). List +// "Use T3 Code in another app" opens these apps (apps/web/src/components/mcp/mcpApps.ts). Match // each exact link shape the wizard sends, never a whole scheme. -const APP_LAUNCH_URLS = new Set(["grokbot://app"]); +const isAppLaunchUrl = (url: URL) => + url.protocol === "grokbot:" && + url.host === "app" && + url.pathname === "/v1/prompt" && + url.username.length === 0 && + url.password.length === 0 && + url.hash.length === 0 && + [...url.searchParams.keys()].join() === "text"; // Zed embeds [user@]host in the path; reject passwords and ports there. const ZED_SSH_PATHNAME = /^\/(?:[^/@:]+@)?[^/@:]+\/.*$/; @@ -50,7 +57,7 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option { try { const url = new URL(rawUrl); return SAFE_WEB_PROTOCOLS.has(url.protocol) || - APP_LAUNCH_URLS.has(url.href) || + isAppLaunchUrl(url) || isRemoteEditorUrl(url) || isLocalEditorFileUrl(url) ? Option.some(url.href) diff --git a/apps/desktop/src/electron/ElectronTheme.test.ts b/apps/desktop/src/electron/ElectronTheme.test.ts index 4239bfe4c5..47aa0ce1f8 100644 --- a/apps/desktop/src/electron/ElectronTheme.test.ts +++ b/apps/desktop/src/electron/ElectronTheme.test.ts @@ -42,7 +42,7 @@ describe("ElectronTheme", () => { assert.equal(nativeTheme.themeSource, "light"); portal.report(null); assert.equal(nativeTheme.themeSource, "system"); - }).pipe(Effect.scoped), + }), ); it.effect("keeps an explicit appearance over the desktop color scheme", () => @@ -57,7 +57,7 @@ describe("ElectronTheme", () => { yield* theme.setSource("system"); assert.equal(nativeTheme.themeSource, "dark"); - }).pipe(Effect.scoped), + }), ); it.effect("stops following the desktop when the layer is released", () => @@ -76,6 +76,6 @@ describe("ElectronTheme", () => { }); yield* theme.setSource("system"); assert.equal(nativeTheme.themeSource, "system"); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts new file mode 100644 index 0000000000..e47c741bf3 --- /dev/null +++ b/apps/desktop/src/electron/ElectronUpdater.test.ts @@ -0,0 +1,118 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Intercepts the spawn electron-updater requires natively. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { autoUpdater } from "electron-updater"; +import type * as NodeChildProcess from "node:child_process"; +import * as NodeModule from "node:module"; +import { vi } from "vite-plus/test"; + +// electron-updater requires Electron natively, outside vi.mock's reach, and builds its +// autoUpdater singleton as soon as it is imported. +vi.hoisted(() => { + const NodeModule = process.getBuiltinModule("node:module"); + const NodeEvents = process.getBuiltinModule("node:events"); + const require = NodeModule.createRequire(import.meta.url); + const electronPath = NodeModule.createRequire(require.resolve("electron-updater")).resolve( + "electron", + ); + const electronModule = new NodeModule.Module(electronPath); + electronModule.filename = electronPath; + electronModule.loaded = true; + electronModule.exports = { + app: { + getVersion: () => "1.0.0", + getName: () => "T3 Code", + isPackaged: true, + quit: () => undefined, + once: () => undefined, + }, + autoUpdater: new NodeEvents.EventEmitter(), + }; + require.cache[electronPath] = electronModule; +}); + +import * as ElectronUpdater from "./ElectronUpdater.ts"; + +const childProcess = NodeModule.createRequire(import.meta.url)("node:child_process") as { + spawn: ( + command: string, + args: ReadonlyArray, + options: NodeChildProcess.SpawnOptions, + ) => NodeChildProcess.ChildProcess; +}; + +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "ElectronUpdater AppImage install", + () => { + it.live("relaunches the installed AppImage without the updating process's descriptors", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-appimage-install-" }); + const appImagePath = path.join(dir, "T3-Code.AppImage"); + const stagedPath = path.join(dir, "T3-Code-1.0.1.AppImage"); + const fdReportPath = path.join(dir, "relaunched-fds.txt"); + yield* fileSystem.writeFileString(appImagePath, "old AppImage"); + yield* fileSystem.writeFileString( + stagedPath, + `#!/bin/sh\nls /proc/self/fd > '${fdReportPath}'\n`, + ); + yield* fileSystem.chmod(stagedPath, 0o755); + + yield* Effect.acquireRelease( + Effect.sync(() => vi.stubEnv("APPIMAGE", appImagePath)), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + + autoUpdater.logger = null; + Object.assign(autoUpdater, { + downloadedUpdateHelper: { + file: stagedPath, + downloadedFileInfo: { isAdminRightsRequired: false }, + }, + }); + + // Electron's main process holds the AppImage runtime's keepalive pipe and some + // Chromium files without O_CLOEXEC. Node cannot hold such a descriptor, so the + // relaunch runs with fd 7 opened that way to stand in for them. + const relaunched = yield* Deferred.make(); + const realSpawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = (command, args, options) => { + const child = realSpawn( + "bash", + ["-c", 'exec 7 Deferred.doneUnsafe(relaunched, Effect.void)); + return child; + }; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = realSpawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + + const electronUpdater = yield* ElectronUpdater.ElectronUpdater; + yield* electronUpdater.quitAndInstall({ isSilent: true, isForceRunAfter: true }); + yield* Deferred.await(relaunched); + + const descriptors = (yield* fileSystem.readFileString(fdReportPath)).trim().split("\n"); + assert.notInclude( + descriptors, + "7", + `relaunched AppImage inherited the updating process's fd 7 (open fds: ${descriptors.join(" ")})`, + ); + }).pipe(Effect.provide([ElectronUpdater.layer, NodeServices.layer])), + ); + }, +); diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts index c71b42040d..0cc22bb4b1 100644 --- a/apps/desktop/src/electron/ElectronUpdater.ts +++ b/apps/desktop/src/electron/ElectronUpdater.ts @@ -4,9 +4,29 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; -import { autoUpdater } from "electron-updater"; +import { AppImageUpdater, autoUpdater } from "electron-updater"; type AutoUpdater = typeof autoUpdater; +type SpawnLog = (cmd: string, args?: Array, ...rest: Array) => Promise; + +// Electron holds the AppImage runtime's keepalive pipe and some files without O_CLOEXEC; a +// relaunched AppImage inherits them, so old runtimes and FUSE mounts never exit. bash (AppRun +// already needs it; dash cannot close multi-digit fds) closes them before exec'ing the AppImage. +// -p skips BASH_ENV and exported functions in the helper only; the AppImage still receives both. +const CLOSE_INHERITED_FDS_THEN_EXEC = + 'for fd in /proc/self/fd/*; do fd=${fd##*/}; case $fd in *[!0-9]*|[012]) ;; *) eval "exec $fd>&-" ;; esac; done; exec "$@"'; + +const relaunchWithoutInheritedDescriptors = (updater: AppImageUpdater) => { + const spawnLog = (AppImageUpdater.prototype as unknown as { spawnLog: SpawnLog }).spawnLog; + (updater as unknown as { spawnLog: SpawnLog }).spawnLog = function (cmd, args = [], ...rest) { + return spawnLog.call( + this, + "bash", + ["-p", "-c", CLOSE_INHERITED_FDS_THEN_EXEC, cmd, cmd, ...args], + ...rest, + ); + }; +}; export type ElectronUpdaterFeedUrl = Parameters[0]; @@ -153,6 +173,7 @@ export const make = ElectronUpdater.of({ }) { return Effect.suspend(() => { const channel = autoUpdater.channel; + if (autoUpdater instanceof AppImageUpdater) relaunchWithoutInheritedDescriptors(autoUpdater); return Effect.try({ try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter), catch: (cause) => diff --git a/apps/desktop/src/electron/ElectronWindow.test.ts b/apps/desktop/src/electron/ElectronWindow.test.ts index 9eb41ed4e2..eac944722e 100644 --- a/apps/desktop/src/electron/ElectronWindow.test.ts +++ b/apps/desktop/src/electron/ElectronWindow.test.ts @@ -148,6 +148,34 @@ describe("ElectronWindow", () => { }).pipe(Effect.provide(layerTestFor("win32"))), ); + it.effect("reports which windows were created with a title bar overlay", () => + Effect.gen(function* () { + const framed = { isDestroyed: () => false }; + const overlay = { isDestroyed: () => false }; + browserWindowMock + .mockImplementationOnce(function FramedWindowMock() { + return framed; + }) + .mockImplementationOnce(function OverlayWindowMock() { + return overlay; + }); + const electronWindow = yield* ElectronWindow.ElectronWindow; + yield* electronWindow.create({}); + yield* electronWindow.create({ + titleBarStyle: "hidden", + titleBarOverlay: { color: "#01000000", height: 40 }, + }); + getAllWindowsMock.mockReturnValue([framed, overlay, { isDestroyed: () => false }]); + + const seen: Array = []; + yield* electronWindow.syncAllAppearance((_window, { titleBarOverlay }) => + Effect.sync(() => seen.push(titleBarOverlay)), + ); + + assert.deepEqual(seen, [false, true, false]); + }).pipe(Effect.provide(layerTestFor("win32"))), + ); + it.effect("preserves destroy failures and continues with later windows", () => Effect.gen(function* () { const cause = new Error("window destroy failed"); diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts index 15a117a52b..b5f89969e6 100644 --- a/apps/desktop/src/electron/ElectronWindow.ts +++ b/apps/desktop/src/electron/ElectronWindow.ts @@ -125,7 +125,10 @@ export class ElectronWindow extends Context.Service< readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect; readonly destroyAll: Effect.Effect; readonly syncAllAppearance: ( - sync: (window: Electron.BrowserWindow) => Effect.Effect, + sync: ( + window: Electron.BrowserWindow, + appearance: { readonly titleBarOverlay: boolean }, + ) => Effect.Effect, ) => Effect.Effect; } >()("@t3tools/desktop/electron/ElectronWindow") {} @@ -145,6 +148,7 @@ export const make = Effect.gen(function* () { yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close())); const mainWindowRef = yield* Ref.make>(Option.none()); const auxiliaryWindows = new WeakSet(); + const titleBarOverlayWindows = new WeakSet(); const listWindows = Effect.try({ try: () => Electron.BrowserWindow.getAllWindows(), @@ -241,6 +245,9 @@ export const make = Effect.gen(function* () { try: () => { const window = new Electron.BrowserWindow(options); if (behavior?.auxiliary === true) auxiliaryWindows.add(window); + if (options.titleBarOverlay !== undefined && options.titleBarOverlay !== false) { + titleBarOverlayWindows.add(window); + } return window; }, catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }), @@ -383,14 +390,17 @@ export const make = Effect.gen(function* () { } }), syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* ( - sync: (window: Electron.BrowserWindow) => Effect.Effect, + sync: ( + window: Electron.BrowserWindow, + appearance: { readonly titleBarOverlay: boolean }, + ) => Effect.Effect, ) { const windows = yield* listWindows; for (const window of windows) { if (yield* isWindowDestroyed(window)) { continue; } - yield* sync(window); + yield* sync(window, { titleBarOverlay: titleBarOverlayWindows.has(window) }); } }), }); diff --git a/apps/desktop/src/ipc/DesktopIpc.test.ts b/apps/desktop/src/ipc/DesktopIpc.test.ts index 45f63b951f..1973ab49ce 100644 --- a/apps/desktop/src/ipc/DesktopIpc.test.ts +++ b/apps/desktop/src/ipc/DesktopIpc.test.ts @@ -63,5 +63,5 @@ it.effect("answers only the main window's top frame", () => appSubframe: ["rejected", undefined], previewGuest: ["rejected", undefined], }); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 9ed02db904..990282e50e 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -31,15 +31,18 @@ import { getLocalEnvironmentBearerToken, getSystemLocale, getPreferredSystemLanguages, + getPrimaryPasteEnabled, getWindowFullscreenState, openExternal, readMedia, + restartAudioService, openSystemSettings, checkSystemPermission, pasteAsText, probeRemoteEditors, revealWindow, pickFolder, + toLocalBackendPath, pickProjectFavicon, pickThemeFiles, setTheme, @@ -89,6 +92,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handleSync(getAppBranding); yield* ipc.handleSync(getSystemLocale); yield* ipc.handleSync(getPreferredSystemLanguages); + yield* ipc.handleSync(getPrimaryPasteEnabled); yield* ipc.handleSync(getWindowFullscreenState); yield* ipc.handleSync(getLocalEnvironmentBootstraps); yield* ipc.handleSync(getLocalEnvironmentEnabled); @@ -96,6 +100,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); yield* ipc.handle(getConnectionCatalog); @@ -124,6 +129,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(setWslOnly); yield* ipc.handle(pickFolder); + yield* ipc.handle(toLocalBackendPath); yield* ipc.handle(pickProjectFavicon); yield* ipc.handle(pickThemeFiles); yield* ipc.handle(setTheme); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 694336189b..e2c24dc5a9 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -1,6 +1,7 @@ // apps/desktop/src/ipc/channels.ts // names desktop bridge channels export const PICK_FOLDER_CHANNEL = "desktop:pick-folder"; +export const TO_LOCAL_BACKEND_PATH_CHANNEL = "desktop:to-local-backend-path"; export const SET_NOTIFICATION_BADGE_CHANNEL = "desktop:set-notification-badge"; export const PICK_PROJECT_FAVICON_CHANNEL = "desktop:pick-project-favicon"; export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files"; @@ -38,6 +39,7 @@ export const CLI_COMMAND_ADD_TO_PATH_CHANNEL = "desktop:cli-command-add-to-path" export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding"; export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale"; export const GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL = "desktop:get-preferred-system-languages"; +export const GET_PRIMARY_PASTE_ENABLED_CHANNEL = "desktop:get-primary-paste-enabled"; export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps"; export const GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:get-local-environment-enabled"; export const SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:set-local-environment-enabled"; @@ -77,6 +79,7 @@ export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webvie export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate"; export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back"; export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward"; +export const PREVIEW_STOP_LOADING_CHANNEL = "desktop:preview-stop-loading"; export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh"; export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in"; export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out"; @@ -85,7 +88,10 @@ export const PREVIEW_SET_ZOOM_FACTOR_CHANNEL = "desktop:preview-set-zoom-factor" export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload"; export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme"; export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted"; +export const PREVIEW_FIND_IN_PAGE_CHANNEL = "desktop:preview-find-in-page"; +export const PREVIEW_STOP_FIND_IN_PAGE_CHANNEL = "desktop:preview-stop-find-in-page"; export const PREVIEW_SET_SHOWN_CHANNEL = "desktop:preview-set-shown"; +export const PREVIEW_SET_CAPTURE_DRAWN_CHANNEL = "desktop:preview-set-capture-drawn"; export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools"; export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies"; export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache"; @@ -109,6 +115,7 @@ export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save"; export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change"; export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event"; export const PREVIEW_OPEN_LINK_CHANNEL = "desktop:preview-open-link"; +export const PREVIEW_FIND_RESULT_CHANNEL = "desktop:preview-find-result"; export const MAC_PERMISSION_HELPER_CHANNEL = "desktop:mac-permission-helper"; @@ -123,3 +130,5 @@ export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider- export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback"; export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage"; export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage"; + +export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 98a0aab831..757e1e463f 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -5,6 +5,7 @@ import { DesktopPreviewPickElementInputSchema, DesktopPreviewArtifactInputSchema, DesktopPreviewConfigInputSchema, + DesktopPreviewFindInPageInputSchema, DesktopPreviewNavigateInputSchema, DesktopPreviewRecordingArtifactSchema, DesktopPreviewRecordingSaveInputSchema, @@ -12,6 +13,7 @@ import { DesktopPreviewScreenshotArtifactSchema, DesktopPreviewSetAudioMutedInputSchema, DesktopPreviewSetShownInputSchema, + DesktopPreviewSetCaptureDrawnInputSchema, DesktopPreviewSetColorSchemeInputSchema, DesktopPreviewSetZoomFactorInputSchema, BrowserImportResult, @@ -59,6 +61,9 @@ export const installPreviewEventForwarding = Effect.fn( yield* manager.subscribeOpenLinks((event) => electronWindow.sendAll(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, event), ); + yield* manager.subscribeFindResults((event) => + electronWindow.sendAll(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, event), + ); }); const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ @@ -116,6 +121,21 @@ const navigate = DesktopIpc.makeIpcMethod({ }), }); +const findInPage = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_FIND_IN_PAGE_CHANNEL, + payload: DesktopPreviewFindInPageInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.findInPage")(function* ({ + tabId, + text, + forward, + newSession, + }) { + const manager = yield* PreviewManager.PreviewManager; + yield* manager.findInPage(tabId, text, { forward, newSession }); + }), +}); + const tabMethod = ( channel: string, name: string, @@ -149,6 +169,11 @@ const refresh = tabMethod( "desktop.ipc.preview.refresh", (manager, tabId) => manager.refresh(tabId), ); +const stopLoading = tabMethod( + IpcChannels.PREVIEW_STOP_LOADING_CHANNEL, + "desktop.ipc.preview.stopLoading", + (manager, tabId) => manager.stopLoading(tabId), +); const zoomIn = tabMethod( IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, "desktop.ipc.preview.zoomIn", @@ -169,6 +194,11 @@ const hardReload = tabMethod( "desktop.ipc.preview.hardReload", (manager, tabId) => manager.hardReload(tabId), ); +const stopFindInPage = tabMethod( + IpcChannels.PREVIEW_STOP_FIND_IN_PAGE_CHANNEL, + "desktop.ipc.preview.stopFindInPage", + (manager, tabId) => manager.stopFindInPage(tabId), +); const setZoomFactor = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_ZOOM_FACTOR_CHANNEL, payload: DesktopPreviewSetZoomFactorInputSchema, @@ -205,6 +235,15 @@ const setShown = DesktopIpc.makeIpcMethod({ yield* manager.setShown(tabId, shown); }), }); +const setCaptureDrawn = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL, + payload: DesktopPreviewSetCaptureDrawnInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.setCaptureDrawn")(function* ({ tabId, drawn }) { + const manager = yield* PreviewManager.PreviewManager; + yield* manager.setCaptureDrawn(tabId, drawn); + }), +}); const openDevTools = tabMethod( IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, "desktop.ipc.preview.openDevTools", @@ -448,14 +487,18 @@ export const methods = [ goBack, goForward, refresh, + stopLoading, zoomIn, zoomOut, resetZoom, hardReload, + findInPage, + stopFindInPage, setColorScheme, setZoomFactor, setAudioMuted, setShown, + setCaptureDrawn, openDevTools, clearCookies, clearCache, diff --git a/apps/desktop/src/ipc/methods/providerAuth.ts b/apps/desktop/src/ipc/methods/providerAuth.ts index fbde6a409f..d7f432815d 100644 --- a/apps/desktop/src/ipc/methods/providerAuth.ts +++ b/apps/desktop/src/ipc/methods/providerAuth.ts @@ -23,8 +23,13 @@ export const receiveProviderAuthCallback = DesktopIpc.makeIpcMethod({ const context = yield* Effect.context(); const runPromise = Effect.runPromiseWith(context); const callbackUrl = yield* Effect.tryPromise({ - try: () => - receiveCodexAuthCallback(authorizationUrl, (url) => runPromise(shell.openExternal(url))), + try: (signal) => + receiveCodexAuthCallback( + authorizationUrl, + (url) => runPromise(shell.openExternal(url)), + undefined, + signal, + ), catch: () => new CodexAuthCallbackError({ detail: diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index 4a6004448d..fe9ba342a7 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -2,6 +2,8 @@ // checks desktop window and environment bridge behavior import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts"; +import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -24,6 +26,7 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import { @@ -31,6 +34,7 @@ import { pickProjectFavicon, probeRemoteEditors, syncHtmlFullscreen, + toLocalBackendPath, } from "./window.ts"; const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = { @@ -180,6 +184,47 @@ describe("getLocalEnvironmentBootstraps", () => { }); }); +describe("toLocalBackendPath", () => { + const { runningDistro: _, ...windowsConfig } = readyWslConfig; + it.effect("converts paths through wslpath only for backends running in WSL", () => + Effect.gen(function* () { + const convert = (backendId: string, path = "C:\\Users\\me\\project") => + toLocalBackendPath.handler({ backendId, path }); + assert.strictEqual(yield* convert("primary"), "C:\\Users\\me\\project"); + assert.strictEqual(yield* convert("wsl:default"), "/drives/c/Users/me/project"); + assert.strictEqual(yield* convert("wsl:missing"), null); + assert.strictEqual( + yield* convert("wsl:default", "\\\\wsl.localhost\\ubuntu\\home\\me\\repo"), + "/home/me/repo", + ); + assert.strictEqual(yield* convert("wsl:default", "\\\\wsl$\\Debian\\home\\me\\repo"), null); + assert.strictEqual( + yield* convert("primary", "\\\\wsl$\\Debian\\home\\me\\repo"), + "\\\\wsl$\\Debian\\home\\me\\repo", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + DesktopBackendPool.layerTest([ + { + ...defaultWslInstance, + id: DesktopBackendManager.BackendInstanceId("primary"), + currentConfig: Effect.succeedSome(windowsConfig), + }, + defaultWslInstance, + ]), + DesktopWslEnvironment.layerTest({ + windowsToWslPath: (distro, windowsPath) => + distro === "Ubuntu" && windowsPath === "C:\\Users\\me\\project" + ? Option.some("/drives/c/Users/me/project") + : Option.none(), + }), + ), + ), + ), + ); +}); + describe("readMedia", () => { it.effect("reads http(s) media only for the main window", () => Effect.gen(function* () { @@ -417,3 +462,108 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( assert.include(editors, "webstorm"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + +describe("probeRemoteEditors PATH scan", () => { + const platform = HostProcess.Platform.defaultValue(); + const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command); + + const makeFakePath = Effect.fnUntraced(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-probe-path-" }); + const dirs = ["a", "b", "c", "d"].map((name) => path.join(root, name)); + for (const dir of dirs) yield* fs.makeDirectory(dir, { recursive: true }); + // Launchers in different PATH directories, deliberately not in REMOTE_CAPABLE_EDITOR_IDS order. + for (const [dir, command] of [ + [dirs[2]!, "webstorm"], + [dirs[0]!, "cursor"], + [dirs[3]!, "code"], + [dirs[1]!, "zeditor"], + ] as const) { + const file = path.join(dir, launcherName(command)); + yield* fs.writeFileString(file, "#!/bin/sh\n"); + if (platform !== "win32") yield* fs.chmod(file, 0o755); + } + return { + root, + env: { + HOME: root, + USERPROFILE: root, + PATH: dirs.join(platform === "win32" ? ";" : ":"), + PATHEXT: ".COM;.EXE;.BAT;.CMD", + }, + }; + }); + + const countingFileSystem = (counter: { stat: number; reads: Map }) => + Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return FileSystem.FileSystem.of({ + ...fs, + stat: (target) => { + counter.stat += 1; + return fs.stat(target); + }, + readDirectory: (target, options) => { + counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1); + return fs.readDirectory(target, options); + }, + }); + }), + ).pipe(Layer.provideMerge(NodeServices.layer)); + + const serialReference = (env: Record) => + Effect.gen(function* () { + const available: Array = []; + for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) { + const editor = EDITORS.find((candidate) => candidate.id === editorId); + if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) { + available.push(editorId); + } + } + return available; + }); + + it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () => + Effect.gen(function* () { + const { env: baseEnv } = yield* makeFakePath(); + const delimiter = platform === "win32" ? ";" : ":"; + const uncachedCounter = { stat: 0, reads: new Map() }; + const cachedCounter = { stat: 0, reads: new Map() }; + const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; + const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; + const uncached = yield* serialReference(uncachedEnv).pipe( + Effect.provide(countingFileSystem(uncachedCounter)), + ); + const cached = yield* probeRemoteEditors + .handler(undefined) + .pipe( + Effect.provideService(HostProcess.Environment, cachedEnv), + Effect.provideService(HostProcess.Platform, platform), + Effect.provide(countingFileSystem(cachedCounter)), + ); + // The host can add editors from app folders the fixture can't redirect (e.g. /Applications). + const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"]; + assert.deepStrictEqual( + uncached.filter((id) => fixtureEditors.includes(id)), + fixtureEditors, + ); + assert.deepStrictEqual(cached, uncached); + assert.isAbove(uncachedCounter.stat, 0); + // On every platform the probe lists each PATH directory at most once. Only PATH entries count: + // resolveEditorCommand also reads app folders such as /Applications on macOS. + const pathReads = cachedEnv.PATH.split(delimiter) + .filter((entry) => entry.length > 0) + .map((entry) => cachedCounter.reads.get(entry) ?? 0); + assert.isAbove(Math.max(...pathReads), 0); + assert.isAtMost(Math.max(...pathReads), 1); + // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor; + // elsewhere there is no PATHEXT, so the stat count is about the same either way. + if (platform === "win32") { + assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 5c309d60f0..29914e7a7b 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -2,6 +2,7 @@ // handles desktop window and environment bridge operations import { ContextMenuItemSchema, + ContextMenuSource, DesktopAppBrandingSchema, DesktopEnvironmentBootstrapSchema, DesktopMediaReadSchema, @@ -18,6 +19,7 @@ import { } from "@t3tools/contracts"; import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon"; import { resolveEditorCommand } from "@t3tools/shared/editor"; +import { withPathDirectoryListings } from "@t3tools/shared/shell"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -26,13 +28,16 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts"; +import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts"; import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as DesktopPrimaryPaste from "../../app/DesktopPrimaryPaste.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronApp from "../../electron/ElectronApp.ts"; +import * as ElectronAudio from "../../electron/ElectronAudio.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; import * as ElectronMenu from "../../electron/ElectronMenu.ts"; import * as ElectronShell from "../../electron/ElectronShell.ts"; @@ -57,6 +62,7 @@ const ContextMenuPosition = Schema.Struct({ const ContextMenuInput = Schema.Struct({ items: Schema.Array(ContextMenuItemSchema), position: Schema.optionalKey(ContextMenuPosition), + source: Schema.optionalKey(ContextMenuSource), }); function toWebSocketBaseUrl(httpBaseUrl: URL): string { @@ -83,6 +89,15 @@ export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({ }), }); +export const getPrimaryPasteEnabled = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.GET_PRIMARY_PASTE_ENABLED_CHANNEL, + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.window.getPrimaryPasteEnabled")(function* () { + const primaryPaste = yield* DesktopPrimaryPaste.DesktopPrimaryPaste; + return primaryPaste.enabled; + }), +}); + export const getPreferredSystemLanguages = DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL, result: Schema.Array(Schema.String), @@ -171,6 +186,20 @@ export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({ }), }); +// Ask the distro: its automount root is configurable, so /mnt/ is only the default. +const windowsPathToWsl = Effect.fn("desktop.ipc.window.windowsPathToWsl")(function* ( + distro: string | null, + windowsPath: string, +) { + const linuxUncPath = wslUncPathToLinuxPath(windowsPath); + if (linuxUncPath !== null) return Option.some(linuxUncPath); + const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; + return yield* wslEnvironment.windowsToWslPath( + extractDistroFromUncPath(windowsPath) ?? distro, + windowsPath, + ); +}); + export const pickFolder = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PICK_FOLDER_CHANNEL, payload: Schema.UndefinedOr(PickFolderOptionsSchema), @@ -217,20 +246,29 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ if (!useWsl) { return selectedPath.value; } - - const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value); - if (linuxUncPath !== null) { - return linuxUncPath; - } - - const converted = yield* wslEnvironment.windowsToWslPath( - extractDistroFromUncPath(selectedPath.value) ?? wslDistro, - selectedPath.value, - ); + const converted = yield* windowsPathToWsl(wslDistro, selectedPath.value); return Option.getOrElse(converted, () => selectedPath.value); }), }); +export const toLocalBackendPath = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL, + payload: Schema.Struct({ backendId: Schema.String, path: Schema.String }), + result: Schema.NullOr(Schema.String), + handler: Effect.fn("desktop.ipc.window.toLocalBackendPath")(function* ({ backendId, path }) { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const instance = yield* pool.get(DesktopBackendManager.BackendInstanceId(backendId)); + if (Option.isNone(instance)) return null; + const config = yield* instance.value.currentConfig; + if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) return null; + const { runningDistro } = config.value; + if (runningDistro === undefined) return path; + const uncDistro = extractDistroFromUncPath(path); + if (uncDistro !== null && uncDistro.toLowerCase() !== runningDistro.toLowerCase()) return null; + return Option.getOrNull(yield* windowsPathToWsl(runningDistro, path)); + }), +}); + export const pickProjectFavicon = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL, payload: Schema.UndefinedOr(Schema.String), @@ -283,6 +321,7 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({ window: window.value, items: input.items, position: Option.fromNullishOr(input.position), + source: Option.fromNullishOr(input.source), }); return Option.getOrNull(selectedItemId); }), @@ -367,20 +406,26 @@ export const openSystemSettings = DesktopIpc.makeIpcMethod({ }), }); +const REMOTE_EDITOR_PROBE_CONCURRENCY = 8; + export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, payload: Schema.Undefined, result: Schema.Array(EditorId), handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () { - const available: Array = []; const env = yield* HostProcess.Environment; - for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) { - const editor = EDITORS.find((editor) => editor.id === editorId); - if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) { - available.push(editorId); - } - } - return available; + // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows. + const resolved = yield* Effect.forEach( + REMOTE_CAPABLE_EDITOR_IDS, + (editorId) => { + const editor = EDITORS.find((editor) => editor.id === editorId); + return editor + ? resolveEditorCommand(editor, env).pipe(Effect.map(Option.isSome)) + : Effect.succeed(false); + }, + { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY }, + ).pipe(withPathDirectoryListings); + return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]); }), }); @@ -528,3 +573,10 @@ export const checkSystemPermission = DesktopIpc.makeIpcMethod({ return yield* Effect.promise(check); }), }); + +export const restartAudioService = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL, + payload: Schema.Void, + result: Schema.Boolean, + handler: ElectronAudio.restart, +}); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9887c30a8d..696c47805f 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1,10 +1,10 @@ import * as FinckeAppImageMounts from "./fincke/AppImageMounts.ts"; import * as FinckeFreshProfile from "./fincke/FreshProfile.ts"; import * as MacPermissions from "./permissions/MacPermissions.ts"; +import { handleStdioError } from "./app/stdioErrors.ts"; + for (const stream of [process.stdout, process.stderr]) { - stream.on("error", (err: NodeJS.ErrnoException) => { - if (err.code !== "EPIPE") throw err; - }); + stream.on("error", handleStdioError); } if (process.env.APPIMAGE) FinckeAppImageMounts.dropStaleAppImageMounts(process.env); @@ -43,6 +43,7 @@ import * as DesktopInstance from "./app/DesktopInstance.ts"; import * as DesktopCliCommand from "./app/DesktopCliCommand.ts"; import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts"; import * as DesktopAssets from "./app/DesktopAssets.ts"; +import * as DesktopPrimaryPaste from "./app/DesktopPrimaryPaste.ts"; import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts"; import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts"; import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts"; @@ -130,6 +131,7 @@ const layerDesktopFoundation = Layer.mergeAll( DesktopClientSettings.layer, DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)), DesktopAssets.layer, + DesktopPrimaryPaste.layer, DesktopObservability.layer, DesktopRendererHistory.layer, ).pipe(Layer.provideMerge(layerDesktopEnvironment)); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index db9c2ea6fe..9e4349356f 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -3,6 +3,7 @@ import type { DesktopBridge, DesktopPreviewAnnotationVoiceEvent, + DesktopPreviewFindResultEvent, DesktopPreviewOpenLinkEvent, DesktopPreviewPointerEvent, DesktopPreviewRecordingInputEvent, @@ -68,6 +69,23 @@ const syncHtmlFullscreen = () => { syncHtmlFullscreen(); document.addEventListener("fullscreenchange", syncHtmlFullscreen); +let primaryPasteEnabled = true; +try { + primaryPasteEnabled = + ipcRenderer.sendSync(IpcChannels.GET_PRIMARY_PASTE_ENABLED_CHANNEL) !== false; +} catch {} + +if (!primaryPasteEnabled) { + // Blink pastes the PRIMARY selection on a middle-click mouseup unless it is default-prevented. + window.addEventListener( + "mouseup", + (event) => { + if (event.button === 1) event.preventDefault(); + }, + true, + ); +} + contextBridge.exposeInMainWorld("desktopBridge", { getAppBranding: () => { const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL); @@ -78,6 +96,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { }, getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, + restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL), setNotificationBadge: (badge) => ipcRenderer.invoke(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, badge), onNotificationBadgeClear: (listener) => { @@ -96,6 +115,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { return () => ipcRenderer.removeListener(IpcChannels.TRACKPAD_SCROLL_END_CHANNEL, handler); }, revealWindow: () => ipcRenderer.invoke(IpcChannels.REVEAL_WINDOW_CHANNEL), + getPrimaryPasteEnabled: () => primaryPasteEnabled, getSystemLocale: () => { const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL); return typeof result === "string" ? result : null; @@ -156,14 +176,17 @@ contextBridge.exposeInMainWorld("desktopBridge", { setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro), setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled), pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options), + toLocalBackendPath: (backendId, path) => + ipcRenderer.invoke(IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL, { backendId, path }), pickProjectFavicon: (initialPath) => ipcRenderer.invoke(IpcChannels.PICK_PROJECT_FAVICON_CHANNEL, initialPath), pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined), setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme), - showContextMenu: (items, position) => + showContextMenu: (items, position, source) => ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, { items, ...(position === undefined ? {} : { position }), + ...(source === undefined ? {} : { source }), }), receiveProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url), @@ -307,6 +330,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }), goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }), refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }), + stopLoading: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_STOP_LOADING_CHANNEL, { tabId }), zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }), zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }), resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }), @@ -317,8 +341,19 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }), setAudioMuted: (tabId, audioMuted) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, { tabId, audioMuted }), + findInPage: (tabId, text, { forward, newSession }) => + ipcRenderer.invoke(IpcChannels.PREVIEW_FIND_IN_PAGE_CHANNEL, { + tabId, + text, + forward, + newSession, + }), + stopFindInPage: (tabId) => + ipcRenderer.invoke(IpcChannels.PREVIEW_STOP_FIND_IN_PAGE_CHANNEL, { tabId }), setShown: (tabId, shown) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, { tabId, shown }), + setCaptureDrawn: (tabId, drawn) => + ipcRenderer.invoke(IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL, { tabId, drawn }), openDevTools: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }), listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL), @@ -417,5 +452,14 @@ contextBridge.exposeInMainWorld("desktopBridge", { return () => ipcRenderer.removeListener(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, wrappedListener); }, + onFindResult: (listener) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, findEvent: unknown) => { + if (typeof findEvent !== "object" || findEvent === null) return; + listener(findEvent as DesktopPreviewFindResultEvent); + }; + ipcRenderer.on(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, wrappedListener); + return () => + ipcRenderer.removeListener(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, wrappedListener); + }, }, } satisfies DesktopBridge); diff --git a/apps/desktop/src/preview-pick-preload.ts b/apps/desktop/src/preview-pick-preload.ts index 7c4f23e37f..3511f51132 100644 --- a/apps/desktop/src/preview-pick-preload.ts +++ b/apps/desktop/src/preview-pick-preload.ts @@ -1,6 +1,9 @@ import { ipcRenderer } from "electron"; -import { PASSKEY_BRIDGE_ARGUMENT } from "./preview/GuestProtocol.ts"; +import { + PASSKEY_BRIDGE_ARGUMENT, + PRIMARY_PASTE_DISABLED_ARGUMENT, +} from "./preview/GuestProtocol.ts"; import { installPasskeyBridge } from "./preview/PasskeyBridge.ts"; import "./preview/PickPreload.ts"; @@ -8,3 +11,14 @@ import "./preview/PickPreload.ts"; if (process.argv.includes(PASSKEY_BRIDGE_ARGUMENT)) { installPasskeyBridge((channel, publicKey) => ipcRenderer.invoke(channel, publicKey)); } + +if (process.argv.includes(PRIMARY_PASTE_DISABLED_ARGUMENT)) { + // Same guard as the app preload: Blink pastes PRIMARY on an uncancelled middle mouseup. + window.addEventListener( + "mouseup", + (event) => { + if (event.button === 1) event.preventDefault(); + }, + true, + ); +} diff --git a/apps/desktop/src/preview/AnnotationStroke.test.ts b/apps/desktop/src/preview/AnnotationStroke.test.ts new file mode 100644 index 0000000000..ad8a21c140 --- /dev/null +++ b/apps/desktop/src/preview/AnnotationStroke.test.ts @@ -0,0 +1,73 @@ +import type { PreviewAnnotationPoint } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + addStrokePoint, + openStrokePath, + startStroke, + strokeBounds, + STROKE_SEGMENTS_PER_PATH, +} from "./AnnotationStroke.ts"; + +// The Draw tool used to rebuild the whole path and rescan every point on each move. +const fullPath = (points: ReadonlyArray): string => { + let path = `M ${points[0]!.x} ${points[0]!.y}`; + for (let index = 1; index < points.length - 1; index += 1) { + const current = points[index]!; + const next = points[index + 1]!; + path += ` Q ${current.x} ${current.y} ${(current.x + next.x) / 2} ${(current.y + next.y) / 2}`; + } + const last = points[points.length - 1]!; + return `${path} L ${last.x} ${last.y}`; +}; + +const fullBounds = (points: ReadonlyArray, width: number) => { + const xs = points.map((point) => point.x); + const ys = points.map((point) => point.y); + const padding = width + 3; + const left = Math.min(...xs) - padding; + const top = Math.min(...ys) - padding; + const right = Math.max(...xs) + padding; + const bottom = Math.max(...ys) + padding; + return { x: left, y: top, width: right - left, height: bottom - top }; +}; + +// Each later path starts with a move to where the previous one ended. +const joinPaths = (paths: ReadonlyArray): string => + paths + .map((path, index) => { + if (index === 0) return path; + const resume = path.match(/^M (\S+ \S+)/)![1]!; + expect(paths[index - 1]!.endsWith(` ${resume}`)).toBe(true); + return path.slice(`M ${resume}`.length); + }) + .join(""); + +describe("stroke geometry", () => { + it("draws the same curve and bounds as a full rescan at every length", () => { + const points = Array.from({ length: STROKE_SEGMENTS_PER_PATH * 2 + 30 }, (_, index) => ({ + x: index * 3 + ((index * 7) % 11), + y: 200 + ((index * 13) % 29) - index, + })); + const geometry = startStroke(points[0]!); + const closedPaths: string[] = []; + for (let index = 1; index < points.length; index += 1) { + const closedPath = addStrokePoint(geometry, points[index]!); + if (closedPath !== null) closedPaths.push(closedPath); + const drawn = points.slice(0, index + 1); + expect(joinPaths([...closedPaths, openStrokePath(geometry)])).toBe(fullPath(drawn)); + expect(strokeBounds(geometry, 4)).toEqual(fullBounds(drawn, 4)); + } + expect(closedPaths).toHaveLength(2); + expect(geometry.points).toEqual(points); + }); + + it("keeps the rewritten path short for a stroke past the engine's argument limit", () => { + const geometry = startStroke({ x: 0, y: 0 }); + for (let index = 1; index < 250_000; index += 1) { + addStrokePoint(geometry, { x: index % 800, y: index % 600 }); + } + expect(strokeBounds(geometry, 4)).toEqual({ x: -7, y: -7, width: 813, height: 613 }); + expect(openStrokePath(geometry).length).toBeLessThan(STROKE_SEGMENTS_PER_PATH * 40); + }); +}); diff --git a/apps/desktop/src/preview/AnnotationStroke.ts b/apps/desktop/src/preview/AnnotationStroke.ts new file mode 100644 index 0000000000..66510fc0b7 --- /dev/null +++ b/apps/desktop/src/preview/AnnotationStroke.ts @@ -0,0 +1,69 @@ +import type { PreviewAnnotationPoint, PreviewAnnotationRect } from "@t3tools/contracts"; + +// Setting a path's `d` makes Chromium parse the whole string again, so a long +// stroke is drawn as a run of paths and only the last one is rewritten per move. +export const STROKE_SEGMENTS_PER_PATH = 100; + +export interface StrokeGeometry { + readonly points: PreviewAnnotationPoint[]; + minX: number; + minY: number; + maxX: number; + maxY: number; + // The curve through the newest point is still open: where it ends depends on + // the point after it. This holds only the settled segments of the last path. + openPath: string; + openSegments: number; +} + +export function startStroke(point: PreviewAnnotationPoint): StrokeGeometry { + return { + points: [point], + minX: point.x, + minY: point.y, + maxX: point.x, + maxY: point.y, + openPath: `M ${point.x} ${point.y}`, + openSegments: 0, + }; +} + +// Returns the final `d` of the path this point filled, if it filled one. +export function addStrokePoint( + geometry: StrokeGeometry, + point: PreviewAnnotationPoint, +): string | null { + const previous = geometry.points[geometry.points.length - 1]!; + let closedPath: string | null = null; + if (geometry.points.length > 1) { + const midX = (previous.x + point.x) / 2; + const midY = (previous.y + point.y) / 2; + geometry.openPath += ` Q ${previous.x} ${previous.y} ${midX} ${midY}`; + geometry.openSegments += 1; + if (geometry.openSegments === STROKE_SEGMENTS_PER_PATH) { + closedPath = geometry.openPath; + geometry.openPath = `M ${midX} ${midY}`; + geometry.openSegments = 0; + } + } + geometry.points.push(point); + geometry.minX = Math.min(geometry.minX, point.x); + geometry.minY = Math.min(geometry.minY, point.y); + geometry.maxX = Math.max(geometry.maxX, point.x); + geometry.maxY = Math.max(geometry.maxY, point.y); + return closedPath; +} + +export function openStrokePath(geometry: StrokeGeometry): string { + const last = geometry.points[geometry.points.length - 1]!; + return `${geometry.openPath} L ${last.x} ${last.y}`; +} + +export function strokeBounds(geometry: StrokeGeometry, width: number): PreviewAnnotationRect { + const padding = width + 3; + const left = geometry.minX - padding; + const top = geometry.minY - padding; + const right = geometry.maxX + padding; + const bottom = geometry.maxY + padding; + return { x: left, y: top, width: right - left, height: bottom - top }; +} diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts index 9528cd5d2e..484ba6f935 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts @@ -33,6 +33,7 @@ const layerRejectedBeforeSession = Layer.succeed( isPartition: () => false, getSession: () => Effect.die("getSession must not be reached"), clearCookies: () => Effect.die("clearCookies must not be reached"), + cookiesCleared: () => Effect.die("cookiesCleared must not be reached"), clearCache: () => Effect.die("clearCache must not be reached"), }), ); @@ -88,7 +89,7 @@ describe("BrowserImport.importCookies", () => { assert.instanceOf(error, BrowserImport.BrowserImportFailedError); assert.equal(error.reason, "unknownSourceProfile"); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect.skipIf(!symlinksSupported)( @@ -113,7 +114,7 @@ describe("BrowserImport.importCookies", () => { assert.instanceOf(error, BrowserImport.BrowserImportFailedError); assert.equal(error.reason, "browserRunning"); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts index e5aa05f268..eb4dd3143e 100644 --- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts @@ -134,7 +134,7 @@ describe("readChromiumCookieDatabase", () => { const partitioned = yield* readChromiumCookieDatabase(filename, keys, "linux"); expect(partitioned.cookies).toEqual([]); expect(partitioned.undecryptable).toBe(1); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("reads plaintext, encrypted, and genuinely empty cookie values", () => @@ -186,7 +186,7 @@ describe("readChromiumCookieDatabase", () => { { name: "encrypted", value: "stored encrypted" }, { name: "empty", value: "" }, ]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("enforces domain binding only for schema 24 and newer", () => @@ -227,7 +227,7 @@ describe("readChromiumCookieDatabase", () => { ]); expect(result.undecryptable).toBe(2); expect(result.undecryptableHosts).toEqual(["wrong.example", "short.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("decrypts mixed v10 and v11 cookies with their respective keys", () => @@ -273,7 +273,7 @@ describe("readChromiumCookieDatabase", () => { ]); expect(v10Only.undecryptable).toBe(1); expect(v10Only.undecryptableHosts).toEqual(["v11.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("recovers records written with the empty-passphrase key", () => @@ -320,7 +320,7 @@ describe("readChromiumCookieDatabase", () => { const noV11 = yield* readChromiumCookieDatabase(filename, { cbcV10, cbcEmpty }, "linux"); expect(noV11.cookies.map(({ name }) => name)).toEqual(["empty-v10"]); expect(noV11.undecryptableHosts).toEqual(["ev11.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("treats unversioned encrypted values as legacy plaintext on macOS and Linux", () => @@ -355,6 +355,29 @@ describe("readChromiumCookieDatabase", () => { expect(mac.undecryptable).toBe(0); expect(linux.cookies[0]?.value).toBe("legacy cleartext"); expect(linux.undecryptable).toBe(0); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("reads a cookie database the browser has emptied as having no cookies", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-chromium-cookies-", + }); + const filename = `${directory}/Cookies`; + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`create table scratch (id integer)`; + yield* sql`drop table scratch`; + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename }))); + + const result = yield* readChromiumCookieDatabase( + filename, + { cbcV10: Buffer.from("0123456789abcdef") }, + "darwin", + ); + + expect(result).toEqual({ cookies: [], undecryptable: 0, undecryptableHosts: [] }); }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); @@ -409,6 +432,6 @@ describe("readChromiumCookieDatabase", () => { expect(chips.cookies.map(({ name }) => name)).toEqual(["plain"]); expect(chips.undecryptable).toBe(1); expect(chips.undecryptableHosts).toEqual(["partitioned.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts index 63fef9fb3c..91cbfa03aa 100644 --- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts +++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts @@ -181,6 +181,10 @@ export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiu function* (snapshotPath: string, keys: ChromiumKeyMaterial, platform: NodeJS.Platform) { const result = yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + // Chromium razes a damaged jar to a file with no tables and rebuilds it on its next write. + const tables = + yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`; + if (tables.length === 0) return { rows: [], schemaVersion: 0 }; const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe( Effect.flatMap(decodeSchemaVersion), Effect.map(([row]) => row.value), diff --git a/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts b/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts index 402397d3fd..ca0a86ceda 100644 --- a/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts +++ b/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts @@ -11,7 +11,7 @@ import { snapshotCookieDatabase } from "./CookieDatabase.ts"; const runNode = ( effect: Effect.Effect, -) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped); +) => effect.pipe(Effect.provide(NodeServices.layer)); describe("snapshotCookieDatabase", () => { it.effect("includes committed WAL data in one consistent database", () => diff --git a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts index be41318fa0..33e32ec030 100644 --- a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts @@ -78,7 +78,7 @@ const writeFirefoxCookieDatabase = Effect.fnUntraced(function* ( }); const run = (effect: Effect.Effect) => - effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped); + effect.pipe(Effect.provide(NodeServices.layer)); describe("readFirefoxCookies", () => { it.effect("converts millisecond expiries from schema 16 and newer", () => diff --git a/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts b/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts index 8358088bc1..8ef376e488 100644 --- a/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts +++ b/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts @@ -64,6 +64,6 @@ it.layer(NodeServices.layer)("Linux browser secret path", (it) => { assert.isUndefined(yield* resolve(false, "win32")); yield* fileSystem.remove(staged); assert.isUndefined(yield* resolve(false)); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts b/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts index 7e92334c95..f82f2319ba 100644 --- a/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts @@ -240,7 +240,7 @@ describe("safariAccessDenied", () => { yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b])); assert.isFalse(yield* safariAccessDenied(jar)); assert.isFalse(yield* safariAccessDenied(`${directory}/absent.binarycookies`)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts b/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts index 3b33f872d1..dc225b04ba 100644 --- a/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts +++ b/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts @@ -39,7 +39,7 @@ it.effect("detects Safari access becoming available without reading or importing assert.isTrue(yield* Effect.promise(check)); yield* fs.remove(jar); assert.isFalse(yield* Effect.promise(check)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("recognizes access when cookies exist only in a named Safari profile", () => @@ -55,5 +55,5 @@ it.effect("recognizes access when cookies exist only in a named Safari profile", yield* fs.makeDirectory(directory, { recursive: true }); yield* fs.writeFileString(`${directory}/Cookies.binarycookies`, "not parsed"); assert.isTrue(yield* Effect.promise(check)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/apps/desktop/src/preview/BrowserImport/Sources.test.ts b/apps/desktop/src/preview/BrowserImport/Sources.test.ts index 720a57e64a..9b2c3cb26c 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.test.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.test.ts @@ -51,7 +51,7 @@ const run = ( E, FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner >, -) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped); +) => effect.pipe(Effect.provide(NodeServices.layer)); const writeCookieDatabase = (file: string, count: number) => Effect.sync(() => { diff --git a/apps/desktop/src/preview/BrowserImport/Sources.ts b/apps/desktop/src/preview/BrowserImport/Sources.ts index 20a35752ed..6ecd546a1a 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.ts @@ -345,6 +345,12 @@ const countProfileCookies = Effect.fnUntraced(function* ( if (database === undefined) return undefined; return yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + // readChromiumCookieDatabase imports a razed jar as empty; Firefox has no such reader guard. + if (definition.engine !== "firefox") { + const tables = + yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`; + if (tables.length === 0) return 0; + } const rows = definition.engine === "firefox" ? yield* sql`select count(*) as count from moz_cookies where originAttributes = ''` diff --git a/apps/desktop/src/preview/BrowserSession.test.ts b/apps/desktop/src/preview/BrowserSession.test.ts index e68e52961f..9a9be6213c 100644 --- a/apps/desktop/src/preview/BrowserSession.test.ts +++ b/apps/desktop/src/preview/BrowserSession.test.ts @@ -1,8 +1,11 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as NodeEvents from "node:events"; import { beforeEach, vi } from "vite-plus/test"; const { fromPartition, sessions } = vi.hoisted(() => ({ @@ -12,6 +15,8 @@ const { fromPartition, sessions } = vi.hoisted(() => ({ { readonly clearCache: ReturnType; readonly clearStorageData: ReturnType; + readonly closeAllConnections: ReturnType; + readonly storagePath: string | null; readonly getUserAgent: ReturnType string>>; readonly setPermissionRequestHandler: ReturnType; readonly setPermissionCheckHandler: ReturnType; @@ -21,44 +26,125 @@ const { fromPartition, sessions } = vi.hoisted(() => ({ >(), })); +const storage = vi.hoisted(() => ({ root: "" })); + const { fromWebContents } = vi.hoisted(() => ({ fromWebContents: vi.fn<(webContents: unknown) => unknown>(() => null), })); +const { appListeners } = vi.hoisted(() => ({ + appListeners: new Map void>(), +})); + vi.mock("electron", () => ({ + app: { + on: (eventName: string, listener: (...args: unknown[]) => void) => { + appListeners.set(eventName, listener); + }, + removeListener: (eventName: string) => { + appListeners.delete(eventName); + }, + }, BrowserWindow: { fromWebContents }, session: { fromPartition, }, })); +import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; import * as BrowserSession from "./BrowserSession.ts"; -const { showMessageBox } = vi.hoisted(() => ({ +const { showMessageBox, showErrorBox } = vi.hoisted(() => ({ showMessageBox: vi.fn< - (options: Electron.MessageBoxOptions, owner?: Electron.BrowserWindow) => number + ( + options: Electron.MessageBoxOptions, + owner?: Electron.BrowserWindow, + ) => number | Promise >(() => 1), + showErrorBox: vi.fn<(title: string, content: string) => void>(), })); const layerDialog = Layer.succeed(ElectronDialog.ElectronDialog, { pickFolder: () => Effect.die("unused"), pickFiles: () => Effect.die("unused"), showMessageBox: (options, owner) => - Effect.sync(() => ({ response: showMessageBox(options, owner), checkboxChecked: false })), - showErrorBox: () => Effect.void, + Effect.promise(async () => ({ + response: await showMessageBox(options, owner), + checkboxChecked: false, + })), + showErrorBox: (title, content) => Effect.sync(() => showErrorBox(title, content)), }); const layer = BrowserSession.layer.pipe( - Layer.provide(Layer.merge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), layerDialog)), + Layer.provide( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerDialog, ElectronApp.layer), + ), ); +const selfSignedCertificate = { + fingerprint: "sha256/self-signed", + subjectName: "localhost", + issuerName: "localhost", + validStart: 1_735_776_000, + validExpiry: 1_807_056_000, +} as Electron.Certificate; + +/** Raises Electron's `certificate-error` for a preview guest in `browserSession`. */ +const certificateError = ( + browserSession: unknown, + input: { + readonly url: string; + readonly certificate?: Electron.Certificate; + readonly isMainFrame?: boolean; + }, +) => { + const listener = appListeners.get("certificate-error"); + assert.isDefined(listener, "preview sessions should handle certificate errors"); + const guest = Object.assign(new NodeEvents.EventEmitter(), { + session: browserSession, + hostWebContents: null, + isDestroyed: () => false, + }); + const event = { preventDefault: vi.fn() }; + const decision = Deferred.makeUnsafe(); + const callback = vi.fn((trusted: boolean) => { + Deferred.doneUnsafe(decision, Effect.succeed(trusted)); + }); + listener( + event, + guest, + input.url, + "net::ERR_CERT_AUTHORITY_INVALID", + input.certificate ?? selfSignedCertificate, + callback, + input.isMainFrame ?? true, + ); + return { guest, event, callback, trusted: Deferred.await(decision) }; +}; + +/** Answers the certificate prompt with its "Trust…" button. */ +const trustCertificateButton = (options: Electron.MessageBoxOptions): number => { + const index = (options.buttons ?? []).findIndex((label) => label.startsWith("Trust")); + assert.notStrictEqual(index, -1, "the certificate prompt should offer to trust"); + return index; +}; + describe("BrowserSession", () => { beforeEach(() => { sessions.clear(); + appListeners.clear(); + storage.root = ""; + showErrorBox.mockReset(); fromPartition.mockReset(); fromPartition.mockImplementation((partition: string) => { const browserSession = { clearCache: vi.fn(() => Promise.resolve()), clearStorageData: vi.fn(() => Promise.resolve()), + closeAllConnections: vi.fn(() => Promise.resolve()), + // Like Electron, only a `persist:` partition has storage on disk. + storagePath: + storage.root !== "" && partition.startsWith("persist:") + ? `${storage.root}/Partitions/${partition}` + : null, getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"), setPermissionRequestHandler: vi.fn(), setPermissionCheckHandler: vi.fn(), @@ -129,6 +215,8 @@ describe("BrowserSession", () => { const browserSession = { clearCache: vi.fn(() => Promise.resolve()), clearStorageData: vi.fn(() => Promise.resolve()), + closeAllConnections: vi.fn(() => Promise.resolve()), + storagePath: null, getUserAgent: vi.fn(() => userAgent), setPermissionRequestHandler: vi.fn(), setPermissionCheckHandler: vi.fn(), @@ -333,4 +421,236 @@ describe("BrowserSession", () => { assert.strictEqual(vi.mocked(other.clearStorageData).mock.calls.length, 0); }).pipe(Effect.provide(layer)), ); + + it.effect("asks before trusting an untrusted certificate and remembers the approval", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + + showMessageBox.mockReset(); + showMessageBox.mockImplementation(trustCertificateButton); + const first = certificateError(browserSession, { url: "https://localhost:18443/" }); + assert.strictEqual(first.event.preventDefault.mock.calls.length, 1); + assert.isTrue(yield* first.trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + + // The approval covers this origin, port, and certificate in this profile. + const again = certificateError(browserSession, { url: "https://localhost:18443/other" }); + assert.isTrue(yield* again.trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + // Its sockets reach the same TLS endpoint, and cannot ask on their own. + const socket = certificateError(browserSession, { + url: "wss://localhost:18443/hmr", + isMainFrame: false, + }); + assert.isTrue(yield* socket.trusted); + const otherSocket = certificateError(browserSession, { + url: "wss://localhost:18444/hmr", + isMainFrame: false, + }); + assert.isFalse(yield* otherSocket.trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + + showMessageBox.mockReset(); + showMessageBox.mockReturnValue(1); + const otherPort = certificateError(browserSession, { url: "https://localhost:18444/" }); + assert.isFalse(yield* otherPort.trusted); + const renewed = certificateError(browserSession, { + url: "https://localhost:18443/", + certificate: { ...selfSignedCertificate, fingerprint: "sha256/renewed" }, + }); + assert.isFalse(yield* renewed.trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 2); + + // A Session that is not a preview profile keeps Electron's denial. + const appSession = certificateError({}, { url: "https://localhost:18443/" }); + assert.strictEqual(appSession.event.preventDefault.mock.calls.length, 0); + assert.strictEqual(appSession.callback.mock.calls.length, 0); + }).pipe(Effect.provide(layer)), + ); + + it.effect("revokes certificate approvals when cookies are cleared, not the cache", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + const url = "https://localhost:18443/"; + + showMessageBox.mockReset(); + showMessageBox.mockImplementation(trustCertificateButton); + assert.isTrue(yield* certificateError(browserSession, { url }).trusted); + + yield* browserSessions.clearCache([partition]); + assert.isTrue(yield* certificateError(browserSession, { url }).trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + + // A failed storage clear still forgets the approvals the user asked to clear. + browserSession!.clearStorageData.mockRejectedValueOnce(new Error("disk busy")); + const failure = yield* browserSessions.clearCookies([partition]).pipe(Effect.flip); + assert.strictEqual(failure._tag, "BrowserSessionStorageClearError"); + showMessageBox.mockReset(); + showMessageBox.mockReturnValue(1); + assert.isFalse(yield* certificateError(browserSession, { url }).trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + }).pipe(Effect.provide(layer)), + ); + + it.effect("remembers approvals across restarts, but not incognito ones", () => + Effect.gen(function* () { + storage.root = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped(); + const url = "https://localhost:18443/"; + const approve = Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const persistent = yield* browserSessions.getPartition("scope-a"); + const incognito = yield* browserSessions.getPartition("scope-a", false); + yield* browserSessions.getSession("scope-a"); + yield* browserSessions.getSession("scope-a", false); + showMessageBox.mockReset(); + showMessageBox.mockImplementation(trustCertificateButton); + assert.isTrue(yield* certificateError(sessions.get(persistent), { url }).trusted); + assert.isTrue(yield* certificateError(sessions.get(incognito), { url }).trusted); + return { persistent, incognito }; + }); + const { persistent, incognito } = yield* approve.pipe(Effect.provide(layer)); + + // A restarted app gets fresh Session objects and reads approvals from disk. + sessions.clear(); + appListeners.clear(); + yield* Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + yield* browserSessions.getSession("scope-a"); + yield* browserSessions.getSession("scope-a", false); + showMessageBox.mockReset(); + showMessageBox.mockReturnValue(1); + assert.isTrue(yield* certificateError(sessions.get(persistent), { url }).trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 0); + assert.isFalse(yield* certificateError(sessions.get(incognito), { url }).trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("an answer to a prompt opened before cookies were cleared does not trust", () => + Effect.gen(function* () { + storage.root = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped(); + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + const url = "https://localhost:18443/"; + + const asked = yield* Deferred.make(); + let answer = () => {}; + const answered = new Promise((resolve) => { + answer = resolve; + }); + showMessageBox.mockReset(); + showMessageBox.mockImplementation((options) => { + Deferred.doneUnsafe(asked, Effect.void); + return answered.then(() => trustCertificateButton(options)); + }); + const pending = certificateError(browserSession, { url }); + yield* Deferred.await(asked); + yield* browserSessions.clearCookies([partition]); + answer(); + assert.isFalse(yield* pending.trusted); + + showMessageBox.mockReset(); + showMessageBox.mockReturnValue(1); + assert.isFalse(yield* certificateError(browserSession, { url }).trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + assert.isFalse( + yield* (yield* FileSystem.FileSystem).exists( + `${browserSession!.storagePath}/t3code-certificate-approvals.json`, + ), + ); + }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))), + ); + + it.effect("a tab that closes or navigates away dismisses its certificate prompt", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + const url = "https://localhost:18443/"; + + for (const leave of [ + (guest: NodeEvents.EventEmitter) => + guest.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }), + (guest: NodeEvents.EventEmitter) => guest.emit("destroyed"), + ]) { + showMessageBox.mockReset(); + // Answering "Trust" as the tab leaves must not approve the certificate. + showMessageBox.mockImplementation( + (options) => + new Promise((resolve) => + options.signal?.addEventListener("abort", () => + resolve(trustCertificateButton(options)), + ), + ), + ); + const pending = certificateError(browserSession, { url }); + pending.guest.emit("did-start-navigation", { isMainFrame: true, isSameDocument: true }); + leave(pending.guest); + assert.isFalse(yield* pending.trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + } + }).pipe(Effect.provide(layer)), + ); + + it.effect("does not trust a certificate whose approval cannot be saved", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + // A file where the profile directory should be makes every write fail. + const root = yield* fileSystem.makeTempDirectoryScoped(); + yield* fileSystem.writeFileString(`${root}/Partitions`, ""); + storage.root = root; + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + const url = "https://localhost:18443/"; + + showMessageBox.mockReset(); + showMessageBox.mockImplementation(trustCertificateButton); + assert.isFalse(yield* certificateError(browserSession, { url }).trusted); + assert.strictEqual(showErrorBox.mock.calls.length, 1); + // Nothing was trusted for this run either, so the next visit asks again. + showMessageBox.mockReset(); + showMessageBox.mockReturnValue(1); + assert.isFalse(yield* certificateError(browserSession, { url }).trusted); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))), + ); + + it.effect("clearing cookies deletes a saved approval even when none are loaded", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + storage.root = yield* fileSystem.makeTempDirectoryScoped(); + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + // What a clear whose removal failed leaves behind: memory forgot, the file did not. + const file = `${browserSession!.storagePath}/t3code-certificate-approvals.json`; + yield* fileSystem.makeDirectory(browserSession!.storagePath!, { recursive: true }); + yield* fileSystem.writeFileString( + file, + JSON.stringify([ + { + origin: "https://localhost:18443", + fingerprint: selfSignedCertificate.fingerprint, + error: "net::ERR_CERT_AUTHORITY_INVALID", + }, + ]), + ); + + yield* browserSessions.clearCookies([partition]); + assert.isFalse(yield* fileSystem.exists(file)); + }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))), + ); }); diff --git a/apps/desktop/src/preview/BrowserSession.ts b/apps/desktop/src/preview/BrowserSession.ts index b2523ba62b..7211e00f24 100644 --- a/apps/desktop/src/preview/BrowserSession.ts +++ b/apps/desktop/src/preview/BrowserSession.ts @@ -1,15 +1,23 @@ -import type { Session, WebContents } from "electron"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type { Certificate, Session, WebContents } from "electron"; import { BrowserWindow, session } from "electron"; import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; +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 Result from "effect/Result"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as SynchronizedRef from "effect/SynchronizedRef"; +import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; +import { DESKTOP_APP_NAME } from "../fincke/build.ts"; const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-"; /** Ephemeral partitions omit persist: but retain a product prefix so the webview gate recognizes them. */ @@ -73,6 +81,64 @@ const permissionOrigin = (rawUrl: string | undefined): string | null => { } }; +/** + * Certificate errors a user may accept for a preview page, with the reason the + * prompt shows. Every other error keeps Electron's denial. + */ +const OVERRIDABLE_CERTIFICATE_ERRORS: ReadonlyMap = new Map([ + ["net::ERR_CERT_AUTHORITY_INVALID", "No trusted authority issued this certificate."], + ["net::ERR_CERT_COMMON_NAME_INVALID", "This certificate is not for this address."], + ["net::ERR_CERT_DATE_INVALID", "This certificate has expired or is not valid yet."], +]); + +/** + * A `wss:` socket reaches the same TLS endpoint as the page, so it shares the + * `https:` origin. It must: a socket is never a main frame, so it could not be + * approved on its own, and a page's dev-server socket would stay blocked. + */ +const certificateOrigin = (rawUrl: string): string | null => { + try { + const url = new URL(rawUrl); + return url.protocol === "https:" || url.protocol === "wss:" ? `https://${url.host}` : null; + } catch { + return null; + } +}; + +const CertificateApproval = Schema.Struct({ + origin: Schema.String, + fingerprint: Schema.String, + error: Schema.String, +}); +type CertificateApproval = typeof CertificateApproval.Type; +const CertificateApprovalsJson = Schema.fromJsonString(Schema.Array(CertificateApproval)); +const decodeCertificateApprovals = Schema.decodeEffect(CertificateApprovalsJson); +const encodeCertificateApprovals = Schema.encodeEffect(CertificateApprovalsJson); + +const certificateApprovalKey = ({ origin, fingerprint, error }: CertificateApproval): string => + JSON.stringify([origin, fingerprint, error]); + +/** Kept beside the profile's cookies, so it lives and dies with them. */ +const CERTIFICATE_APPROVALS_FILE = "t3code-certificate-approvals.json"; + +/** Server-chosen certificate names must not add lines or flood the prompt. */ +const promptCertificateName = (name: string): string => { + const flat = name.replace(/\s+/g, " ").trim(); + return flat.length > 120 ? `${flat.slice(0, 120)}…` : flat; +}; + +const promptCertificateDate = (seconds: number): string => + DateTime.formatIsoDateUtc(DateTime.makeUnsafe(seconds * 1000)); + +/** The certificates a user accepted in one preview Session. */ +interface CertificateTrust { + /** `null` for an incognito Session, whose approvals end with the process. */ + readonly file: string | null; + readonly approvals: Map; + /** Bumped by each revocation, so an answer to an older prompt cannot restore trust. */ + revocations: number; +} + export class BrowserSessionPartitionDerivationError extends Schema.TaggedError()( "BrowserSessionPartitionDerivationError", { @@ -154,6 +220,10 @@ export class BrowserSession extends Context.Service< readonly clearCookies: ( partitions?: ReadonlyArray, ) => Effect.Effect; + /** For cookies cleared outside `clearCookies`, such as over a tab's CDP session. */ + readonly cookiesCleared: ( + browserSession: Session, + ) => Effect.Effect; readonly clearCache: ( partitions?: ReadonlyArray, ) => Effect.Effect; @@ -190,7 +260,11 @@ const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined /** @public */ export const make = Effect.gen(function* BrowserSessionMake() { const crypto = yield* Digest.Digest; + const electronApp = yield* ElectronApp.ElectronApp; const electronDialog = yield* ElectronDialog.ElectronDialog; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const platform = yield* HostProcess.Platform; const runFork = Effect.runForkWith(yield* Effect.context()); // One prompt at a time, so a page cannot stack dialogs by looping a deep link. let permissionPromptOpen = false; @@ -257,6 +331,229 @@ export const make = Effect.gen(function* BrowserSessionMake() { (answer) => callback(answer === true), ); }; + + const certificateTrust = new WeakMap(); + const writeCertificateApprovals = yield* Semaphore.make(1); + const loadCertificateTrust = Effect.fn("BrowserSession.loadCertificateTrust")(function* ( + browserSession: Session, + ) { + const file = + browserSession.storagePath == null + ? null + : path.join(browserSession.storagePath, CERTIFICATE_APPROVALS_FILE); + const approvals: ReadonlyArray = + file === null + ? [] + : yield* fileSystem.readFileString(file).pipe( + Effect.flatMap(decodeCertificateApprovals), + Effect.catchTags({ + PlatformError: (error) => + error.reason._tag === "NotFound" ? Effect.succeed([]) : Effect.fail(error), + }), + Effect.catch((cause) => + Effect.logWarning("Ignored saved certificate approvals.", { file, cause }).pipe( + Effect.as([]), + ), + ), + ); + const trust: CertificateTrust = { + file, + approvals: new Map(approvals.map((approval) => [certificateApprovalKey(approval), approval])), + revocations: 0, + }; + return trust; + }); + const writeApprovalsFile = Effect.fn("BrowserSession.writeApprovalsFile")(function* ( + file: string, + approvals: ReadonlyMap, + ) { + if (approvals.size === 0) return yield* fileSystem.remove(file, { force: true }); + yield* fileSystem.makeDirectory(path.dirname(file), { recursive: true }); + yield* fileSystem.writeFileString( + file, + yield* encodeCertificateApprovals([...approvals.values()]), + ); + }); + /** + * Saved before it is trusted, so a failed write cannot leave an approval that + * silently ends at restart. Writes share one lock, so a slower write cannot + * restore stale data. + */ + const rememberCertificate = Effect.fn("BrowserSession.rememberCertificate")(function* ( + trust: CertificateTrust, + key: string, + approval: CertificateApproval, + revocations: number, + ) { + if (trust.revocations !== revocations) return false; + if (trust.file !== null) { + yield* writeApprovalsFile(trust.file, new Map(trust.approvals).set(key, approval)); + // A revocation during the write queues its own rewrite behind this one. + if (trust.revocations !== revocations) return false; + } + trust.approvals.set(key, approval); + return true; + }, writeCertificateApprovals.withPermits(1)); + /** + * Rewrites the file from memory. Clearing cookies runs this even when memory + * is already empty, so retrying after a failed removal still deletes the file. + */ + const saveCertificateApprovals = Effect.fn("BrowserSession.saveCertificateApprovals")(function* ( + trust: CertificateTrust, + ) { + if (trust.file !== null) yield* writeApprovalsFile(trust.file, trust.approvals); + }, writeCertificateApprovals.withPermits(1)); + + // One prompt at a time; tabs that hit the same certificate wait on it. + let certificatePrompt: { + readonly trust: CertificateTrust; + readonly key: string; + readonly callbacks: Array<(trusted: boolean) => void>; + } | null = null; + const confirmCertificate = ( + contents: WebContents, + trust: CertificateTrust, + approval: CertificateApproval, + certificate: Certificate, + reason: string, + callback: (trusted: boolean) => void, + ): void => { + const key = certificateApprovalKey(approval); + if (certificatePrompt !== null) { + if (certificatePrompt.trust === trust && certificatePrompt.key === key) { + certificatePrompt.callbacks.push(callback); + } else { + callback(false); + } + return; + } + const prompt = { trust, key, callbacks: [callback] }; + certificatePrompt = prompt; + // A prompt for a tab that closed or moved on would approve a page nobody is waiting for. + const dismiss = new AbortController(); + const abandon = () => dismiss.abort(); + const navigated = ( + event: Electron.Event, + ) => { + if (event.isMainFrame && !event.isSameDocument) abandon(); + }; + contents.once("destroyed", abandon); + contents.on("did-start-navigation", navigated); + const settle = (trusted: boolean) => + Effect.sync(() => { + certificatePrompt = null; + if (!contents.isDestroyed()) { + contents.off("destroyed", abandon); + contents.off("did-start-navigation", navigated); + } + for (const waiter of prompt.callbacks) waiter(trusted); + }); + const host = new URL(approval.origin).host; + const revocations = trust.revocations; + runFork( + electronDialog + .showMessageBox( + { + type: "warning", + buttons: ["Trust and Remember", "Cancel"], + defaultId: 1, + cancelId: 1, + signal: dismiss.signal, + message: `${host} has an untrusted certificate`, + detail: [ + reason, + "", + `Issued to: ${promptCertificateName(certificate.subjectName)}`, + `Issued by: ${promptCertificateName(certificate.issuerName)}`, + `Valid: ${promptCertificateDate(certificate.validStart)} – ${promptCertificateDate(certificate.validExpiry)}`, + `Fingerprint: ${approval.fingerprint}`, + "", + "Trust it only if you know this certificate belongs to the site. Clearing this browser profile's cookies forgets it.", + ].join("\n"), + }, + // In the reporter's Windows test, a box owned by the host window + // blocked all mouse input, its own buttons included, until it closed. + platform === "win32" ? undefined : previewHostWindow(contents), + ) + .pipe( + Effect.flatMap(({ response }) => + response === 0 && !dismiss.signal.aborted + ? rememberCertificate(trust, key, approval, revocations).pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to save a certificate approval.", { cause }).pipe( + Effect.andThen( + electronDialog.showErrorBox( + `Could not trust the certificate for ${host}`, + `${DESKTOP_APP_NAME} could not save this approval, so the page stays blocked. Check that the disk is not full and its data folder is writable, then try again.`, + ), + ), + Effect.as(false), + ), + ), + ) + : Effect.succeed(false), + ), + Effect.orElseSucceed(() => false), + Effect.flatMap(settle), + Effect.onInterrupt(() => settle(false)), + ), + ); + }; + yield* electronApp.on( + "certificate-error", + ( + event: Electron.Event, + contents: WebContents, + url: string, + error: string, + certificate: Certificate, + callback: (trusted: boolean) => void, + isMainFrame: boolean, + ) => { + if (contents.isDestroyed()) return; + // Sessions this service did not create keep Electron's denial. + const trust = certificateTrust.get(contents.session); + const origin = certificateOrigin(url); + const reason = OVERRIDABLE_CERTIFICATE_ERRORS.get(error); + if (trust === undefined || origin === null || reason === undefined) return; + const approval = { origin, fingerprint: certificate.fingerprint, error }; + event.preventDefault(); + if (trust.approvals.has(certificateApprovalKey(approval))) { + callback(true); + return; + } + // Only a page navigation asks; a subresource the user has not accepted stays blocked. + if (!isMainFrame) { + callback(false); + return; + } + confirmCertificate(contents, trust, approval, certificate, reason, callback); + }, + ); + + /** Clearing a profile's cookies also forgets the certificates its user trusted. */ + const revokeCertificates = Effect.fn("BrowserSession.revokeCertificates")(function* ( + partition: string, + browserSession: Session, + ) { + const trust = certificateTrust.get(browserSession); + if (trust === undefined) return; + const hadApprovals = trust.approvals.size > 0; + trust.revocations += 1; + trust.approvals.clear(); + const saved = yield* saveCertificateApprovals(trust).pipe(Effect.result); + // An open connection already passed its certificate check. + if (hadApprovals) { + yield* Effect.tryPromise({ + try: () => browserSession.closeAllConnections(), + catch: (cause) => new BrowserSessionStorageClearError({ partition, cause }), + }); + } + if (Result.isFailure(saved)) { + return yield* new BrowserSessionStorageClearError({ partition, cause: saved.failure }); + } + }); + const sessionsRef = yield* SynchronizedRef.make>(new Map()); const getPartition = Effect.fn("BrowserSession.getPartition")(function* ( @@ -361,9 +658,7 @@ export const make = Effect.gen(function* BrowserSessionMake() { }); }, ); - const next = new Map(sessions); - next.set(partition, browserSession); - return [browserSession, next] as const; + return browserSession; }, catch: (cause) => new BrowserSessionCreationError({ @@ -371,7 +666,18 @@ export const make = Effect.gen(function* BrowserSessionMake() { partition, cause, }), - }); + }).pipe( + Effect.flatMap((browserSession) => + loadCertificateTrust(browserSession).pipe( + Effect.map((trust) => { + certificateTrust.set(browserSession, trust); + const next = new Map(sessions); + next.set(partition, browserSession); + return [browserSession, next] as const; + }), + ), + ), + ); }); }); @@ -386,20 +692,37 @@ export const make = Effect.gen(function* BrowserSessionMake() { yield* Effect.forEach( selectSessions(sessions, partitions), ([partition, browserSession]) => - Effect.tryPromise({ - try: () => - browserSession.clearStorageData({ - storages: ["cookies", "localstorage", "indexdb", "serviceworkers", "cachestorage"], - }), - catch: (cause) => - new BrowserSessionStorageClearError({ - partition, - cause, - }), + Effect.gen(function* () { + const cleared = yield* Effect.tryPromise({ + try: () => + browserSession.clearStorageData({ + storages: [ + "cookies", + "localstorage", + "indexdb", + "serviceworkers", + "cachestorage", + ], + }), + catch: (cause) => + new BrowserSessionStorageClearError({ + partition, + cause, + }), + }).pipe(Effect.result); + // Approvals go even when the storage clear fails, since the user asked to forget them. + yield* revokeCertificates(partition, browserSession); + if (Result.isFailure(cleared)) return yield* cleared.failure; }), { concurrency: "unbounded", discard: true }, ); }), + cookiesCleared: Effect.fn("BrowserSession.cookiesCleared")(function* (browserSession) { + const sessions = yield* SynchronizedRef.get(sessionsRef); + for (const [partition, candidate] of sessions) { + if (candidate === browserSession) yield* revokeCertificates(partition, browserSession); + } + }), clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) { const sessions = yield* SynchronizedRef.get(sessionsRef); yield* Effect.forEach( diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts index d409ad8b42..564b4dc57d 100644 --- a/apps/desktop/src/preview/CdpRelay.test.ts +++ b/apps/desktop/src/preview/CdpRelay.test.ts @@ -1,10 +1,15 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { createCdpRelayConnection, type CdpRelayTarget } from "./CdpRelay.ts"; +import { + createCdpRelayConnection, + type CdpRelayConnection, + type CdpRelayTarget, +} from "./CdpRelay.ts"; const makeTarget = ( send: CdpRelayTarget["send"], setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {}, + ackScreencastFrame: CdpRelayTarget["ackScreencastFrame"] = () => {}, ): CdpRelayTarget => ({ send, targetId: async () => "GUEST-TARGET", @@ -12,6 +17,8 @@ const makeTarget = ( title: () => "Fixture", userAgent: () => "Electron", setDownloadDirectory, + receivesScreencast: () => true, + ackScreencastFrame, }); const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) => @@ -133,9 +140,13 @@ describe("CDP relay", () => { describe("CDP relay extra sessions", () => { it("gives a second page session the page's commands and events", async () => { - const send = vi.fn(async () => ({})); + const send = vi.fn(async () => ({})); const written: Array> = []; - const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); + const nativeAcks: Array = []; + const relay = makeRelay( + makeTarget(send, undefined, (frameId) => nativeAcks.push(frameId)), + (raw) => written.push(JSON.parse(raw)), + ); relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" })); await settle(); @@ -165,8 +176,63 @@ describe("CDP relay extra sessions", () => { await settle(); expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra); written.length = 0; - relay.event("Page.screencastFrame", { data: "x" }, undefined); - expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]); + const frame = (frameId: number) => + relay.event("Page.screencastFrame", { data: "x", sessionId: frameId }, undefined); + const ack = (sessionId: string, frameId: number) => + relay.receive( + JSON.stringify({ + id: 6, + method: "Page.screencastFrameAck", + params: { sessionId: frameId }, + sessionId, + }), + ); + const delivered = () => { + const frames = written + .filter((m) => m["method"]) + .map((m) => [m["sessionId"], (m["params"] as { sessionId?: number }).sessionId]); + written.length = 0; + return frames; + }; + frame(1); + expect(delivered()).toEqual([ + ["t3-preview-page", 1], + [extra, 1], + ]); + // A session that has not acknowledged its frame gets only the newest one, on its ack. + for (let i = 2; i < 100; i++) frame(i); + expect(delivered()).toEqual([]); + // Frames every session is busy for stay unacknowledged, so Chromium pauses at its in-flight limit. + expect(nativeAcks).toEqual([1]); + ack(extra, 1); + await settle(); + expect(delivered()).toEqual([[extra, 99]]); + // Each consumer ack lets Chromium send one more frame. + expect(nativeAcks).toEqual([1, 2]); + ack(extra, 99); + await settle(); + expect(delivered()).toEqual([]); + expect(nativeAcks).toEqual([1, 2, 3]); + frame(100); + expect(delivered()).toEqual([[extra, 100]]); + ack(extra, 99); + await settle(); + frame(101); + expect(delivered()).toEqual([]); + expect(send.mock.calls.some(([method]) => method === "Page.screencastFrameAck")).toBe(false); + // A restart keeps the unacknowledged frame's slot until its own acknowledgement. + relay.receive(JSON.stringify({ id: 7, method: "Page.stopScreencast", sessionId: extra })); + relay.receive(JSON.stringify({ id: 8, method: "Page.startScreencast", sessionId: extra })); + await settle(); + delivered(); + frame(102); + expect(delivered()).toEqual([]); + ack(extra, 100); + await settle(); + expect(delivered()).toEqual([[extra, 102]]); + // Other events still reach a session while its frame is unacknowledged. + relay.event("Page.loadEventFired", { timestamp: 1 }, undefined); + expect(delivered().map(([session]) => session)).toEqual(["t3-preview-page", extra]); }); }); @@ -354,3 +420,43 @@ describe("CDP relay payload budget", () => { expect(written.map((message) => message["method"])).toEqual([]); }); }); + +describe("CDP relay reconnects", () => { + it("reports the page's default execution context to every connection", async () => { + // Electron keeps one debugger attached, so Runtime stays enabled after a client drops, + // and the native Runtime.enable announces contexts again only after Runtime.disable. + let runtimeEnabled = false; + let current: CdpRelayConnection | undefined; + const context = { + context: { id: 1, origin: "null", name: "", auxData: { isDefault: true, frameId: "F" } }, + }; + const send = vi.fn(async (method: string) => { + if (method === "Runtime.disable") runtimeEnabled = false; + if (method === "Runtime.enable" && !runtimeEnabled) { + runtimeEnabled = true; + current!.event("Runtime.executionContextCreated", context, ""); + } + return {}; + }); + const connect = async () => { + const written: Array> = []; + current = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); + current.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); + await settle(); + current.receive( + JSON.stringify({ id: 2, method: "Runtime.enable", sessionId: "t3-preview-page" }), + ); + await settle(); + return written.filter((m) => m["method"] === "Runtime.executionContextCreated"); + }; + const expected = [ + { + method: "Runtime.executionContextCreated", + params: context, + sessionId: "t3-preview-page", + }, + ]; + expect(await connect()).toEqual(expected); + expect(await connect()).toEqual(expected); + }); +}); diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts index 9a8e4e4c68..e9f3cf509b 100644 --- a/apps/desktop/src/preview/CdpRelay.ts +++ b/apps/desktop/src/preview/CdpRelay.ts @@ -9,6 +9,10 @@ export interface CdpRelayTarget { owner?: string, ) => Promise; readonly sessionDetached?: (owner: string) => void; + /** Whether a page session, by owner as `send` names it, gets the page's screencast frames. */ + readonly receivesScreencast: (owner: string | undefined) => boolean; + /** Acknowledges a native screencast frame, letting Chromium send the next one. */ + readonly ackScreencastFrame: (frameId: number) => void; /** The page's own CDP target id; Playwright keys the main frame by it. */ readonly targetId: () => Promise; readonly url: () => string; @@ -101,6 +105,20 @@ export function createCdpRelayConnection( let downloadEventsEnabled = false; /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */ const sessions = new Map([[PAGE_SESSION_ID, "page"]]); + // Each page session holds one unacknowledged frame and keeps the newest one skipped meanwhile. + const unackedFrames = new Map(); + const skippedFrames = new Map>(); + // Chromium keeps a few frames in flight and reuses one frame id per run, so pacing it means + // leaving frames every session is busy for unacknowledged and releasing one per consumer ack. + const heldNativeFrames: Array = []; + const releaseHeldFramesWithoutHolders = () => { + if (skippedFrames.size === 0) + for (const frameId of heldNativeFrames.splice(0)) target.ackScreencastFrame(frameId); + }; + const sendFrame = (sessionId: string, params: Record) => { + unackedFrames.set(sessionId, params["sessionId"] as number); + send({ method: "Page.screencastFrame", params, sessionId }); + }; let sessionSequence = 0; const newSession = (kind: "browser" | "page") => { const sessionId = `t3-preview-${kind}-${++sessionSequence}`; @@ -168,6 +186,9 @@ export function createCdpRelayConnection( const sessionId = command.params?.["sessionId"]; if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) { sessions.delete(sessionId); + unackedFrames.delete(sessionId); + skippedFrames.delete(sessionId); + releaseHeldFramesWithoutHolders(); target.sessionDetached?.(sessionId); } return {}; @@ -188,6 +209,8 @@ export function createCdpRelayConnection( } }; + let runtimeReset: Promise | undefined; + const pageCommand = (command: CdpCommand): Promise => { const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId; const owner = @@ -198,6 +221,35 @@ export function createCdpRelayConnection( } // Playwright asks for this on every page; the host emulates focus only while it is in use. if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({}); + if (command.method === "Page.screencastFrameAck" && child === undefined) { + // A restart keeps the slot too, or restarting would let frames past an unacknowledged one. + const sessionId = command.sessionId!; + if (unackedFrames.get(sessionId) === command.params?.["sessionId"]) { + unackedFrames.delete(sessionId); + const skipped = skippedFrames.get(sessionId); + skippedFrames.delete(sessionId); + if ( + skipped !== undefined && + target.receivesScreencast(sessionId === PAGE_SESSION_ID ? undefined : sessionId) + ) + sendFrame(sessionId, skipped); + const released = heldNativeFrames.shift(); + if (released !== undefined) target.ackScreencastFrame(released); + } + return Promise.resolve({}); + } + if (command.method === "Page.stopScreencast" && child === undefined) { + skippedFrames.delete(command.sessionId!); + releaseHeldFramesWithoutHolders(); + } + // The shared debugger keeps Runtime enabled after an earlier connection, and a repeated + // enable reports no existing contexts; Playwright waits for them, so reset once per connection. + if (command.method === "Runtime.enable" && child === undefined) { + runtimeReset ??= target.send("Runtime.disable", {}, undefined, owner).catch(() => undefined); + return runtimeReset.then(() => + target.send(command.method, command.params ?? {}, undefined, owner), + ); + } return target.send(command.method, command.params ?? {}, child, owner); }; @@ -250,6 +302,27 @@ export function createCdpRelayConnection( send({ method, params, sessionId }); return; } + if (method === "Page.screencastFrame") { + const frame = (params ?? {}) as Record; + const frameId = frame["sessionId"]; + if (typeof frameId !== "number") return; + let held = false; + let delivered = false; + for (const [id, kind] of sessions) { + if (kind !== "page") continue; + if (!target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id)) continue; + if (unackedFrames.has(id)) { + skippedFrames.set(id, frame); + held = true; + } else { + sendFrame(id, frame); + delivered = true; + } + } + if (held && !delivered) heldNativeFrames.push(frameId); + else target.ackScreencastFrame(frameId); + return; + } for (const [id, kind] of sessions) if (kind === "page") send({ method, params, sessionId: id }); }, diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 7b8729a116..8e96129293 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -16,7 +16,21 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); const decodeCdpReply = Schema.decodeUnknownSync( Schema.fromJsonString(Schema.Struct({ id: Schema.Number })), ); +const decodeCdpMessage = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + id: Schema.optional(Schema.Number), + method: Schema.optional(Schema.String), + sessionId: Schema.optional(Schema.String), + }), + ), +); const key = { threadId: "thread-1", tabId: "tab-1" }; + +/** A host whose client already draws `key` at full detail, so its screenshots go out at once. */ +const makeDrawnHost = Effect.tap(DesktopBrowserHost.make, (host) => + Effect.sync(() => host.setCaptureDrawn(key, true)), +); /** Sends a page command whose id the fake debugger records as it receives it. */ const command = ( host: DesktopBrowserHost.DesktopBrowserHost["Service"], @@ -43,6 +57,8 @@ const makeDebuggee = ( const pending: Array<() => void> = []; const focusChanges: Array<() => void> = []; const sent: Array = []; + const methods: Array = []; + const rejects: Array<() => void> = []; const sendWaiters: Array<() => void> = []; const focusEmulation: Array = []; const debuggee = Object.assign(emitter, { @@ -67,6 +83,8 @@ const makeDebuggee = ( return; } sent.push(params?.id); + methods.push(method); + rejects.push(() => reject(new Error("Refused"))); pending.push(() => resolve({ method })); sendWaiters.shift()?.(); }), @@ -94,6 +112,10 @@ const makeDebuggee = ( webContents.emit("did-fail-load", {}, code, "Failed", "http://localhost/", true), /** Ids of the commands the debugger received, in order. */ sent, + /** Methods of the same commands, in order. */ + methods, + /** Refuses the pending command the debugger received with this id. */ + refuse: (id: number) => rejects[sent.indexOf(id)]?.(), focusEmulation, nextSend: () => new Promise((resolve) => sendWaiters.push(resolve)), release: () => pending.splice(0).forEach((resolve) => resolve()), @@ -116,16 +138,24 @@ const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], coun /** * Ids of the replies the host sends, in order. A screenshot's reply leaves after its turn * has passed on, so by then the next waiting screenshot, if any, has been sent. Subscribe - * before sending commands: a new subscriber releases the tab's relay. + * before sending commands: a new subscriber releases the tab's relay. Screencast frames + * go to `frames` by the session they were sent to. */ -const watchReplies = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) => +const watchReplies = ( + host: DesktopBrowserHost.DesktopBrowserHost["Service"], + frames: Array = [], +) => Effect.gen(function* () { const replies = yield* Queue.unbounded(); yield* host.events.pipe( Stream.map((line) => decodeEvent(new TextDecoder().decode(line))), - Stream.runForEach((event) => - event.type === "cdp" ? Queue.offer(replies, decodeCdpReply(event.message).id) : Effect.void, - ), + Stream.runForEach((event) => { + if (event.type !== "cdp") return Effect.void; + const { id, method, sessionId } = decodeCdpMessage(event.message); + if (id !== undefined) return Queue.offer(replies, id); + if (method === "Page.screencastFrame") frames.push(sessionId); + return Effect.void; + }), Effect.forkScoped, ); yield* Effect.yieldNow; @@ -147,7 +177,7 @@ const watchPainting = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) = describe("DesktopBrowserHost", () => { it.effect("announces tabs already attached to a backend that starts later", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; host.attach(key, makeDebuggee().tab); expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]); @@ -157,7 +187,7 @@ describe("DesktopBrowserHost", () => { it.effect("announces a guest still loading its first page only once that page is up", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const loading = makeDebuggee({ loading: true }); const other = { ...key, tabId: "tab-2" }; const reader = yield* takeEvents(host, 3).pipe(Effect.forkScoped); @@ -180,7 +210,7 @@ describe("DesktopBrowserHost", () => { "keeps a loading guest unannounced across a replaced navigation and a new backend", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const loading = makeDebuggee({ loading: true }); const other = { ...key, tabId: "tab-2" }; host.attach(key, loading.tab); @@ -202,7 +232,7 @@ describe("DesktopBrowserHost", () => { "announces a first page that never comes up, but never a tab closed or destroyed first", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const closed = { ...key, tabId: "tab-2" }; const destroyed = { ...key, tabId: "tab-3" }; const destroyedGuest = makeDebuggee({ loading: true }); @@ -222,7 +252,7 @@ describe("DesktopBrowserHost", () => { it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; host.attach(key, makeDebuggee().tab); host.setShown(key, true); const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped); @@ -243,7 +273,7 @@ describe("DesktopBrowserHost", () => { it.effect("replays an explicit hidden report before announcing another tab", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const other = { ...key, tabId: "tab-2" }; host.setShown(key, false); host.attach(key, makeDebuggee().tab); @@ -260,7 +290,7 @@ describe("DesktopBrowserHost", () => { it.effect("drops replies from a relay the server released", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped); @@ -283,12 +313,12 @@ describe("DesktopBrowserHost", () => { expect(reply).toMatchObject({ type: "cdp" }); expect(decodeCdpReply((reply as { message: string }).message).id).toBe(2); - }).pipe(Effect.scoped), + }), ); it.effect("sends a page one screenshot at a time", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -302,12 +332,41 @@ describe("DesktopBrowserHost", () => { debuggee.releaseFirst(); expect(yield* Queue.take(replies)).toBe(1); expect(debuggee.sent).toEqual([1, 3, 2]); - }).pipe(Effect.scoped), + }), + ); + + it.effect( + "sends a screenshot once the client draws the guest at full detail, or soon after", + () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([]); + host.setCaptureDrawn(key, true); + yield* settle; + expect(debuggee.sent).toEqual([1]); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(1); + + // A client that never draws, such as a hidden window, only delays the capture. + host.setCaptureDrawn(key, false); + yield* command(host, 2, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([1]); + yield* TestClock.adjust("1 second"); + yield* settle; + expect(debuggee.sent).toEqual([1, 2]); + }).pipe(Effect.scoped), ); it.effect("stops waiting on a screenshot the page navigated away from", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -327,12 +386,12 @@ describe("DesktopBrowserHost", () => { debuggee.releaseFirst(); expect(yield* Queue.take(replies)).toBe(2); expect(debuggee.sent).toEqual([1, 2, 3]); - }).pipe(Effect.scoped), + }), ); it.effect("drops screenshots a released relay left waiting", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -352,7 +411,7 @@ describe("DesktopBrowserHost", () => { it.effect("emulates focus while the server drives a guest, then lets a hidden one throttle", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -383,7 +442,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused while a command it is running is still pending", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -399,12 +458,12 @@ describe("DesktopBrowserHost", () => { expect(yield* Queue.take(replies)).toBe(1); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -426,7 +485,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused for the screenshot a navigation lets start", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -442,7 +501,7 @@ describe("DesktopBrowserHost", () => { it.effect("never sends a screenshot a navigation superseded while focus was changing", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ deferFocus: true }); host.attach(key, debuggee.tab); @@ -459,7 +518,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused when its turn starts after the agent's first command", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const turn = (active: boolean) => @@ -481,7 +540,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle through a turn that only sent it housekeeping", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); yield* host.handleCommandLine( @@ -491,6 +550,9 @@ describe("DesktopBrowserHost", () => { // Playwright re-enabling a domain after a reload is not the agent using the tab. yield* command(host, 1, "Runtime.enable"); yield* settle; + // The relay resets Runtime before a connection's first enable: answer the disable, then the enable. + debuggee.release(); + yield* settle; debuggee.release(); yield* settle; yield* TestClock.adjust("1 minute"); @@ -507,7 +569,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest the agent used focused through its turn's pauses", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const turn = (active: boolean) => @@ -535,7 +597,7 @@ describe("DesktopBrowserHost", () => { "ends a command's hold with the turn that sent it, even if Chromium never answers", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); yield* host.handleCommandLine( @@ -556,7 +618,7 @@ describe("DesktopBrowserHost", () => { it.effect("ends the agent's own session's holds with its turn, but not a viewer's stream", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -584,12 +646,12 @@ describe("DesktopBrowserHost", () => { yield* turn(false); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false, true]); - }).pipe(Effect.scoped), + }), ); it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -607,26 +669,27 @@ describe("DesktopBrowserHost", () => { params: { sessionId: "t3-preview-page-1" }, }); expect(yield* Queue.take(replies)).toBe(3); - expect(painting).toEqual([true, false]); + expect(painting).toEqual([true]); // The agent's screenshot waits its turn; painting lets the abandoned one finish first. yield* command(host, 4, "Page.captureScreenshot"); yield* settle; - expect(painting).toEqual([true, false, true]); + expect(painting).toEqual([true]); debuggee.release(); expect(yield* Queue.take(replies)).toBe(2); yield* settle; expect(debuggee.sent).toEqual([undefined, 4]); + expect(painting).toEqual([true]); debuggee.release(); expect(yield* Queue.take(replies)).toBe(4); yield* settle; - expect(painting).toEqual([true, false, true, false]); - }).pipe(Effect.scoped), + expect(painting).toEqual([true, false]); + }), ); it.effect("stops painting for a queued screenshot once its session detaches", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -645,22 +708,27 @@ describe("DesktopBrowserHost", () => { expect(yield* Queue.take(replies)).toBe(2); yield* raw({ id: 3, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" }); yield* settle; - expect(painting).toEqual([true, false, true]); + expect(painting).toEqual([true]); yield* raw({ id: 4, method: "Target.detachFromTarget", params: { sessionId: "t3-preview-page-1" }, }); expect(yield* Queue.take(replies)).toBe(4); - expect(painting).toEqual([true, false, true, false]); + + // The agent's answers late; the viewer's is dropped unsent, so nothing is left to paint. + debuggee.release(); + yield* settle; + expect(debuggee.sent).toEqual([1]); + expect(painting).toEqual([true, false]); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("never sends a screenshot whose session detached while focus was changing", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ deferFocus: true }); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -679,12 +747,12 @@ describe("DesktopBrowserHost", () => { debuggee.settleFocus(); yield* settle; expect(debuggee.sent).toEqual([]); - }).pipe(Effect.scoped), + }), ); - it.effect("stops painting for a screenshot still queued when the agent's turn ends", () => + it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -697,21 +765,24 @@ describe("DesktopBrowserHost", () => { yield* settle; yield* turn(false); yield* settle; - expect(painting).toEqual([true, false]); + expect(painting).toEqual([true]); - // The first answers late; the second still goes in turn, but holds nothing. + // The first answers late; the second still goes in turn, painting but holding no focus. debuggee.releaseFirst(); yield* settle; expect(debuggee.sent).toEqual([1, 2]); - expect(painting).toEqual([true, false]); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + expect(painting).toEqual([true]); + debuggee.release(); + yield* settle; + expect(painting).toEqual([true, false]); + }), ); it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ refuse: (method) => method === "Page.startScreencast" }); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -727,12 +798,12 @@ describe("DesktopBrowserHost", () => { expect(painting).toEqual([true, false]); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("lets a guest throttle after a person's input through a viewer that then closed", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -756,12 +827,12 @@ describe("DesktopBrowserHost", () => { yield* settle; yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("keeps a page's screencast when a child session's screencast is refused", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ refuse: (method, sessionId) => method === "Page.startScreencast" && sessionId !== undefined, }); @@ -778,12 +849,12 @@ describe("DesktopBrowserHost", () => { expect(yield* Queue.take(replies)).toBe(2); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true]); - }).pipe(Effect.scoped), + }), ); it.effect("ignores a screencast that arrives on a session after it detached", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -804,12 +875,12 @@ describe("DesktopBrowserHost", () => { yield* settle; yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("lets a guest throttle once the session waiting on its command detaches", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -831,12 +902,12 @@ describe("DesktopBrowserHost", () => { }); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("never sends a screenshot queued by a session that has since detached", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -862,12 +933,12 @@ describe("DesktopBrowserHost", () => { yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("keeps a streamed guest focused until its screencast ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -896,7 +967,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused while any of its screencasts runs", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -923,12 +994,12 @@ describe("DesktopBrowserHost", () => { }); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("paints a hidden guest only while the screenshot it is taking is pending", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -949,55 +1020,57 @@ describe("DesktopBrowserHost", () => { debuggee.release(); yield* settle; expect(painting).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); - it.effect("stops painting for a screenshot Chromium never answers", () => + it.effect("stops painting for a screenshot Chromium never answers once its document goes", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); const turn = (active: boolean) => host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active })); - // The server gave up on it, and the agent's turn ends. + // The server gave up on it, and the agent's turn ends; Chromium still holds the capture. yield* turn(true); yield* command(host, 1, "Page.captureScreenshot"); yield* settle; yield* turn(false); yield* settle; - expect(painting).toEqual([true, false]); + expect(painting).toEqual([true]); // The page loads a new document, which also frees the screenshot turn. debuggee.navigate(); + expect(painting).toEqual([true, false]); yield* command(host, 2, "Page.captureScreenshot"); yield* settle; debuggee.navigate(); yield* settle; expect(painting).toEqual([true, false, true, false]); - // The server releases the relay. + // The server releases the relay; Chromium still holds the capture. yield* command(host, 3, "Page.captureScreenshot"); yield* settle; yield* host.handleCommandLine(encodeJson({ type: "release", ...key })); yield* settle; - expect(painting).toEqual([true, false, true, false, true, false]); + expect(painting).toEqual([true, false, true, false, true]); // The guest detaches; a replacement starts with no screenshot pending. const replacement = makeDebuggee(); host.attach(key, replacement.tab); + expect(painting).toEqual([true, false, true, false, true, false]); yield* command(host, 4, "Page.captureScreenshot"); yield* settle; host.detach(key); yield* settle; expect(painting).toEqual([true, false, true, false, true, false, true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("paints a streamed guest until its last screencast ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -1023,12 +1096,188 @@ describe("DesktopBrowserHost", () => { }); yield* settle; expect(painting).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); - it.effect("saves a server tab's download under its CDP guid where the server asked", () => + it.effect("keeps a guest's one screencast running until its last streaming session stops", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const frames: Array = []; + const replies = yield* watchReplies(host, frames); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + const nativeStops = () => + debuggee.methods.filter((method) => method === "Page.stopScreencast").length; + + // A viewer and a recording share Chromium's single screencast for the guest. + yield* raw({ id: 0, method: "Target.setAutoAttach", params: { autoAttach: true } }); + expect(yield* Queue.take(replies)).toBe(0); + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]); + yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" }); + yield* settle; + debuggee.release(); + yield* raw({ id: 5, method: "Page.stopScreencast", sessionId: "t3-preview-page-1" }); + yield* settle; + expect(nativeStops(), "stopped the screencast another session still streams").toBe(0); + debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 1 }); + yield* settle; + expect(frames, "sent a stopped or idle session the screencast's frames").toEqual([ + "t3-preview-page-2", + ]); + + yield* raw({ id: 6, method: "Page.stopScreencast", sessionId: "t3-preview-page-2" }); + yield* settle; + expect(nativeStops()).toBe(1); + }), + ); + + it.effect("keeps a session's screencast when another of its starts is refused", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const frames: Array = []; + const replies = yield* watchReplies(host, frames); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + + yield* raw({ id: 0, method: "Target.setAutoAttach", params: { autoAttach: true } }); + expect(yield* Queue.take(replies)).toBe(0); + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(1); + yield* raw({ + id: 2, + method: "Page.startScreencast", + params: { id: 2 }, + sessionId: "t3-preview-page-1", + }); + yield* raw({ + id: 3, + method: "Page.startScreencast", + params: { id: 3 }, + sessionId: "t3-preview-page-1", + }); + yield* settle; + debuggee.refuse(2); + debuggee.release(); + expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([2, 3]); + yield* settle; + expect(debuggee.methods).not.toContain("Page.stopScreencast"); + debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 1 }); + yield* settle; + expect(frames).toContain("t3-preview-page-1"); + + // A refused replacement leaves the session's running stream, shared with another session. + yield* raw({ id: 4, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(4); + yield* raw({ + id: 5, + method: "Page.startScreencast", + params: { id: 5 }, + sessionId: "t3-preview-page-2", + }); + yield* raw({ + id: 6, + method: "Page.startScreencast", + params: { id: 6 }, + sessionId: "t3-preview-page-1", + }); + yield* settle; + debuggee.refuse(6); + debuggee.release(); + expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([5, 6]); + yield* raw({ + id: 7, + method: "Page.screencastFrameAck", + params: { sessionId: 1 }, + sessionId: "t3-preview-page-1", + }); + expect(yield* Queue.take(replies)).toBe(7); + yield* settle; + frames.length = 0; + debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 2 }); + yield* settle; + expect(frames).toEqual(["t3-preview-page-1", "t3-preview-page-2"]); + }), + ); + + it.effect("stops a guest's screencast once its last streaming session detaches", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + const nativeStops = () => + debuggee.methods.filter((method) => method === "Page.stopScreencast").length; + + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]); + yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" }); + yield* settle; + debuggee.release(); + // Streamers go without stopping, such as viewers that closed. + yield* raw({ + id: 5, + method: "Target.detachFromTarget", + params: { sessionId: "t3-preview-page-1" }, + }); + yield* settle; + expect(nativeStops(), "stopped the screencast another session still streams").toBe(0); + yield* raw({ + id: 6, + method: "Target.detachFromTarget", + params: { sessionId: "t3-preview-page-2" }, + }); + const answered = []; + for (let reply = 0; reply < 4; reply++) answered.push(yield* Queue.take(replies)); + expect(answered.toSorted()).toEqual([3, 4, 5, 6]); + yield* settle; + expect(nativeStops()).toBe(1); + }), + ); + + it.effect("stops a screencast whose start lands after its session detached", () => Effect.gen(function* () { const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee({ deferFocus: true }); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(1); + // The start waits on focus emulation while the viewer closes. + yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + yield* raw({ + id: 3, + method: "Target.detachFromTarget", + params: { sessionId: "t3-preview-page-1" }, + }); + expect(yield* Queue.take(replies)).toBe(3); + debuggee.settleFocus(); + yield* settle; + debuggee.release(); + expect(yield* Queue.take(replies)).toBe(2); + yield* settle; + expect(debuggee.methods.at(-1), "left the late screencast running").toBe( + "Page.stopScreencast", + ); + }), + ); + + it.effect("saves a server tab's download under its CDP guid where the server asked", () => + Effect.gen(function* () { + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -1058,12 +1307,12 @@ describe("DesktopBrowserHost", () => { expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true); expect(paths).toEqual(["/srv/downloads/guid-1"]); expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false); - }).pipe(Effect.scoped), + }), ); it.effect("tells a download the person clicked from one the agent's input started", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -1090,9 +1339,44 @@ describe("DesktopBrowserHost", () => { }), ); - it.effect("detaches only the tab whose CDP event is too large to relay", () => + it.effect("stops crediting the agent once a person acts through a viewer", () => Effect.gen(function* () { const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + const viewer = (id: number, method: string, type: string) => + raw({ id, method, params: { type }, sessionId: "t3-preview-page-1" }); + const led = () => host.agentLedPage(debuggee.tab.webContents); + + yield* command(host, 1, "DOM.getDocument"); + expect(led()).toBe(false); + yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(2); + yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + + for (const [method, type] of [ + ["Input.dispatchKeyEvent", "rawKeyDown"], + ["Input.dispatchMouseEvent", "mousePressed"], + ["Input.dispatchTouchEvent", "touchStart"], + ] as const) { + yield* command(host, 4, "Runtime.evaluate"); + expect(led()).toBe(true); + // The viewer's pointer only passes over the page the agent drives. + yield* viewer(5, "Input.dispatchMouseEvent", "mouseMoved"); + yield* viewer(6, "Input.dispatchMouseEvent", "mouseWheel"); + expect(led()).toBe(true); + yield* viewer(7, method, type); + expect(led()).toBe(false); + } + }).pipe(Effect.scoped), + ); + + it.effect("detaches only the tab whose CDP event is too large to relay", () => + Effect.gen(function* () { + const host = yield* makeDrawnHost; const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()]; const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand"); const keys = [key, { threadId: "thread-2", tabId: "tab-2" }]; @@ -1156,6 +1440,6 @@ describe("DesktopBrowserHost", () => { expect(JSON.parse((next as { message: string }).message)).toMatchObject({ method: "Page.loadEventFired", }); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index 2168532902..ce5d7074a7 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -4,6 +4,7 @@ import { DesktopBrowserCommand, DesktopBrowserEvent, type DesktopBrowserEvent as DesktopBrowserEventType, + type PreviewAutomationLoadError, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as NodePath from "node:path"; @@ -25,8 +26,12 @@ const AGENT_INPUT_COMMAND = /"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/; /** The same commands as above, by method, for the relay's sends. */ const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|callFunctionOn)$)/; -const AGENT_DOWNLOAD_WINDOW_MS = 5_000; +const AGENT_INPUT_WINDOW_MS = 5_000; +/** A viewer's pointer travelling over the stream activates nothing on the page. */ +const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]); const FOCUS_IDLE = "5 seconds"; +/** How long a screenshot waits for the client to draw its guest at full detail. */ +const CAPTURE_DRAW_WAIT = "1 second"; /** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */ const FIRST_PAGE_TIMEOUT = "5 seconds"; const ERR_ABORTED = -3; @@ -39,6 +44,8 @@ export interface DesktopBrowserTabKey { export interface DesktopBrowserTabDebugger { readonly webContents: Electron.WebContents; readonly debugger: Electron.Debugger; + /** Runs after the server clears the tab's cookies, so state kept beside them goes too. */ + readonly cookiesCleared?: () => Promise; } const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`; @@ -48,7 +55,7 @@ interface AttachedTab { readonly debuggee: DesktopBrowserTabDebugger; relay: CdpRelayConnection | null; screenshotTurn: object | null; - /** Each holds focus and painting while `held` and whoever queued it still waits on it. */ + /** Each keeps the guest painting while whoever queued it still waits, and focused while `held`. */ readonly waitingScreenshots: Array<{ readonly start: () => void; readonly live: () => boolean; @@ -57,14 +64,15 @@ interface AttachedTab { downloadDirectory: string | null; pendingDownloadGuid: string | null; agentInputAt: number; + /** When the agent last drove the page with no person's input through a viewer since. */ + agentLedAt: number; focusEmulated: boolean; focusChange: Promise | null; focusUses: number; /** Each pending command, by the extra session waiting on it; the main connection's have none. */ - readonly focusPending: Map< - object, - { readonly owner: string | undefined; readonly paints: boolean } - >; + readonly focusPending: Map; + /** Screenshots Chromium was sent and has not answered; each keeps its wake lock until then. */ + readonly capturing: Set; /** Whether the client keeps the guest painting, as published on `painting`. */ painting: boolean; /** @@ -73,8 +81,8 @@ interface AttachedTab { */ agentUsed: boolean; focusReleasing: boolean; - /** The sessions streaming the guest; one stopping leaves the others' screencasts running. */ - readonly screencasts: Set; + /** The sessions sharing the guest's one Chromium screencast; it stops with the last of them. */ + readonly screencasts: Map; readonly onMessage: ( event: Electron.Event, method: string, @@ -93,8 +101,13 @@ export class DesktopBrowserHost extends Context.Service< readonly handleCommandLine: (line: string) => Effect.Effect; readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void; readonly detach: (key: DesktopBrowserTabKey) => void; + readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void; readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void; + /** Whether the client draws the guest at full detail while it is captured. */ + readonly setCaptureDrawn: (key: DesktopBrowserTabKey, drawn: boolean | undefined) => void; readonly humanStartedDownload: (source: Electron.WebContents) => boolean; + /** Whether what the page does now follows the agent's input, not a viewer's. */ + readonly agentLedPage: (source: Electron.WebContents) => boolean; readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean; readonly pointers: Stream.Stream<{ readonly key: DesktopBrowserTabKey; @@ -129,6 +142,8 @@ export const make = Effect.gen(function* () { // Kept apart from attachment: the renderer can show a webview before its debugger attaches, // and the server forgets `shown` on detach, for example while DevTools holds the debugger. const shownTabs = new Map(); + const drawnTabs = new Set(); + const drawWaiters = new Map void>>(); const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event)); const nextScreenshot = (tab: AttachedTab) => { @@ -148,7 +163,7 @@ export const make = Effect.gen(function* () { tab: AttachedTab, relay: CdpRelayConnection, ownerLive: () => boolean, - /** Sends only while `current` holds; holds focus and painting only while `held`. */ + /** Sends only while `current` holds; holds focus only while `held`. */ capture: (current: () => boolean, held: boolean) => Promise, ) => new Promise((resolve, reject) => { @@ -236,38 +251,62 @@ export const make = Effect.gen(function* () { const active = tabs.get(keyOf(tab.key)) === tab && (tab.screencasts.size > 0 || - waitingHolds(tab) || - [...tab.focusPending.values()].some((hold) => hold.paints)); + tab.capturing.size > 0 || + tab.waitingScreenshots.some((waiting) => waiting.live())); if (tab.painting === active) return; tab.painting = active; runFork(PubSub.publish(painting, { key: tab.key, active })); }; /** A command may wait on the page's next frame, so the guest stays focused until it settles. */ - const holdFocus = ( - tab: AttachedTab, - method: string, - owner: string | undefined, - work: () => Promise, - ) => { + const holdFocus = (tab: AttachedTab, owner: string | undefined, work: () => Promise) => { const pending = {}; - tab.focusPending.set(pending, { owner, paints: method === "Page.captureScreenshot" }); + tab.focusPending.set(pending, owner); tab.focusUses += 1; setFocusEmulation(tab, true); releaseFocusWhenIdle(tab); - syncPainting(tab); return work().finally(() => { if (!tab.focusPending.delete(pending)) return; tab.focusUses += 1; releaseFocusWhenIdle(tab); + }); + }; + + /** + * A scaled guest rasters at its on-screen size until the client draws it at full detail, + * and a screenshot taken before that copies the blurred frame. A client that cannot draw + * (a hidden window, say) only delays the capture. + */ + const whenDrawn = (tab: AttachedTab) => + new Promise((resolve) => { + const id = keyOf(tab.key); + const waiters = drawWaiters.get(id) ?? new Set(); + drawWaiters.set(id, waiters); + const done = () => { + waiters.delete(done); + if (waiters.size === 0 && drawWaiters.get(id) === waiters) drawWaiters.delete(id); + resolve(); + }; + waiters.add(done); + runFork(Effect.sleep(CAPTURE_DRAW_WAIT).pipe(Effect.andThen(Effect.sync(done)))); + }); + + /** Chromium answers a capture, and frees its wake lock, only once the guest paints a frame. */ + const paintUntilAnswered = (tab: AttachedTab, send: () => Promise) => { + const sent = {}; + tab.capturing.add(sent); + syncPainting(tab); + // Sent at once when already drawn, so it keeps its place among the commands after it. + return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => { + tab.capturing.delete(sent); syncPainting(tab); }); }; /** * Chromium can leave a command unanswered, so the screenshot guard's release points - * also end every hold: a released relay has no one waiting, and a new document answers - * nothing pending from the old one. A released relay's screencast has no viewer to stop it. + * also end every focus hold: a released relay has no one waiting, and a new document + * answers nothing pending from the old one. A released relay's screencast has no viewer. */ const dropFocusHolds = (tab: AttachedTab) => { tab.focusPending.clear(); @@ -282,11 +321,17 @@ export const make = Effect.gen(function* () { dropFocusHolds(tab); }; + /** An owner that leaves without stopping would otherwise keep the screencast running unseen. */ + const leaveScreencast = (tab: AttachedTab, owner: string | undefined) => { + if (!tab.screencasts.delete(owner) || tab.screencasts.size > 0) return; + void tab.debuggee.debugger.sendCommand("Page.stopScreencast").catch(() => {}); + }; + /** A detached session, such as a closed viewer, waits on nothing it sent. */ const dropSessionHolds = (tab: AttachedTab, owner: string) => { - tab.screencasts.delete(owner); - for (const [pending, hold] of tab.focusPending) { - if (hold.owner === owner) tab.focusPending.delete(pending); + leaveScreencast(tab, owner); + for (const [pending, holder] of tab.focusPending) { + if (holder === owner) tab.focusPending.delete(pending); } releaseFocusWhenIdle(tab); syncPainting(tab); @@ -294,7 +339,7 @@ export const make = Effect.gen(function* () { /** * A command the server stopped waiting on, such as a timed-out screenshot or evaluation, - * may never settle; the turn's end ends every hold. The agent also sends on its own extra + * may never settle; the turn's end ends every focus hold. The agent also sends on its own extra * session, so this cannot spare other sessions; a viewer's screencast still holds. */ const endAgentTurn = (threadId: string) => { @@ -302,7 +347,7 @@ export const make = Effect.gen(function* () { for (const tab of tabs.values()) { if (tab.key.threadId !== threadId) continue; tab.agentUsed = false; - // Still sent in turn, so the queue keeps moving, but no longer kept painting. + // Still sent in turn, so the queue keeps moving, but no longer kept focused. for (const waiting of tab.waitingScreenshots) waiting.held = false; dropFocusHolds(tab); } @@ -310,9 +355,12 @@ export const make = Effect.gen(function* () { const relayFor = (tab: AttachedTab) => { if (tab.relay) return tab.relay; - const { webContents, debugger: debuggee } = tab.debuggee; - const send = (method: string, params: Record, sessionId?: string) => - sendPageCommand(webContents, debuggee, method, params, sessionId); + const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee; + const send = async (method: string, params: Record, sessionId?: string) => { + const result = await sendPageCommand(webContents, debuggee, method, params, sessionId); + if (method === "Network.clearBrowserCookies") await cookiesCleared?.(); + return result; + }; const detachedOwners = new Set(); /** Viewers and recordings stream; the agent's own sessions never do. */ const streamingOwners = new Set(); @@ -320,26 +368,41 @@ export const make = Effect.gen(function* () { { send: (method, params, sessionId, owner) => { // A child session's screencast is not the page's, such as a late one on a detached session. - if (sessionId === undefined && method === "Page.startScreencast") { - tab.screencasts.add(owner); + const stream = + sessionId === undefined && method === "Page.startScreencast" + ? (tab.screencasts.get(owner) ?? { started: false, pending: 0 }) + : undefined; + if (stream) { + stream.pending += 1; + tab.screencasts.set(owner, stream); if (owner !== undefined) streamingOwners.add(owner); + syncPainting(tab); } else if (sessionId === undefined && method === "Page.stopScreencast") { tab.screencasts.delete(owner); + syncPainting(tab); + if (tab.screencasts.size > 0) return Promise.resolve({}); } // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's. - if ( - AGENT_INPUT_METHOD.test(method) && - (owner === undefined || !streamingOwners.has(owner)) - ) { - tab.agentUsed = true; + if (AGENT_INPUT_METHOD.test(method)) { + if (owner === undefined || !streamingOwners.has(owner)) { + tab.agentUsed = true; + tab.agentLedAt = performance.now(); + } else if (method.startsWith("Input.") && !POINTER_TRAVEL.has(params["type"])) { + tab.agentLedAt = Number.NEGATIVE_INFINITY; + } } // Waits for focus emulation; insertText and other non-CDP input would not queue behind it. const forward = (current?: () => boolean) => { const change = tab.focusChange; + const stale = () => tab.relay !== relay || (current !== undefined && !current()); + const sendUnlessStale = () => + stale() + ? Promise.reject(new Error("The page this screenshot was for has moved on.")) + : send(method, params, sessionId); const run = () => - tab.relay === relay && (current === undefined || current()) - ? send(method, params, sessionId) - : Promise.reject(new Error("The page this screenshot was for has moved on.")); + current === undefined || stale() + ? sendUnlessStale() + : paintUntilAnswered(tab, sendUnlessStale); return change === null ? run() : change.then(run); }; return method === "Page.captureScreenshot" @@ -348,22 +411,49 @@ export const make = Effect.gen(function* () { relay, () => owner === undefined || !detachedOwners.has(owner), (current, held) => - held ? holdFocus(tab, method, owner, () => forward(current)) : forward(current), + held ? holdFocus(tab, owner, () => forward(current)) : forward(current), ) : method === "Page.startScreencast" - ? holdFocus(tab, method, owner, forward).catch((cause: unknown) => { - // A viewer can outlive a refused stream; nothing is streaming for it. - if (sessionId === undefined && tab.relay === relay) tab.screencasts.delete(owner); - releaseFocusWhenIdle(tab); - syncPainting(tab); - throw cause; - }) - : holdFocus(tab, method, owner, forward); + ? holdFocus(tab, owner, forward).then( + (result) => { + if (stream) { + stream.pending -= 1; + stream.started = true; + // A detach's stop can overtake a start still waiting on focus; nobody owns it now. + if (tab.screencasts.get(owner) !== stream && tab.screencasts.size === 0) { + void debuggee.sendCommand("Page.stopScreencast").catch(() => {}); + } + } + return result; + }, + (cause: unknown) => { + if (stream) stream.pending -= 1; + // A viewer can outlive a refused start; its running or pending stream still holds it. + if ( + stream && + !stream.started && + stream.pending === 0 && + tab.relay === relay && + tab.screencasts.get(owner) === stream + ) { + leaveScreencast(tab, owner); + } + releaseFocusWhenIdle(tab); + syncPainting(tab); + throw cause; + }, + ) + : holdFocus(tab, owner, forward); }, sessionDetached: (owner) => { detachedOwners.add(owner); dropSessionHolds(tab, owner); }, + receivesScreencast: (owner) => tab.screencasts.has(owner), + ackScreencastFrame: (frameId) => + void debuggee + .sendCommand("Page.screencastFrameAck", { sessionId: frameId }) + .catch(() => {}), targetId: () => debuggee .sendCommand("Target.getTargetInfo") @@ -441,14 +531,16 @@ export const make = Effect.gen(function* () { downloadDirectory: null, pendingDownloadGuid: null, agentInputAt: Number.NEGATIVE_INFINITY, + agentLedAt: Number.NEGATIVE_INFINITY, focusEmulated: false, focusChange: null, focusUses: 0, focusPending: new Map(), + capturing: new Set(), painting: false, agentUsed: false, focusReleasing: false, - screencasts: new Set(), + screencasts: new Map(), onMessage: (_event, method, params, sessionId) => { if (method === "Page.downloadWillBegin") { const guid = (params as { guid?: unknown } | undefined)?.guid; @@ -459,7 +551,8 @@ export const make = Effect.gen(function* () { // A screenshot pending when the page loads a new document, a reload included, can // stay unanswered. A crashed page lands here once it reloads, well after its renderer died. onNewDocument: () => { - // Before the next screenshot starts, so its own hold survives. + // Before the next screenshot starts, so its own holds survive. + tab.capturing.clear(); dropFocusHolds(tab); if (tab.screenshotTurn !== null) nextScreenshot(tab); }, @@ -523,6 +616,21 @@ export const make = Effect.gen(function* () { if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown }); }; + const setCaptureDrawn = (key: DesktopBrowserTabKey, drawn: boolean | undefined) => { + const id = keyOf(key); + if (!drawn) { + drawnTabs.delete(id); + return; + } + drawnTabs.add(id); + for (const done of drawWaiters.get(id) ?? []) done(); + drawWaiters.delete(id); + }; + + const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => { + if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure }); + }; + const handleCommandLine = (line: string) => Effect.sync(() => { const command = decodeCommand(line); @@ -549,7 +657,12 @@ export const make = Effect.gen(function* () { const humanStartedDownload = (source: Electron.WebContents) => { const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source); - return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS; + return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_INPUT_WINDOW_MS; + }; + + const agentLedPage = (source: Electron.WebContents) => { + const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source); + return tab !== undefined && performance.now() - tab.agentLedAt <= AGENT_INPUT_WINDOW_MS; }; const announceAll = Effect.suspend(() => { @@ -588,9 +701,12 @@ export const make = Effect.gen(function* () { handleCommandLine, attach, detach, + loadFailed, setShown, + setCaptureDrawn, placeDownload, humanStartedDownload, + agentLedPage, }); }); diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts index a0889940a6..48191ce2c4 100644 --- a/apps/desktop/src/preview/GuestInput.test.ts +++ b/apps/desktop/src/preview/GuestInput.test.ts @@ -44,6 +44,30 @@ describe("preview guest input", () => { expect(guest.sendCommand).not.toHaveBeenCalledWith("Input.insertText", expect.anything()); }); + it("stops the guest navigation without stopping its embedder", async () => { + let guestLoading = true; + let hostLoading = true; + const guest = { + stop: () => { + guestLoading = false; + }, + }; + const debuggee = { + sendCommand: async () => { + hostLoading = false; + return {}; + }, + }; + await sendPageCommand( + guest as unknown as Electron.WebContents, + debuggee as unknown as Electron.Debugger, + "Page.stopLoading", + {}, + ); + expect(guestLoading).toBe(false); + expect(hostLoading).toBe(true); + }); + it.each([ { sessionId: undefined, diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index 2af13af8d7..4d794beea6 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -185,6 +185,10 @@ export const sendPageCommand = async ( else webContents.reload(); return {}; } + if (method === "Page.stopLoading") { + webContents.stop(); + return {}; + } if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) { return debuggee.sendCommand(method, params); } diff --git a/apps/desktop/src/preview/GuestProtocol.ts b/apps/desktop/src/preview/GuestProtocol.ts index a4fd88c475..1d24079d19 100644 --- a/apps/desktop/src/preview/GuestProtocol.ts +++ b/apps/desktop/src/preview/GuestProtocol.ts @@ -5,14 +5,19 @@ export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured"; export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme"; export const ANNOTATION_SEND_ENABLED_CHANNEL = "preview:annotation-send-enabled"; export const HUMAN_INPUT_CHANNEL = "preview:human-input"; -export const MOUSE_NAVIGATE_CHANNEL = "preview:mouse-navigate"; +// Sent to the hosting element (ipc-message). The web app mirrors this +// literal in HostedBrowserWebview because it cannot import from the desktop app. +export const POINTER_DOWN_HOST_CHANNEL = "preview:pointer-down"; +export const PAGE_UNHANDLED_SHORTCUT_CHANNEL = "preview:page-unhandled-shortcut"; export const RECORDING_CURSOR_CHANNEL = "preview:recording-cursor"; export const RECORDING_POINTER_CHANNEL = "preview:recording-pointer"; export const RECORDING_KEY_CHANNEL = "preview:recording-key"; export const RECORDING_INPUT_CHANNEL = "preview:recording-input"; export const RECORDING_CONTROLLER_CHANNEL = "preview:recording-controller"; +export const THUMB_PRESS_CHANNEL = "preview:thumb-press"; export const PASSKEY_CREATE_CHANNEL = "preview:passkey-create"; export const PASSKEY_GET_CHANNEL = "preview:passkey-get"; export const PASSKEY_BRIDGE_ARGUMENT = "--t3code-preview-passkey-bridge"; export const ANNOTATION_VOICE_EVENT_CHANNEL = "preview:annotation-voice-event"; export const ANNOTATION_VOICE_STATE_CHANNEL = "preview:annotation-voice-state"; +export const PRIMARY_PASTE_DISABLED_ARGUMENT = "--t3code-preview-primary-paste-disabled"; diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index b4e4b2a8b7..2091ff3c7f 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -2,6 +2,7 @@ import { it as effectIt } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { + DesktopPreviewFindResultEvent, DesktopPreviewRecordingInputEvent, PreviewAnnotationPayload, PreviewAnnotationRect, @@ -204,6 +205,7 @@ const layerBrowserSession = Layer.succeed( isPartition: (partition) => partition.startsWith("persist:t3code-preview-"), getSession: () => Effect.succeed(previewSession as unknown as Electron.Session), clearCookies: () => Effect.void, + cookiesCleared: () => Effect.void, clearCache: () => Effect.void, }), ); @@ -347,6 +349,47 @@ const makeTestPreviewWebContents = ( } as unknown as TestPreviewWebContents; }; +const makeStillImage = (pixels = "fresh-png") => ({ + toPNG: () => Buffer.from(pixels), + toJPEG: () => Buffer.from(pixels), + getSize: () => ({ width: 100, height: 80 }), +}); + +const makeTestStillImageWebContents = (...args: Parameters) => { + const wc = makeTestPreviewWebContents(...args); + Object.assign(wc, { isDevToolsOpened: () => false }); + holdStillImagePaint(wc, Promise.resolve()); + return wc; +}; + +const holdStillImagePaint = ( + wc: TestPreviewWebContents, + paint: Promise | Array>, +) => { + vi.mocked(wc.debugger.sendCommand).mockImplementation(async (method) => { + if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } }; + if (method === "Page.createIsolatedWorld") return { executionContextId: 7 }; + if (method === "Runtime.evaluate") { + await (Array.isArray(paint) ? paint.shift() : paint); + return { result: { value: true } }; + } + return undefined; + }); +}; + +const setupStill = (manager: PreviewManager.PreviewManager["Service"], paint = Promise.resolve()) => + Effect.gen(function* () { + const image = makeStillImage(); + const capturePage = vi.fn<() => Promise>().mockResolvedValue(image); + const wc = makeTestStillImageWebContents(capturePage); + holdStillImagePaint(wc, paint); + fromId.mockReturnValue(wc); + yield* manager.createTab("tab_still"); + yield* manager.registerWebview("tab_still", wc.id); + yield* manager.setColorScheme("tab_still", "system"); + return { image, capturePage, wc, capture: manager.captureScreenshot("tab_still") }; + }); + const setupRecordingRaceTabs = (manager: PreviewManager.PreviewManager["Service"]) => Effect.gen(function* () { const capturePage = vi.fn(async () => ({ @@ -574,6 +617,32 @@ describe("PreviewManager", () => { webviewSend.mockClear(); }); + effectIt.effect("preserves recording artifacts saved in the same millisecond", () => + withManager((manager) => + Effect.gen(function* () { + const stored = new Map(); + const save = (path: string, bytes: Uint8Array) => { + stored.set(path, Uint8Array.from(bytes)); + return undefined; + }; + writeFile.mockImplementationOnce(save).mockImplementationOnce(save); + const firstBytes = new Uint8Array([1, 2, 3]); + const secondBytes = new Uint8Array([4, 5, 6]); + const [first, second] = yield* Effect.all( + [ + manager.saveRecording("tab_first", "video/webm", firstBytes), + manager.saveRecording("tab_second", "video/webm", secondBytes), + ], + { concurrency: "unbounded" }, + ); + + expect(first.path).not.toBe(second.path); + expect(stored.get(first.path)).toEqual(firstBytes); + expect(stored.get(second.path)).toEqual(secondBytes); + }), + ), + ); + effectIt.effect.each([false, true])( "preserves simultaneous same-name downloads with an existing destination: %s", (existing) => @@ -615,7 +684,10 @@ describe("PreviewManager", () => { attach: () => {}, detach: () => {}, setShown: () => {}, + setCaptureDrawn: () => {}, + loadFailed: () => {}, humanStartedDownload: () => true, + agentLedPage: () => false, placeDownload: () => true, }), Layer.mock(PreviewPasskeys.PreviewPasskeys)({ @@ -668,7 +740,7 @@ describe("PreviewManager", () => { if (existing) { expect(yield* fs.readFileString(`${downloads}/report.txt`)).toBe("existing download"); } - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); effectIt.effect.each([ @@ -742,6 +814,137 @@ describe("PreviewManager", () => { ), ); + effectIt.effect.each([ + "navigate", + "reload", + "goBack", + "goForward", + "refresh", + "hardReload", + ] as const)("%s stops a page script that never yields before it navigates", (operation) => + withManager((manager) => + Effect.gen(function* () { + const preview = makeFaviconWebContents(); + // As in Chromium: the hung renderer answers nothing, and a terminate reaches it only + // while no navigation is pending. + let stopped = false; + const probed = yield* Deferred.make(); + const navigatedAfterStop: Array = []; + const navigated = () => { + navigatedAfterStop.push(stopped); + }; + const sendCommand = async (method: string) => { + if (method === "Runtime.evaluate") { + Deferred.doneUnsafe(probed, Effect.void); + await new Promise(() => {}); + } + if (method === "Runtime.terminateExecution") stopped = true; + }; + Object.assign(preview.webContents, { + getURL: () => "http://localhost:5173/busy", + reload: navigated, + reloadIgnoringCache: navigated, + loadURL: async () => navigated(), + navigationHistory: { + canGoBack: () => true, + canGoForward: () => true, + goBack: navigated, + goForward: navigated, + }, + debugger: { + isAttached: () => false, + attach: vi.fn(), + sendCommand, + on: vi.fn(), + off: vi.fn(), + }, + }); + fromId.mockReturnValue(preview.webContents); + yield* manager.createTab("tab_busy"); + yield* manager.registerWebview("tab_busy", 42); + + const leaving = yield* ( + operation === "navigate" + ? manager.navigate("tab_busy", "http://localhost:5173/next") + : operation === "reload" + ? manager.navigate("tab_busy", "http://localhost:5173/busy") + : manager[operation]("tab_busy") + ).pipe(Effect.forkChild); + const probing = yield* Effect.raceFirst( + Deferred.await(probed).pipe(Effect.as(true)), + Fiber.await(leaving).pipe(Effect.as(false)), + ); + if (probing) yield* TestClock.adjust(1_000); + yield* Fiber.join(leaving); + + expect(navigatedAfterStop).toEqual([true]); + }), + ), + ); + + effectIt.effect("keeps mouse back and forward buttons inside the preview tab", () => + withManager((manager) => + Effect.gen(function* () { + const preview = makeFaviconWebContents(); + const goBack = vi.fn(); + const goForward = vi.fn(); + const send = vi.fn(); + let canGoBack = false; + Object.assign(preview.webContents, { + navigationHistory: { + canGoBack: () => canGoBack, + canGoForward: () => true, + goBack, + goForward, + }, + getZoomFactor: () => 2, + send, + }); + fromId.mockReturnValue(preview.webContents); + yield* manager.createTab("tab_mouse_navigation"); + yield* manager.registerWebview("tab_mouse_navigation", 42); + + // Electron reports thumb buttons as "back"/"forward" for every frame of the guest, iframes included. + const beforeMouse = preview.listeners.get("before-mouse-event"); + expect(beforeMouse, "guest has no before-mouse-event listener").toBeDefined(); + const press = (type: "mouseDown" | "mouseUp", button: string) => { + const preventDefault = vi.fn(); + beforeMouse!({ preventDefault } as never, { type, button, x: 10, y: 10 } as never); + return preventDefault; + }; + + // At the start of tab history the press is still swallowed, or the host app goes back instead. + expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); + expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); + expect(goBack).not.toHaveBeenCalled(); + + canGoBack = true; + expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); + expect(goBack).not.toHaveBeenCalled(); + expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); + expect(goBack).toHaveBeenCalledOnce(); + expect(press("mouseDown", "forward")).toHaveBeenCalledOnce(); + expect(press("mouseUp", "forward")).toHaveBeenCalledOnce(); + expect(goForward).toHaveBeenCalledOnce(); + for (const button of ["left", "right"]) { + expect(press("mouseDown", button)).not.toHaveBeenCalled(); + expect(press("mouseUp", button)).not.toHaveBeenCalled(); + } + expect(goBack).toHaveBeenCalledOnce(); + expect(goForward).toHaveBeenCalledOnce(); + // The guest replays dropped presses for human input and recordings, in CSS px. + expect(send.mock.calls.filter(([channel]) => channel === "preview:thumb-press")).toEqual([ + ["preview:thumb-press", "down", 5, 5, 3], + ["preview:thumb-press", "up", 5, 5, 3], + ["preview:thumb-press", "down", 5, 5, 3], + ["preview:thumb-press", "up", 5, 5, 3], + ["preview:thumb-press", "down", 5, 5, 4], + ["preview:thumb-press", "up", 5, 5, 4], + ]); + }), + ), + ); + effectIt.effect("keeps editing and forwarded shortcuts in whichever tab holds focus", () => withManager((manager) => Effect.gen(function* () { @@ -812,6 +1015,150 @@ describe("PreviewManager", () => { ), ); + effectIt.effect.each([ + ["darwin", true], + ["linux", false], + ["win32", false], + ] as const)( + "lets the page and its iframes claim the find and zoom shortcuts before the host acts on %s", + ([platform, usesMeta]) => + withManager( + (manager) => + Effect.gen(function* () { + const preview = makeFaviconWebContents(); + const send = vi.fn(); + const mainFrame = { processId: 1, routingId: 1 }; + Object.assign(preview.webContents, { + hostWebContents: { isDestroyed: () => false, send }, + mainFrame, + focusedFrame: mainFrame, + }); + fromId.mockReturnValue(preview.webContents); + yield* manager.createTab("tab_page_find"); + yield* manager.registerWebview("tab_page_find", 42); + yield* manager.setForwardedShortcuts([ + { command: "preview.find", shortcut: parseKeybindingShortcut("mod+f")! }, + { command: "preview.zoomIn", shortcut: parseKeybindingShortcut("mod+=")! }, + ]); + const beforeInput = preview.listeners.get("before-input-event")!; + const keepsZoom = vi.fn(); + beforeInput( + { preventDefault: keepsZoom } as never, + { + type: "keyDown", + key: "=", + code: "Equal", + meta: usesMeta, + control: !usesMeta, + shift: false, + alt: false, + } as never, + ); + expect(keepsZoom).not.toHaveBeenCalled(); + const findKey = { + type: "keyDown", + key: "f", + code: "KeyF", + meta: usesMeta, + control: !usesMeta, + }; + const preventDefault = vi.fn(); + + beforeInput( + { preventDefault } as never, + { ...findKey, shift: false, alt: false } as never, + ); + expect(preventDefault).not.toHaveBeenCalled(); + expect(send).not.toHaveBeenCalled(); + + const ipcOn = (preview.webContents as Electron.WebContents).ipc.on as ReturnType< + typeof vi.fn + >; + const pageUnhandledShortcut = ipcOn.mock.calls.find( + ([channel]) => channel === "preview:page-unhandled-shortcut", + )![1]; + pageUnhandledShortcut( + {}, + { + key: "f", + code: "KeyF", + metaKey: usesMeta, + ctrlKey: !usesMeta, + shiftKey: false, + altKey: false, + }, + ); + expect(send).toHaveBeenCalledExactlyOnceWith("desktop:menu-action", "preview.find"); + + Object.assign(preview.webContents, { focusedFrame: { processId: 1, routingId: 2 } }); + beforeInput( + { preventDefault } as never, + { ...findKey, shift: false, alt: false } as never, + ); + expect(preventDefault).not.toHaveBeenCalled(); + expect(send).toHaveBeenCalledOnce(); + + Object.assign(preview.webContents, { focusedFrame: mainFrame }); + yield* manager.setForwardedShortcuts([ + { command: "preview.find", shortcut: parseKeybindingShortcut("ctrl+alt+8")! }, + ]); + pageUnhandledShortcut( + {}, + { + key: "[", + code: "Digit8", + metaKey: false, + ctrlKey: true, + shiftKey: false, + altKey: true, + }, + ); + expect(send).toHaveBeenCalledTimes(usesMeta ? 2 : 1); + }), + platform, + ), + ); + + effectIt.effect("searches the guest page and reports its match counts", () => + withManager((manager) => + Effect.gen(function* () { + const preview = makeFaviconWebContents(); + const findInPage = vi.fn(); + const stopFindInPage = vi.fn(); + Object.assign(preview.webContents, { findInPage, stopFindInPage }); + fromId.mockReturnValue(preview.webContents); + yield* manager.createTab("tab_find"); + yield* manager.registerWebview("tab_find", 42); + const reported = yield* Deferred.make(); + yield* manager.subscribeFindResults((event) => Deferred.succeed(reported, event)); + + yield* manager.findInPage("tab_find", "needle", { forward: true, newSession: true }); + expect(findInPage).toHaveBeenCalledExactlyOnceWith("needle", { + forward: true, + findNext: true, + }); + + preview.listeners.get("found-in-page")!( + {} as never, + { + requestId: 1, + activeMatchOrdinal: 2, + matches: 5, + finalUpdate: true, + } as never, + ); + expect(yield* Deferred.await(reported)).toEqual({ + tabId: "tab_find", + activeMatchOrdinal: 2, + matches: 5, + }); + + yield* manager.stopFindInPage("tab_find"); + expect(stopFindInPage).toHaveBeenCalledExactlyOnceWith("clearSelection"); + }), + ), + ); + effectIt.effect("isolates failed state listeners and continues delivery", () => { const loggedErrors: Array = []; const logger = Logger.make(({ message }) => { @@ -1545,6 +1892,30 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("captures final pixels after warmup fails and paint readiness settles", () => + withManager((manager) => + Effect.gen(function* () { + const paint = Promise.withResolvers(); + const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise); + capturePage + .mockRejectedValueOnce(new Error("UnknownVizError")) + .mockRejectedValueOnce(new Error("UnknownVizError")) + .mockRejectedValueOnce(new Error("UnknownVizError")) + .mockResolvedValue(makeStillImage("final-png")); + const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust(300); + expect(capturePage).toHaveBeenCalledTimes(3); + expect(writeFile).not.toHaveBeenCalled(); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); + paint.resolve(); + const artifact = yield* Fiber.join(fiber); + expect(capturePage).toHaveBeenCalledTimes(4); + expect(writeFile.mock.calls).toEqual([[artifact.path, Buffer.from("final-png")]]); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + }), + ), + ); + effectIt.effect("preserves both screenshots of the same site in the same millisecond", () => withManager((manager) => Effect.gen(function* () { @@ -1558,6 +1929,8 @@ describe("PreviewManager", () => { const capturePage = vi .fn<() => Promise>>() .mockResolvedValueOnce(pngImage(firstPng)) + .mockResolvedValueOnce(pngImage(firstPng)) + .mockResolvedValueOnce(pngImage(secondPng)) .mockResolvedValueOnce(pngImage(secondPng)); fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); yield* manager.createTab("tab_1"); @@ -1578,6 +1951,115 @@ describe("PreviewManager", () => { ), ); + effectIt.effect( + "waits for paint before capturing and restores rendering after overlapping requests", + () => + withManager((manager) => + Effect.gen(function* () { + const paints = [Promise.withResolvers(), Promise.withResolvers()]; + const pendingPaints = paints.map((paint) => paint.promise); + const { image, capturePage, wc, capture } = yield* setupStill(manager); + holdStillImagePaint(wc, pendingPaints); + const first = Promise.withResolvers(); + const second = Promise.withResolvers(); + capturePage + .mockResolvedValueOnce(makeStillImage("discarded-warmup")) + .mockResolvedValueOnce(makeStillImage("discarded-warmup")) + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise); + const hostThrottling = vi.fn(); + yield* manager.setMainWindow({ + isDestroyed: () => false, + once: vi.fn(), + webContents: { setBackgroundThrottling: hostThrottling }, + } as never); + const one = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); + const two = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust(0); + expect(capturePage).toHaveBeenCalledTimes(2); + expect(pendingPaints).toHaveLength(0); + expect(writeFile).not.toHaveBeenCalled(); + expect(hostThrottling.mock.calls).toEqual([[false]]); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); + paints.forEach((paint) => paint.resolve()); + yield* TestClock.adjust(0); + expect(capturePage).toHaveBeenCalledTimes(4); + first.resolve(image); + yield* Fiber.join(one); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); + second.resolve(image); + yield* Fiber.join(two); + const saved = writeFile.mock.calls.map(([, bytes]) => bytes); + expect(saved).toEqual([image.toPNG(), image.toPNG()]); + expect(hostThrottling.mock.calls).toEqual([[false], [true]]); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + }), + ), + ); + + effectIt.effect("keeps picture-in-picture rendering after a still image completes", () => + withManager((manager) => + Effect.gen(function* () { + const { image, capturePage, wc, capture } = yield* setupStill(manager); + const pending = Promise.withResolvers(); + capturePage + .mockResolvedValueOnce(image) + .mockResolvedValueOnce(makeStillImage("discarded-warmup")) + .mockReturnValueOnce(pending.promise); + const { pictureInPictureWindow } = makeTestPictureInPictureWindow(); + browserWindowConstructor.mockImplementation(function () { + return pictureInPictureWindow; + }); + yield* manager.openPictureInPicture("tab_still"); + const still = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust(0); + expect(capturePage).toHaveBeenCalledTimes(3); + expect(writeFile).not.toHaveBeenCalled(); + pending.resolve(image); + yield* Fiber.join(still); + expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); + yield* manager.closePictureInPicture("tab_still"); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + }), + ), + ); + + effectIt.effect("keeps a pending still image rendering when recording ends", () => + withManager((manager) => + Effect.gen(function* () { + const { image, capturePage, wc, capture } = yield* setupStill(manager); + const pending = Promise.withResolvers(); + capturePage.mockResolvedValueOnce(image).mockReturnValue(pending.promise); + yield* manager.startRecording("tab_still"); + const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust(0); + yield* manager.stopRecording("tab_still"); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); + pending.resolve(image); + yield* Fiber.join(fiber); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + }), + ), + ); + + effectIt.effect("saves available pixels when paint readiness never settles", () => + withManager((manager) => + Effect.gen(function* () { + const paint = Promise.withResolvers(); + const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise); + const first = yield* Effect.exit(capture).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* TestClock.adjust(1_001); + expect(Exit.isSuccess(yield* Fiber.join(first))).toBe(true); + expect(capturePage).toHaveBeenCalledTimes(2); + expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]); + expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + }), + ), + ); + effectIt.effect("keeps every recorded guest unthrottled until its frame capture stops", () => withManager((manager) => Effect.gen(function* () { @@ -1924,7 +2406,7 @@ describe("PreviewManager", () => { expect(yield* nextType).toBe("attached"); yield* manager.closeTab("tab_1"); expect(yield* nextType).toBe("detached"); - }).pipe(Effect.provide(managerLayer()), Effect.scoped), + }).pipe(Effect.provide(managerLayer())), ); effectIt.effect( @@ -1981,11 +2463,168 @@ describe("PreviewManager", () => { }), ); expect(yield* Queue.take(capturing)).toBe(true); + yield* manager.setCaptureDrawn("tab_1", true); screenshot.resolve({ data: "" }); expect(yield* Queue.take(capturing)).toBe(false); + }).pipe(Effect.provide(managerLayer())), + ); + + effectIt.effect( + "opens a new-tab link in the background only when the agent's input led to it", + () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.DesktopBrowserHost; + const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; + const contents = Object.assign( + makeTestPreviewWebContents(async () => { + throw new Error("unused"); + }, 42), + { + isDevToolsOpened: () => false, + getUserAgent: () => "Electron", + focusedFrame: null, + }, + ); + fromId.mockReturnValue(contents); + const manager = yield* PreviewManager.PreviewManager; + const openLinks = yield* Queue.unbounded(); + yield* manager.subscribeOpenLinks(({ background }) => + Queue.offer(openLinks, background).pipe(Effect.asVoid), + ); + const attached = yield* Deferred.make(); + yield* host.events.pipe( + Stream.runForEach((line) => + new TextDecoder().decode(line).includes('"type":"attached"') + ? Deferred.succeed(attached, undefined) + : Effect.void, + ), + Effect.forkScoped, + ); + yield* manager.createTab("tab_1", { serverTab }); + yield* manager.registerWebview("tab_1", 42); + yield* Deferred.await(attached); + const openWindow = vi.mocked(contents.setWindowOpenHandler).mock.calls[0]![0]; + const openBlankLink = Effect.suspend(() => { + openWindow({ + url: "https://example.com/next", + disposition: "foreground-tab", + } as Electron.HandlerDetails); + return Queue.take(openLinks); + }); + + expect(yield* openBlankLink).toBe(false); + + yield* host.handleCommandLine( + JSON.stringify({ + type: "cdp", + ...serverTab, + message: JSON.stringify({ + id: 1, + method: "Runtime.evaluate", + params: { expression: "document.querySelector('a').click()" }, + sessionId: "t3-preview-page", + }), + }), + ); + expect(yield* openBlankLink).toBe(true); + + // A person clicking in the guest itself gives it a focused frame. + Object.assign(contents, { focusedFrame: {} }); + expect(yield* openBlankLink).toBe(false); }).pipe(Effect.provide(managerLayer()), Effect.scoped), ); + effectIt.effect("reports early and subsequent load failures for the current guest", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.DesktopBrowserHost; + const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; + const lines = yield* Queue.unbounded(); + yield* host.events.pipe( + Stream.runForEach((line) => Queue.offer(lines, new TextDecoder().decode(line))), + Effect.forkScoped({ startImmediately: true }), + ); + const makeGuest = (id: number) => { + const listeners = new Map void>>(); + const wc = Object.assign( + makeTestPreviewWebContents( + async () => ({ + toJPEG: () => Buffer.from("jpeg"), + getSize: () => ({ width: 100, height: 80 }), + }), + id, + ), + { + isDevToolsOpened: () => false, + getUserAgent: () => "Electron", + once: vi.fn(), + on: (event: string, listener: (...args: unknown[]) => void) => { + listeners.set(event, [...(listeners.get(event) ?? []), listener]); + }, + }, + ); + const emit = (event: string, ...args: unknown[]) => { + for (const listener of listeners.get(event) ?? []) listener(...args); + }; + return { + wc, + emit, + fail: (url: string) => + emit("did-fail-load", {}, -202, "ERR_CERT_AUTHORITY_INVALID", url, true), + }; + }; + const initial = makeGuest(42); + const replacement = makeGuest(43); + const manager = yield* PreviewManager.PreviewManager; + const statuses: PreviewManager.PreviewNavStatus[] = []; + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + statuses.push(state.navStatus); + }), + ); + yield* manager.createTab("tab_1", { serverTab }); + yield* manager.prepareWebview(initial.wc); + yield* manager.prepareWebview(replacement.wc); + initial.fail("https://first.local/"); + initial.emit("did-start-navigation", { isMainFrame: false, isSameDocument: false }); + initial.emit("did-start-loading"); + replacement.fail("https://second.local/"); + const failure = (url: string) => ({ + type: "loadFailed", + ...serverTab, + url, + code: -202, + description: "ERR_CERT_AUTHORITY_INVALID", + }); + + fromId.mockReturnValue(initial.wc); + yield* manager.registerWebview("tab_1", 42); + expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab }); + expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://first.local/")); + + fromId.mockReturnValue(replacement.wc); + yield* manager.registerWebview("tab_1", 43); + expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab }); + expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab }); + expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://second.local/")); + + // A callback queued by the old guest must not report a failure for its replacement. + initial.fail("https://stale.local/"); + replacement.fail("https://current.local/"); + expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://current.local/")); + expect(statuses).not.toContainEqual(expect.objectContaining({ url: "https://stale.local/" })); + + const retried = makeGuest(44); + yield* manager.prepareWebview(retried.wc); + retried.fail("https://retry.local/"); + retried.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }); + fromId.mockReturnValue(retried.wc); + yield* manager.registerWebview("tab_1", 44); + expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab }); + expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab }); + expect(statuses.at(-1)?.kind).toBe("Success"); + }).pipe(Effect.provide(managerLayer())), + ); + effectIt.effect("discards a screenshot that resolves after its guest is replaced", () => withManager((manager) => Effect.gen(function* () { @@ -2145,6 +2784,116 @@ describe("PreviewManager", () => { ), ); + effectIt.effect( + "publishes human ownership only on transitions while retaining every recording press", + () => + withManager((manager) => + Effect.gen(function* () { + let humanInput: ((input: unknown) => void) | undefined; + const contents = makeTestPreviewWebContents(async () => ({ + toJPEG: () => Buffer.from("frame"), + getSize: () => ({ width: 800, height: 600 }), + })); + contents.ipc.on = (channel, callback) => { + if (channel === "preview:human-input") + humanInput = (input) => callback({} as Electron.IpcMainEvent, input); + return contents.ipc; + }; + fromId.mockReturnValue(contents); + yield* manager.createTab("tab_human"); + yield* manager.registerWebview("tab_human", 42); + yield* manager.startRecording("tab_human", { + showKeyPresses: true, + showMousePresses: true, + }); + const controllers: string[] = []; + const feedback = yield* Queue.unbounded(); + webviewSend.mockImplementation((channel) => { + if (channel === "preview:recording-controller") Queue.offerUnsafe(feedback, undefined); + }); + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + controllers.push(state.controller); + }), + ); + for (const press of [ + { kind: "pointer", x: 10, y: 20, button: 0 }, + { kind: "pointer", x: 30, y: 40, button: 0 }, + { kind: "key", key: "a", code: "KeyA" }, + ]) { + humanInput?.(press); + yield* Queue.take(feedback); + } + expect(controllers).toEqual(["human"]); + expect( + webviewSend.mock.calls.filter( + ([channel]) => channel === "preview:recording-controller", + ), + ).toEqual([ + ["preview:recording-controller", "human", { x: 10, y: 20 }], + ["preview:recording-controller", "human", { x: 30, y: 40 }], + ["preview:recording-controller", "human", undefined], + ]); + yield* TestClock.adjust(750); + expect(controllers).toEqual(["human", "none"]); + }), + ), + ); + + effectIt.effect("keeps human ownership until the last input's idle deadline", () => + withManager((manager) => + Effect.gen(function* () { + let humanInput: ((input: unknown) => void) | undefined; + const contents = makeTestPreviewWebContents(async () => ({ + toJPEG: () => Buffer.from("frame"), + getSize: () => ({ width: 800, height: 600 }), + })); + contents.ipc.on = (channel, callback) => { + if (channel === "preview:human-input") + humanInput = (input) => callback({} as Electron.IpcMainEvent, input); + return contents.ipc; + }; + fromId.mockReturnValue(contents); + yield* manager.createTab("tab_idle"); + yield* manager.registerWebview("tab_idle", 42); + const controllers: string[] = []; + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + controllers.push(state.controller); + }), + ); + const press = () => humanInput?.({ kind: "key", key: "a", code: "KeyA" }); + press(); + yield* TestClock.adjust(500); + press(); + yield* TestClock.adjust(749); + expect(controllers).toEqual(["human"]); + yield* TestClock.adjust(1); + expect(controllers).toEqual(["human", "none"]); + + press(); + yield* TestClock.adjust(500); + const staleInput = humanInput; + const replacement = makeTestPreviewWebContents( + async () => ({ + toJPEG: () => Buffer.from("frame"), + getSize: () => ({ width: 800, height: 600 }), + }), + 43, + ); + replacement.ipc.on = contents.ipc.on; + contents.isDestroyed = () => true; + fromId.mockImplementation((id) => (id === 43 ? replacement : null)); + yield* manager.registerWebview("tab_idle", 43); + expect(controllers.at(-1)).toBe("none"); + const count = controllers.length; + staleInput?.({ kind: "key", key: "b", code: "KeyB" }); + yield* TestClock.adjust(750); + expect(controllers).toHaveLength(count); + }), + ), + ); + effectIt.effect("gates recording decorations and isolates failed subscribers", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index c668c39061..32ac876996 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -12,6 +12,7 @@ import type { DesktopPreviewAnnotationVoiceState, DesktopPreviewColorScheme, DesktopPreviewFavicon, + DesktopPreviewFindResultEvent, DesktopPreviewOpenLinkEvent, DesktopPreviewPointerEvent, PreviewAnnotationPayload, @@ -23,6 +24,7 @@ import type { DesktopPreviewScreenshotArtifact, DesktopPreviewTabDefaults, PreviewForwardedShortcut, + PreviewAutomationLoadError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { matchesKeybindingShortcut } from "@t3tools/shared/keybindings"; @@ -79,12 +81,13 @@ import { CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, HUMAN_INPUT_CHANNEL, - MOUSE_NAVIGATE_CHANNEL, + PAGE_UNHANDLED_SHORTCUT_CHANNEL, RECORDING_CURSOR_CHANNEL, RECORDING_INPUT_CHANNEL, RECORDING_CONTROLLER_CHANNEL, RECORDING_POINTER_CHANNEL, START_PICK_CHANNEL, + THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; @@ -133,6 +136,7 @@ const PICTURE_IN_PICTURE_JPEG_QUALITY = 80; const CAPTURE_PAGE_RETRY_ATTEMPTS = 3; const CAPTURE_PAGE_RETRY_DELAY_MS = 120; const CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS = 1_000; +const BUSY_PAGE_PROBE_MS = 1_000; const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480; const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320; const PICTURE_IN_PICTURE_MIN_WIDTH = 240; @@ -383,7 +387,8 @@ interface ManagedListeners { readonly webContents: Electron.WebContents; } -type FrameCaptureConsumer = "picture-in-picture" | "recording"; +// Each still-image request owns a separate, short-lived rendering lease. +type FrameCaptureConsumer = "picture-in-picture" | "recording" | symbol; interface FrameCaptureSession { readonly recordingInputOptions?: RecordingInputOptions; @@ -437,6 +442,26 @@ type PointerEventListener = (event: DesktopPreviewPointerEvent) => Effect.Effect type OpenLinkListener = (event: DesktopPreviewOpenLinkEvent) => Effect.Effect; +type FindResultListener = (event: DesktopPreviewFindResultEvent) => Effect.Effect; + +const PAGE_FIRST_FORWARDED_COMMANDS: ReadonlySet = new Set([ + "preview.find", + "preview.zoomIn", + "preview.zoomOut", + "preview.resetZoom", +]); + +const decodePageShortcutKeys = Schema.decodeUnknownOption( + Schema.Struct({ + key: Schema.String, + code: Schema.String, + metaKey: Schema.Boolean, + ctrlKey: Schema.Boolean, + shiftKey: Schema.Boolean, + altKey: Schema.Boolean, + }), +); + // about:blank inherits relaxed guest preferences; external editor schemes must reach the OS handler. const POPUP_PROTOCOLS = new Set(["http:", "https:"]); @@ -543,9 +568,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const random = yield* SecureRandom.SecureRandom; const parentScope = yield* Scope.Scope; const browserHost = yield* DesktopBrowserHost.DesktopBrowserHost; + const browserSession = yield* BrowserSession.BrowserSession; const passkeys = yield* PreviewPasskeys.PreviewPasskeys; const context = yield* Effect.context(); const runFork = Effect.runForkWith(context); + const runPromise = Effect.runPromiseWith(context); const resolvedArtifactDirectory = path.resolve(artifactDirectory); let forwardedShortcuts: ReadonlyArray = []; @@ -557,6 +584,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const listenersRef = yield* Ref.make>(new Set()); const pointerEventListenersRef = yield* Ref.make>(new Set()); const openLinkListenersRef = yield* Ref.make>(new Set()); + const findResultListenersRef = yield* Ref.make>(new Set()); const recordingInputListenersRef = yield* Ref.make>( new Set(), ); @@ -584,6 +612,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function { readonly semaphore: Semaphore.Semaphore; users: number } >(); const tabLifecycleGenerations = new Map(); + // A guest can fail its first load before registerWebview installs its tab listeners. + const guestLoadFailures = new Map(); const attempt = (errorContext: PreviewOperationContext, evaluate: () => A) => Effect.try({ @@ -822,7 +852,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); const deliverEvent = ( - eventKind: "state-change" | "recording-input" | "pointer-event" | "open-link", + eventKind: "state-change" | "recording-input" | "pointer-event" | "open-link" | "find-result", tabId: string, delivery: () => Effect.Effect, ) => @@ -859,7 +889,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const update = Effect.fn("PreviewManager.update")(function* ( tabId: string, patch: Partial, - humanPoint?: { readonly x: number; readonly y: number }, ) { const updatedAt = yield* currentIso; const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => { @@ -875,17 +904,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); // syncTabAudible can commit after this update; emitIfCurrent prevents publishing a stale snapshot. if (Option.isSome(next)) { - if (patch.controller !== undefined && next.value.webContentsId != null) { - const capture = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId); - const webContentsId = next.value.webContentsId; - if (capture?.consumers.has("recording")) { - yield* attempt({ operation: "recording.controller", tabId }, () => { - const contents = webContents.fromId(webContentsId); - if (contents && !contents.isDestroyed()) - contents.send(RECORDING_CONTROLLER_CHANNEL, patch.controller, humanPoint); - }).pipe(Effect.ignore); - } - } yield* emitIfCurrent(tabId, next.value); } }); @@ -1078,28 +1096,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ), scope, ); - const handleDebuggerMessage = Effect.fnUntraced(function* ( - method: string, - params: Record, - ) { - if (method === "Page.screencastFrame") { - const sessionId = params["sessionId"]; - if (typeof sessionId === "number") { - yield* attemptPromise( - { - operation: "ackScreencastFrame", - webContentsId: wc.id, - }, - () => wcDebugger.sendCommand("Page.screencastFrameAck", { sessionId }), - ).pipe(Effect.ignore); - } - } + const handleDebuggerMessage = Effect.fnUntraced(function* (method: string) { if (method === "Runtime.consoleAPICalled" || method === "Runtime.exceptionThrown") { yield* Queue.offer(consoleReleases, undefined); } }); - const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => { - runFork(handleDebuggerMessage(method, params)); + const onMessage: BrowserControlSession["onMessage"] = (_event, method) => { + runFork(handleDebuggerMessage(method)); }; const control: BrowserControlSession = { webContentsId: wc.id, @@ -1378,34 +1381,111 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function validatedUrl: string, isMainFrame: boolean, ): void => { - if (code === -3 || !isMainFrame) return; + if (code === -3 || !isMainFrame || wc.isDestroyed()) return; + const url = validatedUrl || wc.getURL(); runFork( - update(tabId, { - navStatus: { - kind: "LoadFailed", - url: validatedUrl || wc.getURL(), - title: wc.getTitle(), - code, - description, - }, + Effect.gen(function* () { + const updatedAt = yield* currentIso; + const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => { + const current = tabs.get(tabId); + if ( + !current || + current.webContentsId !== wc.id || + wc.isDestroyed() || + webContents.fromId(wc.id) !== wc + ) { + return [Option.none(), tabs] as const; + } + const state: PreviewTabState = { + ...current, + navStatus: { kind: "LoadFailed", url, title: wc.getTitle(), code, description }, + updatedAt, + }; + return [ + Option.some(state), + replaceMap(tabs, (copy) => copy.set(tabId, state)), + ] as const; + }); + if (Option.isNone(next)) return; + const current = (yield* SynchronizedRef.get(tabsRef)).get(tabId); + if (current?.webContentsId !== wc.id || current.navStatus !== next.value.navStatus) + return; + if (current.serverTab) { + browserHost.loadFailed(current.serverTab, { url, code, description }); + } + yield* emitIfCurrent(tabId, next.value); }), ); }; + let humanInputWorker = false; + let humanInputDeadline = 0; + let listening = true; + const publishHumanController = Effect.fn("PreviewManager.publishHumanController")(function* ( + controller: "human" | "none", + humanPoint?: { readonly x: number; readonly y: number }, + ) { + const now = yield* currentMillis; + const updatedAt = yield* currentIso; + const result = yield* SynchronizedRef.modify(tabsRef, (tabs) => { + const current = tabs.get(tabId); + if ( + !current || + current.webContentsId !== wc.id || + (controller === "human" + ? !listening || webContents.fromId(wc.id) !== wc + : current.controller !== "human" || humanInputDeadline > now) + ) + return [undefined, tabs] as const; + const changed = current.controller !== controller; + const state = changed ? { ...current, controller, updatedAt } : current; + return [ + { state, changed }, + changed + ? replaceMap(tabs, (copy) => { + copy.set(tabId, state); + }) + : tabs, + ] as const; + }); + if (!result) return; + const capture = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId); + if (capture?.consumers.has("recording")) { + yield* attempt({ operation: "recording.controller", tabId }, () => { + if (!wc.isDestroyed()) wc.send(RECORDING_CONTROLLER_CHANNEL, controller, humanPoint); + }).pipe(Effect.ignore); + } + if (result.changed) yield* emitIfCurrent(tabId, result.state); + }); + yield* Scope.addFinalizer( + scope, + Effect.gen(function* () { + listening = false; + humanInputDeadline = 0; + yield* publishHumanController("none"); + }), + ); const handleHumanInput = Effect.fn("PreviewManager.handleHumanInput")(function* ( rawSignal?: unknown, ) { - yield* update( - tabId, - { controller: "human" }, + if (!listening) return; + humanInputDeadline = (yield* currentMillis) + 750; + if (!humanInputWorker) { + humanInputWorker = true; + yield* Effect.gen(function* () { + let remaining: number; + while ((remaining = humanInputDeadline - (yield* currentMillis)) > 0) { + yield* Effect.sleep(remaining); + } + humanInputWorker = false; + yield* publishHumanController("none"); + }).pipe(Effect.forkIn(scope)); + } + yield* publishHumanController( + "human", isPreviewInputSignal(rawSignal) && rawSignal.kind === "pointer" ? { x: rawSignal.x, y: rawSignal.y } : undefined, ); - yield* Effect.sleep(750); - const tabs = yield* SynchronizedRef.get(tabsRef); - if (tabs.get(tabId)?.controller === "human") { - yield* update(tabId, { controller: "none" }); - } }); const recordingInput = (_event: unknown, input: unknown) => { if (!isRecordingInput(input)) return; @@ -1425,18 +1505,41 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), ); }; + // Chromium splits one search across several updates (the ordinal and the + // final count can land separately), so every update is forwarded. + const foundInPage = (_event: unknown, result: Electron.Result): void => { + runFork( + emitFindResult({ + tabId, + activeMatchOrdinal: result.activeMatchOrdinal, + matches: result.matches, + }), + ); + }; const humanInput = (_event: unknown, rawSignal?: unknown): void => { runFork(handleHumanInput(rawSignal)); }; - const mouseNavigate = (_event: unknown, payload?: unknown): void => { - const direction = - typeof payload === "object" && payload !== null && "direction" in payload - ? (payload as { direction?: unknown }).direction - : undefined; - if (direction !== "back" && direction !== "forward") return; + // Chromium navigates the outermost WebContents (the host app) on thumb buttons, even from guest iframes. + const beforeMouse = (event: Electron.Event, mouse: Electron.MouseInputEvent): void => { + // Electron reports thumb buttons as "back" and "forward", which its typings omit. + const button: string | undefined = mouse.button; + if (button !== "back" && button !== "forward") return; + if (mouse.type !== "mouseDown" && mouse.type !== "mouseUp") return; + event.preventDefault(); + // The page never sees the press, so the guest replays it; these coordinates are DIPs, not CSS px. + const zoom = wc.getZoomFactor(); + const phase = mouse.type === "mouseDown" ? "down" : "up"; + wc.send( + THUMB_PRESS_CHANNEL, + phase, + mouse.x / zoom, + mouse.y / zoom, + button === "back" ? 3 : 4, + ); + if (phase !== "up") return; runFork( attempt({ operation: "mouseNavigate", tabId, webContentsId: wc.id }, () => { - if (direction === "back") { + if (button === "back") { if (wc.navigationHistory.canGoBack()) wc.navigationHistory.goBack(); } else if (wc.navigationHistory.canGoForward()) { wc.navigationHistory.goForward(); @@ -1461,6 +1564,20 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function syncMenuShortcuts(window.webContents, input); }); }; + const findForwardedShortcut = (keys: Parameters[0]) => + !( + hostPlatform !== "darwin" && + keys.ctrlKey && + keys.altKey && + /^(?:[^a-zA-Z0-9]|Dead)$/u.test(keys.key) + ) && + forwardedShortcuts.find(({ shortcut }) => + matchesKeybindingShortcut( + keys, + shortcut, + hostPlatform === "darwin" ? "MacIntel" : hostPlatform, + ), + ); const beforeInput = (event: Electron.Event, input: Electron.Input): void => { syncMenuShortcuts(wc, input); const host = wc.hostWebContents; @@ -1470,27 +1587,18 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function host && !host.isDestroyed() && holdsKeyboardFocus(wc) && - !( - hostPlatform !== "darwin" && - input.control && - input.alt && - /^(?:[^a-zA-Z0-9]|Dead)$/u.test(input.key) - ) && - forwardedShortcuts.find(({ shortcut }) => - matchesKeybindingShortcut( - { - key: input.key, - code: input.code, - metaKey: input.meta, - ctrlKey: input.control, - shiftKey: input.shift, - altKey: input.alt, - }, - shortcut, - hostPlatform === "darwin" ? "MacIntel" : hostPlatform, - ), - ); + findForwardedShortcut({ + key: input.key, + code: input.code, + metaKey: input.meta, + ctrlKey: input.control, + shiftKey: input.shift, + altKey: input.alt, + }); if (forwarded && host) { + // The page keeps these keys. Only the main-frame preload can report one it + // left unhandled, so a focused iframe (e.g. Google Docs' input) keeps its own find or zoom. + if (PAGE_FIRST_FORWARDED_COMMANDS.has(forwarded.command)) return; event.preventDefault(); if (!input.isAutoRepeat) { if ( @@ -1515,6 +1623,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function return; } }; + const pageUnhandledShortcut = (_event: unknown, rawKeys?: unknown): void => { + const host = wc.hostWebContents; + if (!host || host.isDestroyed() || !holdsKeyboardFocus(wc)) return; + const keys = decodePageShortcutKeys(rawKeys); + if (Option.isNone(keys)) return; + const forwarded = findForwardedShortcut(keys.value); + if (!forwarded || !PAGE_FIRST_FORWARDED_COMMANDS.has(forwarded.command)) return; + host.send(MENU_ACTION_CHANNEL, forwarded.command); + }; yield* Scope.addFinalizer( scope, attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => { @@ -1529,11 +1646,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.off("dom-ready", restoreRecordingCursor); wc.off("did-fail-load", failed as never); wc.off("audio-state-changed", audioStateChanged); + wc.off("found-in-page", foundInPage as never); wc.off("did-create-window", windowCreated); wc.off("before-input-event", beforeInput); + wc.off("before-mouse-event", beforeMouse); wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput); - wc.ipc.off(MOUSE_NAVIGATE_CHANNEL, mouseNavigate); + wc.ipc.off(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys(); }).pipe(Effect.ignore), ); @@ -1550,9 +1669,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.on("dom-ready", restoreRecordingCursor); wc.on("did-fail-load", failed as never); wc.on("audio-state-changed", audioStateChanged); + wc.on("found-in-page", foundInPage as never); wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.on(RECORDING_INPUT_CHANNEL, recordingInput); - wc.ipc.on(MOUSE_NAVIGATE_CHANNEL, mouseNavigate); + wc.ipc.on(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys = passkeys.attachGuest(wc); wc.setWindowOpenHandler((details) => { const action = previewWindowOpenAction(details); @@ -1565,7 +1685,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function emitOpenLink({ tabId, url: details.url, - background: details.disposition === "background-tab", + // A person's own click or key leaves the guest a focused frame; GuestInput hands + // focus back after the agent's press, so a foreground tab would take it again. + background: + details.disposition === "background-tab" || + (wc.focusedFrame === null && browserHost.agentLedPage(wc)), }), ); return { action: "deny" }; @@ -1579,6 +1703,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); wc.on("did-create-window", windowCreated); wc.on("before-input-event", beforeInput); + wc.on("before-mouse-event", beforeMouse); }); yield* Ref.update(attachedRef, (attached) => replaceMap(attached, (copy) => { @@ -1702,7 +1827,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); if (Option.isNone(tab)) return; const closedTab = tab.value; - if (closedTab.serverTab) browserHost.setShown(closedTab.serverTab, undefined); + if (closedTab.serverTab) { + browserHost.setShown(closedTab.serverTab, undefined); + browserHost.setCaptureDrawn(closedTab.serverTab, undefined); + } if (closedTab.webContentsId != null) { yield* Effect.all( [ @@ -1838,11 +1966,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ] as const; } const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null; + const failure = guestLoadFailures.get(webContentsId); const { favicon: _favicon, ...currentWithoutFavicon } = current; const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId, - navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus, + navStatus: + failure && (pendingUrl === null || pendingUrl === failure.url) + ? { kind: "LoadFailed", title: wc.getTitle(), ...failure } + : pendingUrl === null + ? computeNavStatus(wc) + : current.navStatus, canGoBack: wc.navigationHistory.canGoBack(), canGoForward: wc.navigationHistory.canGoForward(), audible: attachedAudible, @@ -1910,7 +2044,19 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { yield* rendererHistory.register(wc, { surface: "preview" }); const webContentsId = wc.id; + wc.on("did-start-navigation", (event) => { + if (event.isMainFrame && !event.isSameDocument) guestLoadFailures.delete(webContentsId); + }); + wc.on("did-fail-load", (_event, code, description, validatedUrl, isMainFrame) => { + if (code === -3 || !isMainFrame) return; + guestLoadFailures.set(webContentsId, { + url: validatedUrl || wc.getURL(), + code, + description, + }); + }); wc.once("destroyed", () => { + guestLoadFailures.delete(webContentsId); runFork(hideDestroyedGuest(webContentsId)); runFork(detachControlSession(webContentsId)); }); @@ -1924,6 +2070,28 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); + /** + * A same-site navigation reuses the renderer, so it never commits while a page script holds it. + * Runs before the navigation starts: Chromium does not deliver a terminate once one is pending. + */ + const leaveBusyPage = Effect.fn("PreviewManager.leaveBusyPage")(function* ( + wc: Electron.WebContents, + ) { + const control = (yield* SynchronizedRef.get(controlSessionsRef)).get(wc.id); + if (!control) return; + const answered = yield* Effect.promise(() => + control.debugger.sendCommand("Runtime.evaluate", { expression: "0" }).then( + () => undefined, + () => undefined, + ), + ).pipe(Effect.timeoutOption(BUSY_PAGE_PROBE_MS)); + if (Option.isSome(answered)) return; + // Not awaited: a renderer blocked on something other than script may never acknowledge it. + yield* Effect.sync(() => { + void control.debugger.sendCommand("Runtime.terminateExecution").catch(() => undefined); + }); + }); + const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) { const url = yield* attempt({ operation: "navigate.normalizeUrl", tabId }, () => normalizePreviewUrl(rawUrl), @@ -2006,6 +2174,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); return; } + yield* leaveBusyPage(wc); if (wc.getURL() === url) { yield* attempt({ operation: "navigate.reload", tabId, webContentsId: wc.id }, () => wc.reload(), @@ -2041,17 +2210,44 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* attempt({ operation, tabId, webContentsId: wc.id }, () => use(wc)); }); + const leavePage = Effect.fn("PreviewManager.leavePage")(function* ( + operation: string, + tabId: string, + use: (wc: Electron.WebContents) => void, + ) { + const wc = yield* requireWebContents(tabId); + yield* leaveBusyPage(wc); + yield* attempt({ operation, tabId, webContentsId: wc.id }, () => use(wc)); + }); + const goBack = (tabId: string) => - withWebContents("goBack", tabId, (wc) => { + leavePage("goBack", tabId, (wc) => { if (wc.navigationHistory.canGoBack()) wc.navigationHistory.goBack(); }); const goForward = (tabId: string) => - withWebContents("goForward", tabId, (wc) => { + leavePage("goForward", tabId, (wc) => { if (wc.navigationHistory.canGoForward()) wc.navigationHistory.goForward(); }); - const refresh = (tabId: string) => withWebContents("refresh", tabId, (wc) => wc.reload()); + const refresh = (tabId: string) => leavePage("refresh", tabId, (wc) => wc.reload()); + const stopLoading = (tabId: string) => withWebContents("stopLoading", tabId, (wc) => wc.stop()); const hardReload = (tabId: string) => - withWebContents("hardReload", tabId, (wc) => wc.reloadIgnoringCache()); + leavePage("hardReload", tabId, (wc) => wc.reloadIgnoringCache()); + const findInPage = ( + tabId: string, + text: string, + options: { readonly forward: boolean; readonly newSession: boolean }, + ) => + withWebContents("findInPage", tabId, (wc) => { + // Electron's `findNext` means "begin a new session", not "go to the next match". + wc.findInPage(text, { forward: options.forward, findNext: options.newSession }); + }); + const stopFindInPage = (tabId: string) => + withWebContents("stopFindInPage", tabId, (wc) => wc.stopFindInPage("clearSelection")).pipe( + Effect.catchTags({ + PreviewTabNotFoundError: () => Effect.void, + PreviewWebContentsNotFoundError: () => Effect.void, + }), + ); const openDevTools = Effect.fn("PreviewManager.openDevTools")(function* (tabId: string) { const wc = yield* requireWebContents(tabId); @@ -2356,14 +2552,27 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const beforeAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId); if (beforeAttach?.webContentsId !== wc.id) return; const control = yield* ensureControlSession(wc); + if (beforeAttach.serverTab) yield* listenToBrowserHost; const afterAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId); if (afterAttach?.webContentsId !== wc.id) { yield* detachControlSession(wc.id); return; } if (afterAttach.serverTab) { - yield* listenToBrowserHost; - browserHost.attach(afterAttach.serverTab, { webContents: wc, debugger: control.debugger }); + browserHost.attach(afterAttach.serverTab, { + webContents: wc, + debugger: control.debugger, + cookiesCleared: () => runPromise(browserSession.cookiesCleared(wc.session)), + }); + // CDP cannot recover a failure that happened before it attached. + const { navStatus } = afterAttach; + if (navStatus.kind === "LoadFailed") { + browserHost.loadFailed(afterAttach.serverTab, { + url: navStatus.url, + code: navStatus.code, + description: navStatus.description, + }); + } } if (afterAttach.colorScheme !== "system") { yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () => @@ -2429,12 +2638,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (serverTab) browserHost.setShown(serverTab, shown); }); + const setCaptureDrawn = Effect.fn("PreviewManager.setCaptureDrawn")(function* ( + tabId: string, + drawn: boolean, + ) { + const serverTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.serverTab; + if (serverTab) browserHost.setCaptureDrawn(serverTab, drawn); + }); + // A window reload or guest crash destroys the guest without the renderer reporting it hidden. // The renderer reports again once a new guest registers. const hideDestroyedGuest = Effect.fnUntraced(function* (webContentsId: number) { for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) { if (tab.webContentsId === webContentsId && tab.serverTab) { browserHost.setShown(tab.serverTab, false); + browserHost.setCaptureDrawn(tab.serverTab, false); } } }); @@ -2473,7 +2691,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const [createdAt, millis, image] = yield* Effect.all([ currentIso, currentMillis, - capturePageWithRetry( + captureStillImage( { operation: "captureScreenshot.capturePage", tabId, @@ -2521,6 +2739,100 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }; }); + const captureStillImage = Effect.fn("PreviewManager.captureStillImage")(function* ( + errorContext: PreviewOperationContext, + tabId: string, + wc: Electron.WebContents, + ) { + const consumer = Symbol("still-image"); + return yield* Effect.acquireUseRelease( + startFrameCapture(tabId, consumer), + () => + Effect.gen(function* () { + // A DOM mutation can precede its compositor frame even in a shown + // window. Keep the original guest rendering through the next paint; + // a hidden guest otherwise returns old pixels or never completes. + const probe = Effect.fn("PreviewManager.probeStillImagePaint")(function* ( + send: ( + method: string, + params?: Record, + ) => Effect.Effect, + ) { + // CDP executes against the current document without Electron's + // did-stop-loading gate. Isolate scheduling globals from page code. + const tree = (yield* send("Page.getFrameTree")) as + | { frameTree?: { frame?: { id?: string } } } + | undefined; + const frameId = tree?.frameTree?.frame?.id; + if (typeof frameId !== "string") + return yield* new PreviewOperationError({ + ...errorContext, + cause: new Error("The preview paint frame is unavailable."), + }); + const world = (yield* send("Page.createIsolatedWorld", { + frameId, + worldName: "t3-preview-still-image", + })) as { executionContextId?: number } | undefined; + if (typeof world?.executionContextId !== "number") + return yield* new PreviewOperationError({ + ...errorContext, + cause: new Error("The preview paint context is unavailable."), + }); + const response = (yield* send("Runtime.evaluate", { + // Settle and release scheduled work when only timers keep running. + // The outer deadline still bounds a frozen renderer. + expression: `new Promise(resolve => { let frame; const timer = setTimeout(() => { cancelAnimationFrame(frame); resolve(false); }, ${CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS}); frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => { clearTimeout(timer); resolve(true); }); }); })`, + contextId: world.executionContextId, + awaitPromise: true, + returnByValue: true, + })) as { result?: { value?: unknown }; exceptionDetails?: unknown } | undefined; + if (response?.exceptionDetails || response?.result?.value !== true) + return yield* new PreviewOperationError({ + ...errorContext, + cause: new Error("The preview paint boundary was not confirmed."), + }); + }); + const paintReady = Effect.gen(function* () { + // Only use an existing owned session; never attach or displace + // another debugger to obtain a screenshot. + const control = (yield* SynchronizedRef.get(controlSessionsRef)).get(wc.id); + if (!control) + return yield* new PreviewOperationError({ + ...errorContext, + cause: new Error("The preview paint session is unavailable."), + }); + return yield* probe((method, params) => + attemptPromise(errorContext, () => control.debugger.sendCommand(method, params)), + ); + }).pipe( + Effect.timeout(CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS), + Effect.catch((error) => + Effect.logWarning( + "Preview paint readiness was not confirmed; capturing available pixels with mutation freshness unconfirmed.", + { tabId, webContentsId: wc.id, error }, + ), + ), + ); + // Minimized guests can suspend frames even with throttling disabled. + // A native capture can resume them; discard its pixels and read again + // after the bounded paint probe. + const warmup = capturePageWithRetry(errorContext, tabId, wc).pipe( + Effect.catchTags({ + PreviewOperationError: (error) => + Effect.logWarning("Preview warmup capture failed; continuing with final capture.", { + tabId, + webContentsId: wc.id, + error, + }), + }), + ); + yield* Effect.all([paintReady, warmup], { concurrency: 2, discard: true }); + return yield* capturePageWithRetry(errorContext, tabId, wc); + }), + () => stopFrameCapture(tabId, consumer), + ); + }); + const capturePreviewFrame = Effect.fn("PreviewManager.capturePreviewFrame")(function* ( tabId: string, ) { @@ -3203,7 +3515,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function data: Uint8Array, ) { const [createdAt, millis] = yield* Effect.all([currentIso, currentMillis]); - const id = `browser-recording-${millis.toString(36)}`; + const uuid = yield* random.uuidV4(); + const id = `browser-recording-${millis.toString(36)}-${uuid.slice(0, 8)}`; const extension = recordingFileExtension(mimeType); const artifactPath = path.join(resolvedArtifactDirectory, `${id}.${extension}`); yield* fileSystem.makeDirectory(resolvedArtifactDirectory, { recursive: true }).pipe( @@ -3217,7 +3530,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), ), ); - yield* fileSystem.writeFile(artifactPath, data).pipe( + yield* fileSystem.writeFile(artifactPath, data, { flag: "wx" }).pipe( Effect.mapError( (cause) => new PreviewOperationError({ @@ -3345,6 +3658,16 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function { discard: true }, ); }); + const emitFindResult = Effect.fn("PreviewManager.emitFindResult")(function* ( + event: DesktopPreviewFindResultEvent, + ) { + const listeners = yield* Ref.get(findResultListenersRef); + yield* Effect.forEach( + listeners, + (listener) => deliverEvent("find-result", event.tabId, () => listener(event)), + { discard: true }, + ); + }); const subscribe = ( ref: Ref.Ref>, listener: A, @@ -3367,6 +3690,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function Ref.set(listenersRef, new Set()), Ref.set(pointerEventListenersRef, new Set()), Ref.set(openLinkListenersRef, new Set()), + Ref.set(findResultListenersRef, new Set()), Ref.set(recordingInputListenersRef, new Set()), ], { discard: true }, @@ -3381,6 +3705,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function closeTab, copyArtifactToClipboard, createTab, + findInPage, goBack, goForward, hardReload, @@ -3392,6 +3717,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function prepareWebview, reapplyZoom, refresh, + stopLoading, registerWebview, resetZoom: (tabId: string) => applyZoom(tabId, () => DEFAULT_ZOOM_FACTOR), setZoomFactor: (tabId: string, zoomFactor: number) => @@ -3402,6 +3728,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function setAnnotationSendEnabled, setAudioMuted, setShown, + setCaptureDrawn, setColorScheme, setMainWindow, setForwardedShortcuts: (shortcuts: ReadonlyArray) => @@ -3410,10 +3737,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), startRecording, closePictureInPicture, + stopFindInPage, stopRecording, subscribePointerEvents: (listener: PointerEventListener) => subscribe(pointerEventListenersRef, listener), subscribeOpenLinks: (listener: OpenLinkListener) => subscribe(openLinkListenersRef, listener), + subscribeFindResults: (listener: FindResultListener) => + subscribe(findResultListenersRef, listener), subscribeRecordingInputs: (listener: RecordingInputListener) => subscribe(recordingInputListenersRef, listener), subscribeStateChanges: (listener: Listener) => subscribe(listenersRef, listener), @@ -3590,11 +3920,18 @@ export class PreviewManager extends Context.Service< readonly goBack: (tabId: string) => Effect.Effect; readonly goForward: (tabId: string) => Effect.Effect; readonly refresh: (tabId: string) => Effect.Effect; + readonly stopLoading: (tabId: string) => Effect.Effect; readonly zoomIn: (tabId: string) => Effect.Effect; readonly zoomOut: (tabId: string) => Effect.Effect; readonly resetZoom: (tabId: string) => Effect.Effect; readonly reapplyZoom: () => Effect.Effect; readonly hardReload: (tabId: string) => Effect.Effect; + readonly findInPage: ( + tabId: string, + text: string, + options: { readonly forward: boolean; readonly newSession: boolean }, + ) => Effect.Effect; + readonly stopFindInPage: (tabId: string) => Effect.Effect; readonly setColorScheme: ( tabId: string, colorScheme: DesktopPreviewColorScheme, @@ -3608,6 +3945,7 @@ export class PreviewManager extends Context.Service< audioMuted: boolean, ) => Effect.Effect; readonly setShown: (tabId: string, shown: boolean) => Effect.Effect; + readonly setCaptureDrawn: (tabId: string, drawn: boolean) => Effect.Effect; readonly openDevTools: (tabId: string) => Effect.Effect; readonly clearCookies: ( partitions?: ReadonlyArray, @@ -3659,6 +3997,9 @@ export class PreviewManager extends Context.Service< readonly subscribeOpenLinks: ( listener: OpenLinkListener, ) => Effect.Effect; + readonly subscribeFindResults: ( + listener: FindResultListener, + ) => Effect.Effect; readonly subscribeRecordingInputs: ( listener: RecordingInputListener, ) => Effect.Effect; @@ -3755,15 +4096,19 @@ export const make = Effect.gen(function* PreviewManagerMake() { goBack: operations.goBack, goForward: operations.goForward, refresh: operations.refresh, + stopLoading: operations.stopLoading, zoomIn: operations.zoomIn, zoomOut: operations.zoomOut, resetZoom: operations.resetZoom, reapplyZoom: operations.reapplyZoom, hardReload: operations.hardReload, + findInPage: operations.findInPage, + stopFindInPage: operations.stopFindInPage, setColorScheme: operations.setColorScheme, setZoomFactor: operations.setZoomFactor, setAudioMuted: operations.setAudioMuted, setShown: operations.setShown, + setCaptureDrawn: operations.setCaptureDrawn, openDevTools: operations.openDevTools, clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) { yield* browserSession @@ -3808,6 +4153,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { subscribeStateChanges: operations.subscribeStateChanges, subscribePointerEvents: operations.subscribePointerEvents, subscribeOpenLinks: operations.subscribeOpenLinks, + subscribeFindResults: operations.subscribeFindResults, subscribeRecordingInputs: operations.subscribeRecordingInputs, }); }).pipe(Effect.withSpan("PreviewManager.make")); diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts new file mode 100644 index 0000000000..61d3941ba4 --- /dev/null +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -0,0 +1,107 @@ +import { expect, it, vi } from "vite-plus/test"; + +import { START_PICK_CHANNEL } from "./GuestProtocol.ts"; +import "./PickPreload.ts"; + +const ipcListeners = vi.hoisted(() => new Map void>>()); + +vi.mock("electron", () => ({ + ipcRenderer: { + on: (channel: string, listener: (...args: unknown[]) => void) => { + ipcListeners.set(channel, [...(ipcListeners.get(channel) ?? []), listener]); + }, + off: () => {}, + send: () => {}, + invoke: async () => undefined, + }, +})); + +vi.mock("react-grab/primitives", () => ({ getElementContext: async () => null })); + +const startAnnotation = (): ShadowRoot => { + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + disconnect() {} + }, + ); + using attachShadow = vi.spyOn(Element.prototype, "attachShadow"); + for (const listener of ipcListeners.get(START_PICK_CHANNEL) ?? []) listener({}, undefined, false); + const shadowRoot = attachShadow.mock.results[0]?.value; + if (!(shadowRoot instanceof ShadowRoot)) throw new Error("annotation overlay did not start"); + return shadowRoot; +}; + +it("switches tools from the keyboard after a toolbar button is clicked", () => { + const shadowRoot = startAnnotation(); + const region = Array.from(shadowRoot.querySelectorAll("button")).find( + (button) => button.textContent === "Region", + ); + if (!region) throw new Error("Region toolbar button not found"); + + region.focus(); + region.click(); + expect(document.documentElement.getAttribute("data-t3code-annotation-tool")).toBe("marquee"); + + region.dispatchEvent(new KeyboardEvent("keydown", { key: "v", bubbles: true, composed: true })); + + expect( + document.documentElement.getAttribute("data-t3code-annotation-tool"), + "V should switch to Select while focus is on a toolbar button", + ).toBe("select"); +}); + +it("keeps the tool while typing a tool key in the comment", () => { + const shadowRoot = startAnnotation(); + const comment = shadowRoot.querySelector("textarea"); + if (!comment) throw new Error("comment textarea not found"); + + comment.focus(); + comment.dispatchEvent(new KeyboardEvent("keydown", { key: "r", bubbles: true, composed: true })); + + expect(document.documentElement.getAttribute("data-t3code-annotation-tool")).toBe("select"); +}); + +it("keeps comment keystrokes away from the page's capture-phase shortcuts", () => { + const pageShortcut = vi.fn((event: KeyboardEvent) => event.preventDefault()); + window.addEventListener("keydown", pageShortcut, { capture: true }); + const shadowRoot = startAnnotation(); + const comment = shadowRoot.querySelector("textarea"); + if (!comment) throw new Error("comment textarea not found"); + + comment.focus(); + const space = new KeyboardEvent("keydown", { + key: " ", + code: "Space", + bubbles: true, + cancelable: true, + composed: true, + }); + comment.dispatchEvent(space); + window.removeEventListener("keydown", pageShortcut, { capture: true }); + + expect(pageShortcut).not.toHaveBeenCalled(); + expect(space.defaultPrevented).toBe(false); +}); + +it("keeps the annotation when Escape dismisses an IME candidate in the comment", () => { + const shadowRoot = startAnnotation(); + const comment = shadowRoot.querySelector("textarea"); + if (!comment) throw new Error("comment textarea not found"); + + comment.value = "draft"; + comment.focus(); + comment.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + isComposing: true, + bubbles: true, + cancelable: true, + composed: true, + }), + ); + + expect(shadowRoot.host.isConnected).toBe(true); + expect(comment.value).toBe("draft"); +}); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index dcb16b851d..42867b9d9c 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -20,6 +20,13 @@ import type { import { createAnnotationIdSource } from "./AnnotationIds.ts"; import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts"; +import { + addStrokePoint, + openStrokePath, + startStroke, + strokeBounds, + type StrokeGeometry, +} from "./AnnotationStroke.ts"; import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts"; import { installRecordingCursor } from "./RecordingCursor.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS } from "./RecordingInput.ts"; @@ -32,13 +39,15 @@ import { CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, HUMAN_INPUT_CHANNEL, - MOUSE_NAVIGATE_CHANNEL, + POINTER_DOWN_HOST_CHANNEL, + PAGE_UNHANDLED_SHORTCUT_CHANNEL, RECORDING_CURSOR_CHANNEL, RECORDING_POINTER_CHANNEL, RECORDING_KEY_CHANNEL, RECORDING_INPUT_CHANNEL, RECORDING_CONTROLLER_CHANNEL, START_PICK_CHANNEL, + THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui"; const INPUT_LAYER_ATTRIBUTE = "data-t3code-annotation-input"; @@ -148,6 +157,7 @@ interface AnnotationSession { teardown: (notifyMain: boolean) => void; applyTheme: (theme: DesktopPreviewAnnotationTheme) => void; setSendEnabled: (enabled: boolean) => void; + handleOverlayKey: (event: KeyboardEvent) => void; } let activeSession: AnnotationSession | null = null; @@ -184,6 +194,9 @@ const applyAnnotationTheme = ( const reportHumanPointerInput = (event: PointerEvent): void => { if (!event.isTrusted) return; + // The guest does not always take focus on a click, so the host's webview + // `focus` event can't be relied on to dismiss open menus and popovers. + ipcRenderer.sendToHost(POINTER_DOWN_HOST_CHANNEL); ipcRenderer.send(HUMAN_INPUT_CHANNEL, { kind: "pointer", x: event.clientX, @@ -204,34 +217,60 @@ const reportHumanKeyInput = (event: KeyboardEvent): void => { window.addEventListener("pointerdown", reportHumanPointerInput, true); window.addEventListener("keydown", reportHumanKeyInput, true); -const MOUSE_BUTTON_BACK = 3; -const MOUSE_BUTTON_FORWARD = 4; - -const navigationDirectionForButton = (button: number): "back" | "forward" | null => { - if (button === MOUSE_BUTTON_BACK) return "back"; - if (button === MOUSE_BUTTON_FORWARD) return "forward"; - return null; +// Capture runs before a page can stop the event; the task delay lets every page +// listener call preventDefault before the host is told the key went unhandled. +const reportUnhandledShortcut = (event: KeyboardEvent): void => { + if (!event.isTrusted || event.repeat || event.isComposing) return; + if (!event.metaKey && !event.ctrlKey && !event.altKey && !/^F\d{1,2}$/u.test(event.key)) return; + setTimeout(() => { + if (event.defaultPrevented) return; + ipcRenderer.send(PAGE_UNHANDLED_SHORTCUT_CHANNEL, { + key: event.key, + code: event.code, + metaKey: event.metaKey, + ctrlKey: event.ctrlKey, + shiftKey: event.shiftKey, + altKey: event.altKey, + }); + }, 0); }; -// Chromium routes thumb-button navigation to the focused WebContents; navigate this hovered guest explicitly. -const suppressNavigationButton = (event: MouseEvent): void => { - if (!event.isTrusted || navigationDirectionForButton(event.button) === null) return; - event.preventDefault(); - event.stopImmediatePropagation(); -}; +window.addEventListener("keydown", reportUnhandledShortcut, true); -const requestNavigationForButton = (event: MouseEvent): void => { - if (!event.isTrusted) return; - const direction = navigationDirectionForButton(event.button); - if (direction === null) return; - event.preventDefault(); +// Registered before page scripts so their capture listeners never see keys typed into the +// overlay; the closed shadow root retargets those to the host, hiding that they edit text. +const isolateOverlayKey = (event: KeyboardEvent): void => { + if (!activeSession || !(event.target instanceof Element) || !isAnnotationNode(event.target)) + return; + activeSession.handleOverlayKey(event); event.stopImmediatePropagation(); - ipcRenderer.send(MOUSE_NAVIGATE_CHANNEL, { direction }); }; -window.addEventListener("mousedown", suppressNavigationButton, true); -window.addEventListener("mouseup", requestNavigationForButton, true); -window.addEventListener("auxclick", suppressNavigationButton, true); +for (const type of ["keydown", "keypress", "keyup"] as const) + window.addEventListener(type, isolateOverlayKey, true); + +let replayedThumbPress: { readonly x: number; readonly y: number } | null = null; +ipcRenderer.on( + THUMB_PRESS_CHANNEL, + (_event, phase: unknown, x: unknown, y: unknown, button: unknown) => { + if (phase !== "down" && phase !== "up") return; + if (typeof x !== "number" || typeof y !== "number" || typeof button !== "number") return; + // Main reports presses inside a frame in that frame's coordinates. + const inFrame = document.querySelector("iframe:hover, frame:hover, object:hover, embed:hover"); + if (phase === "up") { + const pressed = replayedThumbPress; + replayedThumbPress = null; + // A replayed press is always released, at its own point if the release lands in a frame. + if (pressed) recordingCursor?.press(inFrame ? pressed : { x, y }, "up"); + return; + } + if (inFrame) return; + replayedThumbPress = { x, y }; + ipcRenderer.sendToHost(POINTER_DOWN_HOST_CHANNEL); + ipcRenderer.send(HUMAN_INPUT_CHANNEL, { kind: "pointer", x, y, button }); + recordingCursor?.press({ x, y }, "down"); + }, +); const nextId = createAnnotationIdSource(); @@ -512,34 +551,6 @@ function createUnitInput(unit: string, placeholder = "0"): HTMLInputElement { return input; } -function pathFromPoints(points: ReadonlyArray): string { - if (points.length === 0) return ""; - if (points.length === 1) return `M ${points[0]!.x} ${points[0]!.y} l 0.01 0.01`; - let path = `M ${points[0]!.x} ${points[0]!.y}`; - for (let index = 1; index < points.length - 1; index += 1) { - const current = points[index]!; - const next = points[index + 1]!; - path += ` Q ${current.x} ${current.y} ${(current.x + next.x) / 2} ${(current.y + next.y) / 2}`; - } - const last = points[points.length - 1]!; - path += ` L ${last.x} ${last.y}`; - return path; -} - -function strokeBounds( - points: ReadonlyArray, - width: number, -): PreviewAnnotationRect { - const xs = points.map((point) => point.x); - const ys = points.map((point) => point.y); - const padding = width + 3; - const left = Math.min(...xs) - padding; - const top = Math.min(...ys) - padding; - const right = Math.max(...xs) + padding; - const bottom = Math.max(...ys) + padding; - return { x: left, y: top, width: right - left, height: bottom - top }; -} - function startAnnotation( sendEnabled: boolean, voice: DesktopPreviewAnnotationVoiceConfig | undefined, @@ -876,7 +887,12 @@ function startAnnotation( } let tool: AnnotationTool = isPdf ? "marquee" : "select"; let dragStart: PreviewAnnotationPoint | null = null; - let activeStroke: { target: PreviewAnnotationStrokeTarget; path: SVGPathElement } | null = null; + let activeStroke: { + target: PreviewAnnotationStrokeTarget; + geometry: StrokeGeometry; + group: SVGGElement; + path: SVGPathElement; + } | null = null; let pendingCapture = false; let editorExpanded = false; let editorWasShown = false; @@ -1476,15 +1492,18 @@ function startAnnotation( return; } if (tool === "draw" && activeStroke) { - activeStroke.target.points = [ - ...activeStroke.target.points, - { x: event.clientX, y: event.clientY }, - ]; - activeStroke.target.bounds = strokeBounds( - activeStroke.target.points, - activeStroke.target.width, - ); - activeStroke.path.setAttribute("d", pathFromPoints(activeStroke.target.points)); + const closedPath = addStrokePoint(activeStroke.geometry, { + x: event.clientX, + y: event.clientY, + }); + activeStroke.target.bounds = strokeBounds(activeStroke.geometry, activeStroke.target.width); + if (closedPath !== null) { + activeStroke.path.setAttribute("d", closedPath); + activeStroke.path = activeStroke.group.appendChild( + document.createElementNS("http://www.w3.org/2000/svg", "path"), + ); + } + activeStroke.path.setAttribute("d", openStrokePath(activeStroke.geometry)); } }; @@ -1503,23 +1522,27 @@ function startAnnotation( } dragStart = { x: event.clientX, y: event.clientY }; if (tool === "draw") { + const geometry = startStroke(dragStart); const stroke: PreviewAnnotationStrokeTarget = { id: nextId("stroke"), color: annotationTheme?.primary ?? "#2563eb", width: 4, - points: [dragStart], + points: geometry.points, bounds: { x: dragStart.x, y: dragStart.y, width: 1, height: 1 }, }; - const path = document.createElementNS("http://www.w3.org/2000/svg", "path"); - path.setAttribute(OVERLAY_ATTRIBUTE, ""); - path.setAttribute("data-stroke-id", stroke.id); - path.setAttribute("fill", "none"); - path.setAttribute("stroke", stroke.color); - path.setAttribute("stroke-width", String(stroke.width)); - path.setAttribute("stroke-linecap", "round"); - path.setAttribute("stroke-linejoin", "round"); - svg.appendChild(path); - activeStroke = { target: stroke, path }; + const group = document.createElementNS("http://www.w3.org/2000/svg", "g"); + group.setAttribute(OVERLAY_ATTRIBUTE, ""); + group.setAttribute("data-stroke-id", stroke.id); + group.setAttribute("fill", "none"); + group.setAttribute("stroke", stroke.color); + group.setAttribute("stroke-width", String(stroke.width)); + group.setAttribute("stroke-linecap", "round"); + group.setAttribute("stroke-linejoin", "round"); + const path = group.appendChild( + document.createElementNS("http://www.w3.org/2000/svg", "path"), + ); + svg.appendChild(group); + activeStroke = { target: stroke, geometry, group, path }; } }; @@ -1546,7 +1569,7 @@ function startAnnotation( } } else if (tool === "draw" && activeStroke) { if (activeStroke.target.points.length > 1) strokes.push(activeStroke.target); - else activeStroke.path.remove(); + else activeStroke.group.remove(); activeStroke = null; } dragStart = null; @@ -1652,13 +1675,13 @@ function startAnnotation( return; } } - if (isAnnotationNode(event.target as Element) && event.key !== "Escape") return; - if (event.key === "Escape") { + if (event.key === "Escape" && !event.isComposing) { event.preventDefault(); event.stopPropagation(); teardown(true); return; } + if (shadowRoot.activeElement?.matches("input, textarea, select")) return; if (event.key === "v") tool = "select"; else if (event.key === "r") tool = "marquee"; else if (event.key === "d") tool = "draw"; @@ -1741,15 +1764,17 @@ function startAnnotation( }); }; submit.addEventListener("click", () => submitAnnotation("attach")); - root.addEventListener("keydown", (event) => { + const handleOverlayKey = (event: KeyboardEvent): void => { + if (event.type === "keyup") onVoiceKeyUp(event); + if (event.type !== "keydown") return; + onKeyDown(event); + if (event.cancelBubble) return; const submission = - event.target === comment ? resolveAnnotationSubmission(event, sendEnabled) : null; - // Bubble phase lets editor inputs handle events before hiding them from the page. - event.stopImmediatePropagation(); + shadowRoot.activeElement === comment ? resolveAnnotationSubmission(event, sendEnabled) : null; if (!submission) return; event.preventDefault(); submitAnnotation(submission); - }); + }; window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false }); window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false }); @@ -1785,6 +1810,7 @@ function startAnnotation( sendEnabled = enabled; updateSendHint(); }, + handleOverlayKey, }; } diff --git a/apps/desktop/src/preview/RecordingCursor.ts b/apps/desktop/src/preview/RecordingCursor.ts index 29f1865de2..ab74c361b6 100644 --- a/apps/desktop/src/preview/RecordingCursor.ts +++ b/apps/desktop/src/preview/RecordingCursor.ts @@ -156,13 +156,15 @@ export function installRecordingCursor( moveHuman(point); pointer(point, "move"); }; + const press = (point: { readonly x: number; readonly y: number }, phase: "down" | "up") => { + if (phase === "down") moveHuman(point); + pointer(point, phase); + }; const pointerDown = (event: PointerEvent) => { - if (event.pointerType === "touch") return; - moveHuman({ x: event.clientX, y: event.clientY }); - pointer({ x: event.clientX, y: event.clientY }, "down"); + if (event.pointerType !== "touch") press({ x: event.clientX, y: event.clientY }, "down"); }; const pointerUp = (event: PointerEvent) => { - if (event.pointerType !== "touch") pointer({ x: event.clientX, y: event.clientY }, "up"); + if (event.pointerType !== "touch") press({ x: event.clientX, y: event.clientY }, "up"); }; const keyDown = (event: KeyboardEvent) => { if (event.isComposing || event.repeat) return; @@ -196,6 +198,7 @@ export function installRecordingCursor( window.addEventListener("blur", hide); return { move, + press, keyPress, setController, setTheme, diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 868e1c139f..04406f63c6 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -4,6 +4,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Tracer from "effect/Tracer"; @@ -160,6 +161,49 @@ describe("DesktopSettings", () => { ), ); + it.effect("keeps saved preferences when a read fails before a bounds save", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + yield* writeSettingsPatch({ serverExposureMode: "network-accessible" }); + const cause = PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: environment.desktopSettingsPath, + }); + let failRead = true; + const settings = yield* DesktopAppSettings.make.pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.FileSystem.of({ + ...fileSystem, + readFileString: (path) => + Effect.suspend(() => { + if (failRead && path === environment.desktopSettingsPath) { + failRead = false; + return Effect.fail(cause); + } + return fileSystem.readFileString(path); + }), + }), + ), + ); + + yield* Effect.exit(settings.load); + yield* Effect.exit( + settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, false), + ); + + const persisted = yield* decodeDesktopSettingsPatch( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + ); + assert.equal(persisted.serverExposureMode, "network-accessible"); + }), + ), + ); + it.effect("loads lenient persisted desktop settings JSON", () => withSettings( Effect.gen(function* () { @@ -196,6 +240,28 @@ describe("DesktopSettings", () => { ), ); + it.effect("keeps Local environment off when another value in the file is unreadable", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const settings = yield* DesktopAppSettings.DesktopAppSettings; + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.writeFileString( + environment.desktopSettingsPath, + `{ "localEnvironmentEnabled": false, "serverExposureMode": "tailnet" }\n`, + ); + + assert.isFalse((yield* settings.load).localEnvironmentEnabled); + yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 800, height: 600 }, false); + assert.include( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + `"localEnvironmentEnabled":false`, + ); + }), + ), + ); + it.effect("rejects window bounds that do not satisfy the domain schema", () => withSettings( Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index 4c2ae8d1d1..e81da70660 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -13,6 +13,8 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as SynchronizedRef from "effect/SynchronizedRef"; @@ -88,20 +90,25 @@ const DesktopWindowBoundsDocument = Schema.Struct({ height: Schema.Number, }); +// A value this build cannot read drops only its own key, so the rest of the file +// still loads and is written back instead of every setting resetting to defaults. +const optionalReadableKey = (schema: S) => + Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone))); + const DesktopSettingsDocument = Schema.Struct({ - localEnvironmentEnabled: Schema.optionalKey(Schema.Boolean), - linuxPasswordStore: Schema.optionalKey(Schema.Unknown), - mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)), - mainWindowMaximized: Schema.optionalKey(Schema.Boolean), - serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema), - tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean), - tailscaleServePort: Schema.optionalKey(Schema.Number), - updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema), - updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean), - wslBackendEnabled: Schema.optionalKey(Schema.Boolean), - wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])), - wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)), - wslOnly: Schema.optionalKey(Schema.Boolean), + localEnvironmentEnabled: optionalReadableKey(Schema.Boolean), + linuxPasswordStore: optionalReadableKey(Schema.Unknown), + mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), + mainWindowMaximized: optionalReadableKey(Schema.Boolean), + serverExposureMode: optionalReadableKey(DesktopServerExposureModeSchema), + tailscaleServeEnabled: optionalReadableKey(Schema.Boolean), + tailscaleServePort: optionalReadableKey(Schema.Number), + updateChannel: optionalReadableKey(DesktopUpdateChannelSchema), + updateChannelConfiguredByUser: optionalReadableKey(Schema.Boolean), + wslBackendEnabled: optionalReadableKey(Schema.Boolean), + wslMode: optionalReadableKey(Schema.Literals(["local", "wsl"])), + wslDistro: optionalReadableKey(Schema.NullOr(Schema.String)), + wslOnly: optionalReadableKey(Schema.Boolean), }); type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type; @@ -379,15 +386,20 @@ function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings { return setWslOnly(setWslBackendEnabled(settings, false), false); } +// Fails only when the file may exist but could not be read; a missing file means defaults. function readSettings( fileSystem: FileSystem.FileSystem, settingsPath: string, appVersion: string, -): Effect.Effect { +): Effect.Effect { const defaultSettings = resolveDefaultDesktopSettings(appVersion); return fileSystem.readFileString(settingsPath).pipe( - Effect.option, + Effect.asSome, + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed(Option.none()), + ), Effect.flatMap( Option.match({ onNone: () => Effect.succeed(defaultSettings), @@ -476,6 +488,8 @@ export const make = Effect.gen(function* () { const path = yield* Path.Path; const random = yield* SecureRandom.SecureRandom; const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings); + // Writing over a settings file we could not read would erase the preferences it holds. + const persistenceEnabled = yield* Ref.make(true); const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) => SynchronizedRef.modify(settingsRef, (settings) => { @@ -492,17 +506,23 @@ export const make = Effect.gen(function* () { return Effect.succeed([settingsChange(settings, false), settings] as const); } - return random.uuidV4().pipe( - Effect.map((uuid) => uuid.replace(/-/g, "")), - Effect.flatMap((suffix) => - writeSettings({ - fileSystem, - path, - settingsPath: environment.desktopSettingsPath, - settings: nextSettings, - defaultSettings: environment.defaultDesktopSettings, - suffix, - }), + return Ref.get(persistenceEnabled).pipe( + Effect.flatMap((enabled) => + enabled + ? random.uuidV4().pipe( + Effect.map((uuid) => uuid.replace(/-/g, "")), + Effect.flatMap((suffix) => + writeSettings({ + fileSystem, + path, + settingsPath: environment.desktopSettingsPath, + settings: nextSettings, + defaultSettings: environment.defaultDesktopSettings, + suffix, + }), + ), + ) + : Effect.void, ), Effect.as([settingsChange(nextSettings, true), nextSettings] as const), ); @@ -515,6 +535,17 @@ export const make = Effect.gen(function* () { fileSystem, environment.desktopSettingsPath, environment.appVersion, + ).pipe( + Effect.catch((cause) => + Effect.logWarning( + "Could not read desktop settings; using defaults without saving changes.", + cause, + ).pipe( + Effect.annotateLogs({ settingsPath: environment.desktopSettingsPath }), + Effect.andThen(Ref.set(persistenceEnabled, false)), + Effect.as(resolveDefaultDesktopSettings(environment.appVersion)), + ), + ), ); return yield* SynchronizedRef.setAndGet(settingsRef, settings); }).pipe(Effect.withSpan("desktop.settings.load")), diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 1ab9b3159e..90c8740f83 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -110,7 +110,7 @@ const withClientSettings = ( prefix: "t3-desktop-client-settings-test-", }); return yield* effect.pipe(Effect.provide(layer(baseDir))); - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); describe("DesktopClientSettings", () => { it.effect("saves through a symlinked client settings file without replacing the link", () => diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts index 0001548f45..7be39dbe15 100644 --- a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts +++ b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts @@ -150,7 +150,7 @@ const withSavedEnvironments = ( prefix: "t3-desktop-saved-environments-test-", }); return yield* effect.pipe(Effect.provide(layer(baseDir, options))); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)); describe("DesktopSavedEnvironments", () => { it.effect("loads lenient saved environment registry documents", () => diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 74e46d2488..2d8aae7968 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Deferred from "effect/Deferred"; @@ -62,6 +63,26 @@ function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildPro }); } +function makeSlowProcess( + output: string, + delay: Duration.Input, +): ChildProcessSpawner.ChildProcessHandle { + const stdout = Stream.fromEffect(Effect.as(Effect.sleep(delay), textEncoder.encode(output))); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(125), + stdout, + stderr: Stream.empty, + all: stdout, + exitCode: Effect.as(Effect.sleep(delay), ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(true), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); +} + function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle { return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(124), @@ -486,7 +507,7 @@ describe("DesktopShellEnvironment", () => { Effect.gen(function* () { const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", - PATH: "/Users/test/.local/bin:/usr/bin", + PATH: " /Users/test/.local/bin:/usr/bin", }; const commands: ChildProcess.Command[] = []; @@ -496,7 +517,7 @@ describe("DesktopShellEnvironment", () => { handler: (command) => { commands.push(command); return envOutput({ - PATH: "/opt/homebrew/bin:/usr/bin", + PATH: "/opt/homebrew/bin:/usr/bin:/opt/bin ", SSH_AUTH_SOCK: "/tmp/secretive.sock", HOMEBREW_PREFIX: "/opt/homebrew", }); @@ -505,7 +526,7 @@ describe("DesktopShellEnvironment", () => { assert.equal(commands.length, 1); assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh"); - assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin"); + assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/opt/bin : /Users/test/.local/bin"); assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock"); assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew"); assert.isTrue(prepared); @@ -580,6 +601,39 @@ describe("DesktopShellEnvironment", () => { }), ); + it.effect.each([ + { + name: "hydrates both Android SDK names when neither is inherited", + inherited: {}, + expected: { ANDROID_HOME: "/shell/android-home", ANDROID_SDK_ROOT: "/shell/android-root" }, + }, + { + // The device host reads ANDROID_HOME before ANDROID_SDK_ROOT, so a shell + // ANDROID_HOME next to an inherited ANDROID_SDK_ROOT would change the SDK. + name: "keeps an inherited ANDROID_SDK_ROOT selected over a login-shell ANDROID_HOME", + inherited: { ANDROID_SDK_ROOT: "/inherited/android-sdk" }, + expected: { ANDROID_HOME: undefined, ANDROID_SDK_ROOT: "/inherited/android-sdk" }, + }, + ])("$name", ({ inherited, expected }) => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", ...inherited }; + + yield* runShellEnvironment({ + env, + platform: "darwin", + handler: () => + envOutput({ + PATH: "/usr/bin", + ANDROID_HOME: "/shell/android-home", + ANDROID_SDK_ROOT: "/shell/android-root", + }), + }); + + assert.equal(env.ANDROID_HOME, expected.ANDROID_HOME); + assert.equal(env.ANDROID_SDK_ROOT, expected.ANDROID_SDK_ROOT); + }), + ); + it.effect("keeps mise's PATH record with the login shell PATH", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { @@ -637,6 +691,175 @@ describe("DesktopShellEnvironment", () => { }), ); + it.effect("retries the user's shell when only the fallback shell answered", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { SHELL: "/usr/bin/fish", PATH: "/usr/bin" }; + const commands: string[] = []; + let fishReady = false; + yield* runShellEnvironment({ + env, + platform: "linux", + handler: (command) => { + if (command._tag !== "StandardCommand") return ""; + commands.push(command.command); + if (command.command !== "/usr/bin/fish") return envOutput({ PATH: "/usr/bin" }); + return fishReady + ? envOutput({ PATH: "/fish/bin:/usr/bin" }) + : { output: "", exitCode: 7 }; + }, + use: (service) => + Effect.gen(function* () { + assert.isTrue(yield* service.awaitDiscovery); + assert.equal(env.PATH, "/usr/bin"); + // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await. + const published = yield* service.updates.pipe( + Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + + fishReady = true; + yield* TestClock.adjust("30 seconds"); + assert.isTrue(Option.isSome(yield* Fiber.join(published))); + assert.equal(env.PATH, "/fish/bin:/usr/bin"); + return true; + }), + }).pipe(Effect.provide(Logger.layer([]))); + assert.deepEqual(commands, ["/usr/bin/fish", "/bin/bash", "/usr/bin/fish"]); + + // With no user shell to wait for, the fallback's answer is final. + commands.length = 0; + yield* runShellEnvironment({ + env: { PATH: "/usr/bin" }, + platform: "linux", + handler: (command) => { + if (command._tag === "StandardCommand") commands.push(command.command); + return envOutput({ PATH: "/usr/bin" }); + }, + use: (service) => + Effect.gen(function* () { + assert.isTrue(yield* service.awaitDiscovery); + yield* TestClock.adjust("5 minutes"); + return true; + }), + }).pipe(Effect.provide(Logger.layer([]))); + assert.deepEqual(commands, ["/bin/bash"]); + }), + ); + + it.effect("gives background retries time for a locked or slow shell, then publishes", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + // Startup fails fast, the first retry meets a shell blocked on a lock, the second a slow one. + const spawned = yield* Effect.forEach([0, 1, 2], () => Deferred.make()); + const stopped = yield* Deferred.make(); + let attempts = 0; + yield* runShellEnvironment({ + env, + platform: "darwin", + handler: () => "", + processSpawner: ChildProcessSpawner.make((command) => { + if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") { + return Effect.succeed(makeProcess("")); + } + const attempt = attempts++; + const spawn = Deferred.succeed(spawned[attempt]!, undefined); + if (attempt === 0) return spawn.pipe(Effect.as(makeProcess(""))); + if (attempt === 1) { + return spawn.pipe( + Effect.andThen( + Effect.acquireRelease(Effect.succeed(makeHungProcess()), () => + Deferred.succeed(stopped, command.options), + ), + ), + ); + } + return spawn.pipe( + Effect.as(makeSlowProcess(envOutput({ PATH: "/fresh/bin" }), "20 seconds")), + ); + }), + use: (service) => + Effect.gen(function* () { + assert.isFalse(yield* service.awaitDiscovery); + const published = yield* service.updates.pipe( + Stream.drop(1), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + + yield* TestClock.adjust("30 seconds"); + yield* Deferred.await(spawned[1]!); + // pyenv waits up to 60 s on its rehash lock before the shell continues. + yield* TestClock.adjust("1 minute"); + assert.isFalse(yield* Deferred.isDone(stopped)); + yield* TestClock.adjust("1 minute"); + const stop = yield* Deferred.await(stopped); + // pyenv releases that lock in an EXIT trap, which SIGTERM runs and SIGKILL skips. + assert.equal(stop.killSignal, "SIGTERM"); + assert.isAtLeast(Duration.toMillis(stop.forceKillAfter ?? 0), 5_000); + + yield* TestClock.adjust("30 seconds"); + yield* Deferred.await(spawned[2]!); + yield* TestClock.adjust("20 seconds"); + const snapshot = yield* Fiber.join(published); + assert.equal(env.PATH, "/fresh/bin:/usr/bin"); + assert.isTrue(Option.isSome(snapshot) && snapshot.value.discovered); + assert.equal( + Option.isSome(snapshot) ? snapshot.value.environment.PATH : undefined, + "/fresh/bin:/usr/bin", + ); + return true; + }), + }); + }), + ); + + it.effect("recovers the login-shell PATH when the first probe outlasts the timeout", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" }; + const output = envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }); + let shellProbes = 0; + yield* runShellEnvironment({ + env, + platform: "darwin", + handler: () => "", + processSpawner: ChildProcessSpawner.make((command) => { + if (command._tag !== "StandardCommand" || command.command !== "/bin/zsh") { + return Effect.succeed(makeProcess("")); + } + shellProbes += 1; + if (shellProbes > 1) return Effect.succeed(makeProcess(output)); + // A cold start: the first login shell answers, but only after 7s. + const slow = Effect.sleep("7 seconds"); + const stdout = Stream.fromEffect(slow.pipe(Effect.as(textEncoder.encode(output)))); + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(125), + stdout, + stderr: Stream.empty, + all: stdout, + exitCode: slow.pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + isRunning: Effect.succeed(true), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ); + }), + use: (service) => + Effect.gen(function* () { + yield* service.installIntoProcess; + yield* TestClock.adjust("10 minutes"); + return true; + }), + }).pipe(Effect.provide(Logger.layer([]))); + + assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"); + }), + ); + it.effect("loads PowerShell profile environment on Windows", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 8e3e218c59..5b65365fd0 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -5,8 +5,10 @@ import { applyShellEnvironment, buildEnvironmentCaptureCommand, listLoginShellCandidates, + mergePathValues, readUserLoginShell, setWindowsPath, + windowsEnvironmentValueCommand, } from "@t3tools/shared/shell"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; @@ -16,6 +18,7 @@ import * as Deferred from "effect/Deferred"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -30,9 +33,17 @@ import { isStaleAppImageMountEntry } from "../fincke/AppImageMounts.ts"; type EnvironmentPatch = Record; +interface ProbeBudget { + readonly timeout: Duration.Duration; + // One longer wait for the first login shell that times out. + readonly slowTimeout?: Duration.Duration; + readonly terminateGrace: Duration.Duration; +} + interface ShellEnvironmentConfig { readonly env: NodeJS.ProcessEnv; readonly platform: NodeJS.Platform; + readonly budget: ProbeBudget; } interface WindowsProbeOptions { @@ -91,6 +102,8 @@ export class DesktopShellEnvironment extends Context.Service< const LOGIN_SHELL_ENV_NAMES = [ "PATH", + "ANDROID_HOME", + "ANDROID_SDK_ROOT", "DBUS_SESSION_BUS_ADDRESS", "DISPLAY", "LANG", @@ -115,11 +128,28 @@ const LOGIN_SHELL_ENV_NAMES = [ ] as const; const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const; const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const; +const ANDROID_SDK_ENV_NAMES = ["ANDROID_HOME", "ANDROID_SDK_ROOT"] as const; const FALLBACK_LC_CTYPE = "en_US.UTF-8"; const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const; const LOGIN_SHELL_TIMEOUT = Duration.seconds(5); +// A profile can be slow only while the machine boots; one longer wait covers it. +const SLOW_LOGIN_SHELL_TIMEOUT = Duration.seconds(20); const LAUNCHCTL_TIMEOUT = Duration.seconds(2); const PROCESS_TERMINATE_GRACE = Duration.seconds(1); +const STARTUP_PROBE: ProbeBudget = { + timeout: LOGIN_SHELL_TIMEOUT, + slowTimeout: SLOW_LOGIN_SHELL_TIMEOUT, + terminateGrace: PROCESS_TERMINATE_GRACE, +}; +// Retries block nothing, so they outlast pyenv's 60 s wait on its rehash lock, and SIGTERM gets +// time to run the exit trap that releases it. A SIGKILL leaves the lock for two minutes. +const RETRY_PROBE: ProbeBudget = { + timeout: Duration.minutes(2), + terminateGrace: Duration.seconds(10), +}; +// A Mac asleep at launch fails the first probe on wake, and nothing else would probe again. +const DISCOVERY_RETRY_DELAY = Duration.seconds(30); +const DISCOVERY_RETRIES = 10; const trimNonEmpty = (value: string | null | undefined): Option.Option => Option.fromNullishOr(value).pipe( @@ -127,10 +157,12 @@ const trimNonEmpty = (value: string | null | undefined): Option.Option = Option.filter((entry) => entry.length > 0), ); -const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":"); +// POSIX directory names may begin or end with whitespace; mergePathValues trims only on Windows. +const nonEmptyPath = (value: string | null | undefined): Option.Option => + Option.fromNullishOr(value).pipe(Option.filter((entry) => entry.length > 0)); const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option => - trimNonEmpty(env.PATH ?? env.Path ?? env.path); + nonEmptyPath(env.PATH ?? env.Path ?? env.path); const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, ""); @@ -149,42 +181,20 @@ const linuxRuntimeDirCandidates = ( return candidates.filter((candidate) => candidate.length > 0); }; -const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => { - const normalized = entry.trim().replace(/^"+|"+$/g, ""); - return platform === "win32" ? normalized.toLowerCase() : normalized; -}; - -const sanitizePathEntry = (entry: string, platform: NodeJS.Platform) => - platform === "win32" ? entry.replaceAll('"', "") : entry; - const mergePaths = ( platform: NodeJS.Platform, values: ReadonlyArray>, ): Option.Option => { - const delimiter = pathDelimiter(platform); - const entries: string[] = []; - const seen = new Set(); - - for (const value of values) { - if (Option.isNone(value)) continue; - - for (const entry of value.value.split(delimiter)) { - const sanitized = sanitizePathEntry(entry.trim(), platform); - if (sanitized.length === 0) continue; - // the shell env cache and login shells can carry a dead instance's AppImage mount - if (platform === "linux" && isStaleAppImageMountEntry(sanitized, process.env.APPDIR)) { - continue; - } - - const key = pathComparisonKey(sanitized, platform); - if (key.length === 0 || seen.has(key)) continue; - - seen.add(key); - entries.push(sanitized); - } - } - - return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none(); + const merged = values.reduce( + (current, value) => mergePathValues(current, Option.getOrUndefined(value), platform), + undefined, + ); + if (merged === undefined || platform !== "linux") return Option.fromNullishOr(merged); + // the shell env cache and login shells can carry a dead instance's AppImage mount + const entries = merged + .split(":") + .filter((entry) => !isStaleAppImageMountEntry(entry, process.env.APPDIR)); + return entries.length > 0 ? Option.some(entries.join(":")) : Option.none(); }; const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray => [ @@ -229,7 +239,7 @@ const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => ...names.flatMap((name) => { return [ `Write-Output '${startMarker(name)}'`, - `$value = [Environment]::GetEnvironmentVariable('${name}')`, + windowsEnvironmentValueCommand(name), "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }", `Write-Output '${endMarker(name)}'`, ]; @@ -265,8 +275,13 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( readonly args: ReadonlyArray; readonly env: NodeJS.ProcessEnv; readonly timeout: Duration.Duration; + readonly terminateGrace?: Duration.Duration; readonly shell?: boolean; -}): Effect.fn.Return { +}): Effect.fn.Return< + string, + DesktopShellEnvironmentCommandTimeoutError, + ChildProcessSpawner.ChildProcessSpawner +> { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fiber = yield* Effect.scoped( Effect.gen(function* () { @@ -279,7 +294,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( stdout: "pipe", stderr: "ignore", killSignal: "SIGTERM", - forceKillAfter: PROCESS_TERMINATE_GRACE, + forceKillAfter: input.terminateGrace ?? PROCESS_TERMINATE_GRACE, }), ); return yield* Effect.all([Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode], { @@ -322,21 +337,35 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( return output.value; } - const error = new DesktopShellEnvironmentCommandTimeoutError({ + return yield* new DesktopShellEnvironmentCommandTimeoutError({ probe: input.probe, executable: executableName(input.command), argumentCount: input.args.length, timeoutMs: Duration.toMillis(input.timeout), }); - yield* logShellEnvironmentCommandError(error); - return ""; }); +const orEmptyOnTimeout = ( + effect: Effect.Effect, +): Effect.Effect => + effect.pipe( + Effect.catchTags({ + DesktopShellEnvironmentCommandTimeoutError: (error) => + logShellEnvironmentCommandError(error).pipe(Effect.as("")), + }), + ); + const readLoginShellEnvironment = ( shell: string, names: ReadonlyArray, env: NodeJS.ProcessEnv, -): Effect.Effect => + timeout: Duration.Duration, + terminateGrace: Duration.Duration, +): Effect.Effect< + EnvironmentPatch, + DesktopShellEnvironmentCommandTimeoutError, + ChildProcessSpawner.ChildProcessSpawner +> => names.length === 0 ? Effect.succeed({}) : runCommandOutput({ @@ -344,7 +373,8 @@ const readLoginShellEnvironment = ( command: shell, args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)], env, - timeout: LOGIN_SHELL_TIMEOUT, + timeout, + terminateGrace, }).pipe(Effect.map((output) => extractEnvironment(output, names))); const readLaunchctlPath = (env: NodeJS.ProcessEnv) => @@ -354,13 +384,14 @@ const readLaunchctlPath = (env: NodeJS.ProcessEnv) => command: "/bin/launchctl", args: ["getenv", "PATH"], timeout: LAUNCHCTL_TIMEOUT, - }).pipe(Effect.map(trimNonEmpty)); + }).pipe(orEmptyOnTimeout, Effect.map(trimNonEmpty)); const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")( function* ( names: ReadonlyArray, options: WindowsProbeOptions, env: NodeJS.ProcessEnv, + budget: ProbeBudget, ): Effect.fn.Return { if (names.length === 0) return {}; @@ -378,8 +409,9 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn command, args, env, - timeout: LOGIN_SHELL_TIMEOUT, - }); + timeout: budget.timeout, + terminateGrace: budget.terminateGrace, + }).pipe(orEmptyOnTimeout); const environment = extractEnvironment(output, names); if (Object.keys(environment).length > 0) { return environment; @@ -396,8 +428,13 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin ): Effect.fn.Return { const [noProfile, profile] = yield* Effect.all( [ - readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env), - readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env), + readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env, config.budget), + readWindowsEnvironment( + WINDOWS_PROFILE_ENV_NAMES, + { loadProfile: true }, + config.env, + config.budget, + ), ], { concurrency: 2 }, ); @@ -421,6 +458,9 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin }, ); +const listUserShells = (env: NodeJS.ProcessEnv): ReadonlyArray => + [env.SHELL?.trim(), readUserLoginShell()].filter((shell): shell is string => Boolean(shell)); + const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")( function* ( config: ShellEnvironmentConfig, @@ -431,13 +471,36 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix > { const fileSystem = yield* FileSystem.FileSystem; const shellEnvironment: EnvironmentPatch = {}; - const userShells = [config.env.SHELL?.trim(), readUserLoginShell()]; + const userShells = listUserShells(config.env); let answeredBy: string | undefined; + let waitedForSlowShell = false; for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) { + const read = (timeout: Duration.Duration) => + readLoginShellEnvironment( + shell, + LOGIN_SHELL_ENV_NAMES, + config.env, + timeout, + config.budget.terminateGrace, + ); Object.assign( shellEnvironment, - yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env), + yield* read(config.budget.timeout).pipe( + Effect.catchTags({ + DesktopShellEnvironmentCommandTimeoutError: (error) => { + const slowTimeout = waitedForSlowShell ? undefined : config.budget.slowTimeout; + waitedForSlowShell = true; + return logShellEnvironmentCommandError(error).pipe( + Effect.andThen(slowTimeout ? read(slowTimeout) : Effect.succeed({})), + ); + }, + }), + Effect.catchTags({ + DesktopShellEnvironmentCommandTimeoutError: (error) => + logShellEnvironmentCommandError(error).pipe(Effect.as({})), + }), + ), ); if (shellEnvironment.PATH) { answeredBy = shell; @@ -450,7 +513,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix ? yield* readLaunchctlPath(config.env) : Option.none(); const mergedPath = mergePaths(config.platform, [ - trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)), + nonEmptyPath(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)), readEnvPath(config.env), ]); @@ -495,6 +558,17 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix } } + // The device host picks the Android SDK from ANDROID_HOME before ANDROID_SDK_ROOT, + // so a profile-only ANDROID_HOME must not shadow an inherited ANDROID_SDK_ROOT. + if (ANDROID_SDK_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) { + for (const name of ANDROID_SDK_ENV_NAMES) { + const value = trimNonEmpty(shellEnvironment[name]); + if (Option.isSome(value)) { + config.env[name] = value.value; + } + } + } + // Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE. if ( config.platform === "darwin" && @@ -530,7 +604,10 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix } const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH)); - return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) }; + return { + prepared, + fromUserShell: prepared && answeredBy !== undefined && userShells.includes(answeredBy), + }; }, ); @@ -614,38 +691,60 @@ export const make = Effect.gen(function* () { yield* Ref.set(latest, Option.some(message)); yield* PubSub.publish(changes, message); }); - const refresh = Effect.gen(function* () { - // Refresh from the inherited baseline so removed cached paths and values do not survive. - const fresh = { ...inherited }; - const discovery = yield* installShellEnvironment({ - env: fresh, - platform: environment.platform, - }); - const { prepared } = discovery; - const patch = Object.fromEntries( - Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]), - ); - if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared); - if (prepared) { - const cached = Object.fromEntries( - CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])), - ); - const persist = Effect.gen(function* () { - const encoded = yield* encodeCache({ version: 1, key, environment: cached }); - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); - yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 }); - yield* fileSystem.rename(cachePath + ".tmp", cachePath); + const probe = Effect.fn("desktop.shellEnvironment.refresh")( + function* (budget: ProbeBudget) { + // Refresh from the inherited baseline so removed cached paths and values do not survive. + const fresh = { ...inherited }; + const discovery = yield* installShellEnvironment({ + env: fresh, + platform: environment.platform, + budget, }); - yield* persist.pipe( - Effect.catch(() => Effect.logWarning("Could not cache shell environment")), + const { prepared } = discovery; + const patch = Object.fromEntries( + Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]), ); - } - return discovery; - }).pipe( + if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared); + if (prepared) { + const cached = Object.fromEntries( + CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])), + ); + const persist = Effect.gen(function* () { + const encoded = yield* encodeCache({ version: 1, key, environment: cached }); + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 }); + yield* fileSystem.rename(cachePath + ".tmp", cachePath); + }); + yield* persist.pipe( + Effect.catch(() => Effect.logWarning("Could not cache shell environment")), + ); + } + return discovery; + }, Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.withSpan("desktop.shellEnvironment.refresh"), + ); + // A fallback shell's PATH can miss folders the user's own shell adds, so keep asking that shell. + const awaitsUserShell = listUserShells(inherited).length > 0; + const settled = ({ prepared, fromUserShell }: ShellDiscovery) => + fromUserShell || (prepared && !awaitsUserShell); + const refresh = probe(STARTUP_PROBE).pipe( Effect.onExit((exit) => Deferred.done(discovered, exit)), + Effect.flatMap((discovery) => + settled(discovery) + ? Effect.void + : Effect.sleep(DISCOVERY_RETRY_DELAY).pipe( + Effect.andThen( + probe(RETRY_PROBE).pipe( + Effect.repeat({ + until: settled, + schedule: Schedule.spaced(DISCOVERY_RETRY_DELAY), + times: DISCOVERY_RETRIES - 1, + }), + ), + ), + ), + ), ); const installIntoProcess = yield* Effect.cached( Effect.gen(function* () { diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index 57a38d2ff3..bd736f46b4 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -1048,7 +1048,6 @@ it.effect.each([ { backend: "gnome", screenshot: "PNG" }, { backend: "niri", screenshot: "PNG" }, { backend: "kde", screenshot: "PNG" }, - { backend: "hyprland", screenshot: "PNG" }, { backend: "gnome", screenshot: "invalid" }, ] as const)( "persists $backend accessibility text with a $screenshot screenshot", diff --git a/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts b/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts index 35c007e35d..1a85c9a4cd 100644 --- a/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts +++ b/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts @@ -30,6 +30,7 @@ class FakeBus extends NodeEvents.EventEmitter { requestPath = ""; boundId = ""; foreignHandle = false; + owner = ":1.2"; send(message: Message) { this.sends.push(message); @@ -39,7 +40,7 @@ class FakeBus extends NodeEvents.EventEmitter { member: string, path: string, body: unknown[], - sender = ":1.2", + sender = this.owner, signature = "", ) { this.emit( @@ -71,7 +72,7 @@ class FakeBus extends NodeEvents.EventEmitter { ]), }); } - activate(id = this.boundId, session = this.session, sender = ":1.2") { + activate(id = this.boundId, session = this.session, sender = this.owner) { this.signal(portal, "Activated", root, [session, id, 1, {}], sender, "osta{sv}"); } async call(message: Message) { @@ -87,7 +88,7 @@ class FakeBus extends NodeEvents.EventEmitter { if (this.registryError) throw this.registryError; return reply(); } - if (message.member === "GetNameOwner") return reply([":1.2"]); + if (message.member === "GetNameOwner") return reply([this.owner]); if (message.member === "Get") return reply([new Variant("u", this.version)]); if (message.member === "AddMatch" || message.member === "ConfigureShortcuts") return reply(); const options = message.body.at(-1) as Record>; @@ -338,7 +339,30 @@ it("handles a disappearing portal without keeping a false registered state", asy ); expect(client.state.shortcutRegistered).toBe(false); expect(client.state.shortcutMessage).toContain("restarted"); - expect(bus.disconnect).toHaveBeenCalledOnce(); + expect(client.hasSession).toBe(false); + expect(bus.disconnect).not.toHaveBeenCalled(); + await vi.waitFor(() => expect(client.state.shortcutRegistered).toBe(true)); + expect(bus.calls.filter((call) => call.member === "CreateSession")).toHaveLength(2); +}); + +it("binds a new session when the portal restarts", async () => { + const { bus, client, capture } = start(new FakeBus(), chord, true); + await client.ready; + const ownerChanged = (from: string, to: string) => + bus.signal( + "org.freedesktop.DBus", + "NameOwnerChanged", + "/org/freedesktop/DBus", + ["org.freedesktop.portal.Desktop", from, to], + "org.freedesktop.DBus", + ); + ownerChanged(":1.2", ""); + bus.owner = ":1.3"; + ownerChanged("", ":1.3"); + await vi.waitFor(() => expect(client.state.shortcutActionRegistered).toBe(true)); + expect(bus.calls.filter((call) => call.member === "CreateSession")).toHaveLength(2); + bus.activate(); + expect(capture).toHaveBeenCalledOnce(); }); it("accepts old portals without Registry but does not ignore permission denial", async () => { diff --git a/apps/desktop/src/snapShot/PortalCaptureShortcut.ts b/apps/desktop/src/snapShot/PortalCaptureShortcut.ts index 629124cf65..74b988c933 100644 --- a/apps/desktop/src/snapShot/PortalCaptureShortcut.ts +++ b/apps/desktop/src/snapShot/PortalCaptureShortcut.ts @@ -68,6 +68,7 @@ export class PortalCaptureShortcut { }; readonly ready: Promise; private closed = false; + private connection = 0; private owner = ""; private namespace = ""; private session = ""; @@ -75,8 +76,10 @@ export class PortalCaptureShortcut { private version = 0; private pending: { path: string; resolve: (body: unknown) => void } | undefined; private responses = new Map(); - private readonly stopped: Promise; + private stopped!: Promise; private rejectStopped!: (reason: Error) => void; + private readonly appId: string; + private readonly trigger: string; private readonly onCapture: () => void; private readonly onStateChanged: () => void; private readonly bus: MessageBus; @@ -90,6 +93,8 @@ export class PortalCaptureShortcut { bus: MessageBus = sessionBus(), managedByHyprland = false, ) { + this.appId = appId; + this.trigger = portalShortcutTrigger(shortcut); this.onCapture = onCapture; this.onStateChanged = onStateChanged; this.bus = bus; @@ -100,13 +105,41 @@ export class PortalCaptureShortcut { shortcutPending: true, shortcutMessage: "Connecting to Hyprland shortcuts…", }; + this.resetStopped(); + bus.on("error", this.failed); + bus.on("message", this.message); + this.ready = this.connect(true); + } + + private resetStopped() { this.stopped = new Promise((_, reject) => { this.rejectStopped = reject; }); void this.stopped.catch(() => undefined); - bus.on("error", this.failed); - bus.on("message", this.message); - this.ready = this.initialize(appId, shortcut).catch(this.failed); + } + + private connect(first = false) { + const connection = ++this.connection; + return this.initialize(first).catch((error: unknown) => { + if (connection === this.connection) this.failed(error); + }); + } + + private portalGone() { + this.rejectStopped(new Error("The desktop shortcut service restarted.")); + this.resetStopped(); + this.owner = ""; + this.session = ""; + this.pending = undefined; + this.responses.clear(); + this.update({ + shortcutRegistered: false, + shortcutActionRegistered: false, + shortcutPending: true, + shortcutMessage: "The desktop shortcut service restarted. Reconnecting…", + }); + // Register is sent to the well-known name, so it D-Bus-activates a portal that is not running. + void this.connect(); } close = () => { @@ -210,10 +243,9 @@ export class PortalCaptureShortcut { message.sender === "org.freedesktop.DBus" && message.interface === DBUS && message.member === "NameOwnerChanged" && - message.body[0] === PORTAL && - message.body[1] === this.owner + message.body[0] === PORTAL ) { - this.failed(new Error("The desktop shortcut service restarted. Retry the shortcut request.")); + if (this.owner && message.body[1] === this.owner) this.portalGone(); return; } if (!this.owner || message.sender !== this.owner) return; @@ -271,7 +303,8 @@ export class PortalCaptureShortcut { const response = new Promise((done) => { resolve = done; }); - this.pending = { path: expectedPath, resolve }; + const pending = { path: expectedPath, resolve }; + this.pending = pending; this.responses.clear(); let completed = false; try { @@ -285,7 +318,7 @@ export class PortalCaptureShortcut { }); const handle = string(reply.body[0]); if (!handle.startsWith(this.namespace)) throw new Error("Invalid shortcut request handle."); - this.pending.path = handle; + pending.path = handle; if (this.responses.has(handle)) resolve(this.responses.get(handle)); const [status, results] = decodeResponse( await this.wait(response, member === "BindShortcuts" ? 120_000 : 5_000), @@ -307,9 +340,11 @@ export class PortalCaptureShortcut { } return results; } finally { - if (!completed && !this.closed && this.pending) this.closeObject(this.pending.path, REQUEST); - this.pending = undefined; - this.responses.clear(); + if (this.pending === pending) { + if (!completed && !this.closed) this.closeObject(pending.path, REQUEST); + this.pending = undefined; + this.responses.clear(); + } } } @@ -339,8 +374,8 @@ export class PortalCaptureShortcut { }); } - private async initialize(appId: string, shortcut: SnapShotKeyChord) { - const trigger = portalShortcutTrigger(shortcut); + private async initialize(first: boolean) { + const trigger = this.trigger; if (!process.env.FLATPAK_ID && !process.env.SNAP) { await this.call({ destination: PORTAL, @@ -348,7 +383,7 @@ export class PortalCaptureShortcut { interface: "org.freedesktop.host.portal.Registry", member: "Register", signature: "sa{sv}", - body: [appId, {}], + body: [this.appId, {}], }).catch((error: unknown) => { if ( !( @@ -382,7 +417,11 @@ export class PortalCaptureShortcut { this.version = decodeVersion(version.body[0]).value; for (const rule of [ `type='signal',sender='${this.owner}',path_namespace='${PATH}'`, - `type='signal',sender='org.freedesktop.DBus',interface='${DBUS}',member='NameOwnerChanged',arg0='${PORTAL}'`, + ...(first + ? [ + `type='signal',sender='org.freedesktop.DBus',interface='${DBUS}',member='NameOwnerChanged',arg0='${PORTAL}'`, + ] + : []), ]) await this.call({ destination: DBUS, diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts index 0a2b10e08c..415901878c 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts @@ -352,6 +352,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () { return Queue.offer(updateCommitQueue, message).pipe(Effect.asVoid); case "cancelDesktopUpdate": return Queue.offer(updateCancellationQueue, message).pipe(Effect.asVoid); + case "serverReady": + return Effect.void; } }; const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = ( diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts index 1f5321148b..5cdf2ba1b5 100644 --- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts @@ -102,6 +102,29 @@ describe("DesktopRemoteUpdates", () => { assert.equal(terminals[0]?.requestId, "req-1"); assert.equal(harness.quitAndInstalls(), 0); + yield* Queue.offer(requests, request("req-retry")); + yield* settle; + assert.deepEqual( + terminalReports(reports).map((report) => report.outcome), + ["ready-to-install", "ready-to-install"], + ); + assert.equal(terminalReports(reports)[1]?.requestId, "req-retry"); + assert.equal(terminalReports(reports)[1]?.preparedRequestId, "req-1"); + assert.equal(harness.quitAndInstalls(), 0); + assert.equal(harness.downloadCount(), 1); + + yield* Queue.offer(requests, { + ...request("req-other-track"), + channel: "nightly", + targetVersion: "1.2.4-nightly.20261027.1", + }); + yield* settle; + assert.equal(terminalReports(reports)[2]?.outcome, "failed"); + assert.equal( + terminalReports(reports)[2]?.reason, + "A prepared desktop update is already in progress.", + ); + yield* Queue.offer(commits, { version: 1, type: "commitDesktopUpdate", @@ -119,6 +142,49 @@ describe("DesktopRemoteUpdates", () => { ); }); + it.effect("does not renew the preparation lease when a retry recovers its token", () => { + const harness = makeHarness(); + + return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) => + Effect.gen(function* () { + harness.emit("update-downloaded", { version: "1.2.4" }); + yield* settle; + yield* Queue.offer(requests, request("req-original")); + yield* settle; + + yield* TestClock.adjust(Duration.minutes(4)); + harness.emit("update-available", { version: "1.2.4" }); + yield* settle; + yield* Queue.offer(requests, request("req-retry")); + yield* settle; + assert.equal(terminalReports(reports)[1]?.preparedRequestId, "req-original"); + + yield* TestClock.adjust(Duration.minutes(1)); + yield* Queue.offer(commits, { + version: 1, + type: "commitDesktopUpdate", + requestId: "req-original", + }); + yield* settle; + assert.equal( + terminalReports(reports)[2]?.reason, + "This desktop update is no longer prepared.", + ); + assert.equal(harness.quitAndInstalls(), 0); + + yield* Queue.offer(requests, request("req-new")); + yield* settle; + yield* Queue.offer(commits, { + version: 1, + type: "commitDesktopUpdate", + requestId: "req-new", + }); + yield* settle; + assert.equal(harness.quitAndInstalls(), 1); + }), + ); + }); + it.effect("switches to the requested track before preparing its release", () => { // In-memory settings keep the channel write off real disk I/O. const harness = makeHarness({ beforeSetUpdateChannel: Effect.void }); @@ -667,16 +733,15 @@ describe("DesktopRemoteUpdates", () => { it.effect("waits for a background check before installing a prepared update", () => { const backgroundCheckStarted = Deferred.makeUnsafe(); const releaseBackgroundCheck = Deferred.makeUnsafe(); - let checks = 0; + let blockCheck = false; const harness = makeHarness({ - checkForUpdates: Effect.suspend(() => { - checks += 1; - return checks === 2 + checkForUpdates: Effect.suspend(() => + blockCheck ? Deferred.succeed(backgroundCheckStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseBackgroundCheck)), ) - : Effect.void; - }), + : Effect.void, + ), }); return runRemoteUpdatesTest(harness, ({ requests, commits }) => @@ -689,9 +754,10 @@ describe("DesktopRemoteUpdates", () => { harness.emit("update-downloaded", { version: "1.2.4" }); yield* settle; + blockCheck = true; const backgroundCheck = yield* updates.check("poll").pipe(Effect.forkChild); yield* Deferred.await(backgroundCheckStarted); - assert.equal((yield* updates.getState).status, "checking"); + assert.isTrue(yield* updates.isActionActive); yield* Queue.offer(commits, { version: 1, @@ -701,7 +767,6 @@ describe("DesktopRemoteUpdates", () => { yield* settle; assert.equal(harness.quitAndInstalls(), 0); - harness.emit("update-downloaded", { version: "1.2.4" }); yield* Deferred.succeed(releaseBackgroundCheck, undefined); yield* Fiber.join(backgroundCheck); yield* settle; diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.ts index 560e2e78d4..ce2f23ab3e 100644 --- a/apps/desktop/src/updates/DesktopRemoteUpdates.ts +++ b/apps/desktop/src/updates/DesktopRemoteUpdates.ts @@ -32,6 +32,8 @@ const PREPARED_UPDATE_TTL = Duration.minutes(5); interface PreparedUpdate { readonly requestId: string; + readonly channel: DesktopTelemetryRequestDesktopUpdate["channel"]; + readonly targetVersion: DesktopTelemetryRequestDesktopUpdate["targetVersion"]; readonly downloadedVersion: string; readonly status: "prepared" | "committing" | "failed"; readonly failureReason?: string; @@ -67,7 +69,11 @@ export const listen: Effect.Effect< const publishReport = ( state: DesktopUpdateState, - terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string }, + terminal?: { + readonly outcome: DesktopUpdateRemoteOutcome; + readonly reason?: string; + readonly preparedRequestId?: string; + }, explicitRequestId?: string, ): Effect.Effect => { const reason = normalizeRemoteUpdateReason(terminal?.reason); @@ -82,6 +88,9 @@ export const listen: Effect.Effect< ? { requestId: requestId.value } : {}), ...(terminal === undefined ? {} : { outcome: terminal.outcome }), + ...(terminal?.preparedRequestId === undefined + ? {} + : { preparedRequestId: terminal.preparedRequestId }), ...(reason ? { reason } : {}), state, }), @@ -167,8 +176,22 @@ export const listen: Effect.Effect< : ([current, current] as const), ); if (Option.isSome(prepared) && prepared.value.status !== "failed") { + const state = yield* updates.getState; + if ( + prepared.value.status === "prepared" && + prepared.value.channel === request.channel && + prepared.value.targetVersion === request.targetVersion && + state.downloadedVersion === prepared.value.downloadedVersion + ) { + yield* publishReport( + state, + { outcome: "ready-to-install", preparedRequestId: prepared.value.requestId }, + request.requestId, + ); + return; + } yield* publishReport( - yield* updates.getState, + state, { outcome: "failed", reason: "A prepared desktop update is already in progress.", @@ -301,6 +324,8 @@ export const listen: Effect.Effect< preparedUpdateRef, Option.some({ requestId: request.requestId, + channel: request.channel, + targetVersion: request.targetVersion, downloadedVersion: state.downloadedVersion, status: "prepared", expiresAt: diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 1cb4f4fa1a..7e20e8b790 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -1,6 +1,7 @@ import * as NodeModule from "node:module"; import { assert, describe, it } from "@effect/vitest"; +import { DesktopUpdateStateSchema } from "@t3tools/contracts"; import { computeReleaseNotes } from "electron-updater/out/providers/GitHubProvider.js"; import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; @@ -12,6 +13,7 @@ import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as References from "effect/References"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; @@ -23,6 +25,8 @@ import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts"; import * as DesktopUpdates from "./DesktopUpdates.ts"; import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts"; +const encodeUpdateState = Schema.encodeEffect(DesktopUpdateStateSchema); + type ReleaseFeed = Parameters[2]; type RunningVersion = Parameters[0]; @@ -81,16 +85,22 @@ describe("DesktopUpdates", () => { Effect.scoped( Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; + const desktopState = yield* DesktopState.DesktopState; yield* updates.configure; - return yield* updates.getState; + return { + state: yield* updates.getState, + canInstallUpdates: yield* Ref.get(desktopState.canInstallUpdates), + }; }), ).pipe(Effect.provide(makeHarness({ platform: "linux", packageType }).layer)); const deb = yield* linuxState("deb\n"); - assert.equal(deb.status, "idle"); + assert.equal(deb.state.status, "idle"); + assert.isTrue(deb.canInstallUpdates); const unmarked = yield* linuxState(undefined); - assert.equal(unmarked.status, "disabled"); + assert.equal(unmarked.state.status, "disabled"); + assert.isFalse(unmarked.canInstallUpdates); }), ); @@ -117,7 +127,7 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(harness.layer)); }); - it.effect("checks for newer releases after an update has been downloaded", () => { + it.effect("re-checks an offered update without announcing it again", () => { const harness = makeHarness(); return Effect.scoped( @@ -130,14 +140,23 @@ describe("DesktopUpdates", () => { releaseNotes: "## What's changed\n- fix: queued update", }); yield* flushCallbacks; + const offeredStates = harness.sentStates.length; + + yield* updates.check("poll"); + harness.emit("update-available", { version: "1.2.4" }); + yield* flushCallbacks; + assert.equal(harness.sentStates.length, offeredStates); + harness.emit("update-downloaded", { version: "1.2.4" }); yield* flushCallbacks; + const downloadedStates = harness.sentStates.length; const result = yield* updates.check("poll"); assert.isTrue(result.checked); harness.emit("update-available", { version: "1.2.4" }); yield* flushCallbacks; + assert.equal(harness.sentStates.length, downloadedStates); const unchangedState = yield* updates.getState; assert.equal(unchangedState.status, "downloaded"); @@ -239,15 +258,46 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); - it.effect( - "rejects install while a refresh check is in progress and releases the reservation", - () => + it.effect("checks shortly after startup and then every four minutes", () => { + const harness = makeHarness(); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + + yield* TestClock.adjust("15 seconds"); + assert.equal(harness.checkCount(), 1); + + yield* TestClock.adjust("3 minutes"); + assert.equal(harness.checkCount(), 1); + + yield* TestClock.adjust("1 minute"); + assert.equal(harness.checkCount(), 2); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect.each([ + { action: "download", offer: "update-available", found: null, accepted: true }, + { action: "install", offer: "update-downloaded", found: null, accepted: true }, + { action: "download", offer: "update-available", found: "1.2.5", accepted: true }, + { action: "install", offer: "update-downloaded", found: "1.2.5", accepted: false }, + ] as const)( + "a $action waiting out a refresh check acts on what it found ($found)", + ({ action, offer, found, accepted }) => Effect.gen(function* () { const checkStarted = yield* Deferred.make(); const releaseCheck = yield* Deferred.make(); const harness = makeHarness({ checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseCheck)), + // electron-updater emits the check's outcome before its promise resolves. + Effect.andThen( + Effect.sync(() => { + if (found !== null) harness.emit("update-available", { version: found }); + }), + ), ), }); @@ -255,22 +305,20 @@ describe("DesktopUpdates", () => { Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; yield* updates.configure; - harness.emit("update-downloaded", { version: "1.2.4" }); + harness.emit(offer, { version: "1.2.4" }); yield* flushCallbacks; - const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped); + const checkFiber = yield* updates.check("poll").pipe(Effect.forkScoped); yield* Deferred.await(checkStarted); - - const installResult = yield* updates.install; - assert.isFalse(installResult.accepted); + const actionFiber = yield* updates[action].pipe(Effect.forkScoped); + yield* flushCallbacks; yield* Deferred.succeed(releaseCheck, undefined); - const checkResult = yield* Fiber.join(checkFiber); - assert.isTrue(checkResult.checked); - - const followUpCheck = yield* updates.check("manual"); - assert.isTrue(followUpCheck.checked); - assert.equal(harness.checkCount(), 2); + assert.isTrue((yield* Fiber.join(checkFiber)).checked); + assert.equal((yield* Fiber.join(actionFiber)).accepted, accepted); + const state = yield* updates.getState; + assert.equal(state.availableVersion, found ?? "1.2.4"); + if (action === "download") assert.equal(state.status, "downloading"); }), ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }), @@ -295,10 +343,11 @@ describe("DesktopUpdates", () => { const installFiber = yield* updates.install.pipe(Effect.forkScoped); yield* Deferred.await(installStarted); + const checksBefore = harness.checkCount(); const checkResult = yield* updates.check("manual"); assert.isFalse(checkResult.checked); - assert.equal(harness.checkCount(), 0); + assert.equal(harness.checkCount(), checksBefore); yield* Deferred.succeed(releaseInstall, undefined); const installResult = yield* Fiber.join(installFiber); @@ -309,7 +358,9 @@ describe("DesktopUpdates", () => { ); it.effect("preserves a queued installer after a background updater error", () => { - const harness = makeHarness(); + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-not-available")), + }); return Effect.scoped( Effect.gen(function* () { @@ -418,6 +469,172 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("shows why a download failed, not only the channel", () => { + const harness = makeHarness({ + downloadUpdate: Effect.fail( + new ElectronUpdater.ElectronUpdaterDownloadUpdateError({ + channel: "nightly", + cause: new Error("net::ERR_CONTENT_LENGTH_MISMATCH"), + }), + ), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + harness.emit("update-available", { version: "1.2.4" }); + yield* flushCallbacks; + + const result = yield* updates.download; + assert.isFalse(result.completed); + + const state = yield* updates.getState; + assert.equal(state.errorContext, "download"); + assert.include(state.message ?? "", "ERR_CONTENT_LENGTH_MISMATCH"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("downloads the newest release published since the last check", () => { + // electron-updater downloads the release its last checkForUpdates found. + let published = "1.2.4"; + let lastChecked: string | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => { + lastChecked = published; + harness.emit("update-available", { version: published }); + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: lastChecked }); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + assert.equal((yield* updates.getState).availableVersion, "1.2.4"); + + published = "1.2.5"; + const result = yield* updates.download; + yield* flushCallbacks; + assert.isTrue(result.completed); + assert.equal((yield* updates.getState).downloadedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("installs a release published after the retained download", () => { + let published = "1.2.4"; + let lastChecked: string | undefined; + let installedVersion: string | null | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => { + lastChecked = published; + harness.emit("update-available", { version: published }); + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: lastChecked }); + }), + quitAndInstall: Effect.sync(() => { + installedVersion = harness.sentStates.at(-1)?.downloadedVersion; + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + yield* updates.download; + yield* flushCallbacks; + assert.equal((yield* updates.getState).downloadedVersion, "1.2.4"); + + published = "1.2.5"; + const checksBefore = harness.checkCount(); + const result = yield* updates.installPrepared("1.2.4"); + assert.isTrue(result.accepted); + // A second check before downloading could find a stale feed's older release. + assert.equal(harness.checkCount(), checksBefore + 1); + assert.equal(harness.quitAndInstalls(), 1); + assert.equal(installedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("downloads the known offer when the check before downloading fails", () => { + let checks = 0; + const harness = makeHarness({ + checkForUpdates: Effect.suspend(() => { + checks += 1; + if (checks > 1) { + return Effect.fail( + new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({ + channel: null, + cause: new Error("offline"), + }), + ); + } + harness.emit("update-available", { version: "1.2.4" }); + return Effect.void; + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: "1.2.4" }); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + + const result = yield* updates.download; + yield* flushCallbacks; + assert.isTrue(result.completed); + assert.equal((yield* updates.getState).downloadedVersion, "1.2.4"); + // Remote requests treat a published error after their own check as final. + assert.notInclude( + harness.sentStates.map((state) => state.status), + "error", + ); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("installs the retained download when a stale feed offers an older release", () => { + let published = "1.2.5"; + let installedVersion: string | null | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: published })), + downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.5" })), + quitAndInstall: Effect.sync(() => { + installedVersion = harness.sentStates.at(-1)?.downloadedVersion; + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* updates.download; + yield* flushCallbacks; + + published = "1.2.4"; + const result = yield* updates.installPrepared("1.2.5"); + assert.isTrue(result.accepted); + assert.equal(harness.downloadCount(), 1); + assert.equal(installedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("restores download state and permits retry after interruption", () => Effect.gen(function* () { const actionStarted = yield* Deferred.make(); @@ -487,6 +704,32 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("marks the update in progress before stopping the backend for an install", () => { + let inProgressAtStop: string | undefined; + const harness = makeHarness({ + stopBackend: Effect.sync(() => { + inProgressAtStop = harness.updateInProgressMarker(); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(1_000); + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + harness.emit("update-downloaded", { version: "1.2.4" }); + yield* flushCallbacks; + + assert.isTrue((yield* updates.install).accepted); + assert.deepEqual(JSON.parse(inProgressAtStop ?? "null"), { + startedAt: 1_000, + expiresAt: 61_000, + }); + assert.isDefined(harness.updateInProgressMarker()); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("records the version an install hands to the installer", () => { let recordsAtStop: ReadonlyArray = []; const harness = makeHarness({ @@ -548,6 +791,31 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("drops the update-in-progress marker when an install is interrupted", () => + Effect.gen(function* () { + const stopping = yield* Deferred.make(); + const harness = makeHarness({ + stopBackend: Deferred.succeed(stopping, undefined).pipe(Effect.andThen(Effect.never)), + }); + + yield* Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + harness.emit("update-downloaded", { version: "1.2.4" }); + yield* flushCallbacks; + + const installFiber = yield* updates.install.pipe(Effect.forkScoped); + yield* Deferred.await(stopping); + assert.isDefined(harness.updateInProgressMarker()); + + yield* Fiber.interrupt(installFiber); + assert.isUndefined(harness.updateInProgressMarker()); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }), + ); + it.effect("keeps windows and restarts backends when quitAndInstall fails", () => { const harness = makeHarness({ quitAndInstall: Effect.fail( @@ -572,6 +840,7 @@ describe("DesktopUpdates", () => { assert.isTrue(result.accepted); assert.isFalse(yield* Ref.get(desktopState.quitting)); assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]); + assert.isUndefined(harness.updateInProgressMarker()); assert.equal(harness.installRecords.size, 0); }), ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); @@ -847,6 +1116,32 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("keeps the current track's offers when a track switch fails to save", () => { + const harness = makeHarness({ + setUpdateChannelError: new DesktopAppSettings.DesktopSettingsWriteError({ + operation: "replace-settings-file", + path: "desktop-settings.json", + cause: new Error("rename failed"), + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + const error = yield* updates + .setChannel("nightly", { minimumVersion: "1.2.5-nightly.20261028.1" }) + .pipe(Effect.flip); + assert.equal(error._tag, "DesktopUpdateChannelPersistenceError"); + assert.equal((yield* updates.getState).channel, "latest"); + + harness.emit("update-available", { version: "1.2.4" }); + yield* flushCallbacks; + assert.equal((yield* updates.getState).availableVersion, "1.2.4"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("keeps a saved Stable track across a restart without offering an older release", () => { // A Nightly build whose switch to Stable did not finish before the app quit. const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1", savedChannel: "latest" }); @@ -1111,6 +1406,7 @@ describe("DesktopUpdates under a managed policy", () => { assert.equal(held.status, "disabled"); assert.include(held.message ?? "", message); assert.isTrue(held.channelBlockedByPolicy); + assert.isTrue((yield* encodeUpdateState(held)).channelBlockedByPolicy); assert.isFalse((yield* updates.check("menu")).checked); assert.equal(harness.checkCount(), 0); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index b4edc9790e..a9f94f292d 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -1,5 +1,7 @@ import { isFinckeDesktop } from "../fincke/build.ts"; import { + DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE, + DESKTOP_UPDATE_IN_PROGRESS_TTL_MS, DesktopUpdateChannelSchema, type DesktopRuntimeInfo, type DesktopUpdateActionResult, @@ -60,7 +62,7 @@ const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1); const CHANNEL_CHANGE_RETRIES = 30; const AUTO_UPDATE_STARTUP_DELAY = "15 seconds"; const AUTO_UPDATE_POLL_INTERVAL = "4 minutes"; -const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90); +const UPDATE_CHECK_WAIT = Duration.seconds(90); type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel"; @@ -315,6 +317,10 @@ function getCanRetryFromState(state: DesktopUpdateState): boolean { return state.availableVersion !== null || state.downloadedVersion !== null; } +function isOffered(state: DesktopUpdateState): boolean { + return state.status === "available" || state.status === "downloaded"; +} + function shouldBroadcastDownloadProgress( currentState: DesktopUpdateState, nextPercent: number, @@ -518,6 +524,23 @@ export const make = Effect.gen(function* () { ), ); + // Re-runs admit after each finished action, so a caller waiting on a check decides on its result. + const admitAfterCheck = Effect.fn("desktop.updates.admitAfterCheck")(function* ( + admit: Effect.Effect<"admitted" | "refused" | "wait-for-check">, + ) { + const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions); + let admission = yield* stateMutex.withPermits(1)(admit); + while (admission === "wait-for-check") { + const finishedAction = yield* PubSub.take(actionCompletions).pipe( + Effect.timeoutOption(UPDATE_CHECK_WAIT), + ); + admission = Option.isNone(finishedAction) + ? "refused" + : yield* stateMutex.withPermits(1)(admit); + } + return admission; + }); + const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* ( channel: DesktopUpdateChannel, ) { @@ -536,6 +559,17 @@ export const make = Effect.gen(function* () { }); }); + // The flag is shared updater state, so callers flip it only while holding a reservation. + const runUpdaterCheck = Effect.fn("desktop.updates.runUpdaterCheck")(function* ( + allowDowngrade: boolean, + ) { + const restoreDowngrade = yield* electronUpdater.allowDowngrade; + if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true); + return yield* electronUpdater.checkForUpdates.pipe( + Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)), + ); + }); + const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* ( reason: string, actionReservation: "acquire" | "held" = "acquire", @@ -559,15 +593,13 @@ export const make = Effect.gen(function* () { if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false; const check = Effect.gen(function* () { - const checkedAt = yield* currentIsoTimestamp; - yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt)); + // An offer stays on screen while re-checking, so finding it again changes nothing. + if (!isOffered(state)) { + yield* setState(reduceDesktopUpdateStateOnCheckStart(state, yield* currentIsoTimestamp)); + } yield* logUpdaterInfo("checking for updates", { reason }); - // The flag is shared updater state, so it flips only while this check holds the reservation. - const restoreDowngrade = yield* electronUpdater.allowDowngrade; - if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true); - return yield* electronUpdater.checkForUpdates.pipe( - Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)), + return yield* runUpdaterCheck(allowDowngrade).pipe( Effect.as(true), Effect.catchTags({ ElectronUpdaterCheckForUpdatesError: Effect.fn( @@ -596,17 +628,56 @@ export const make = Effect.gen(function* () { ); }); - const downloadAvailableUpdate = Effect.gen(function* () { - const state = yield* Ref.get(updateStateRef); - if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") { - return { accepted: false, completed: false }; - } - - if (!(yield* tryStartUpdateAction("download"))) { + // Install refreshes before downloading, and a second check could pick a stale, older release. + const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* ( + refresh: boolean, + ) { + const admission = yield* Effect.scoped( + admitAfterCheck( + Effect.gen(function* () { + const state = yield* Ref.get(updateStateRef); + if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") { + return "refused" as const; + } + const activeAction = yield* Ref.get(activeUpdateActionRef); + if (Option.isSome(activeAction)) { + return activeAction.value === "check" + ? ("wait-for-check" as const) + : ("refused" as const); + } + return (yield* tryStartUpdateAction("download")) + ? ("admitted" as const) + : ("refused" as const); + }), + ), + ); + if (admission === "refused") { return { accepted: false, completed: false }; } + const offered = yield* Ref.get(updateStateRef); + let state = offered; return yield* Effect.gen(function* () { + if (refresh) { + // electron-updater downloads what its last check found, which can be hours old. + yield* logUpdaterInfo("checking for updates", { reason: "download" }); + yield* runUpdaterCheck( + offered.channel !== desktopUpdateChannelOf(environment.appVersion), + ).pipe( + // A failed check keeps electron-updater's earlier result, so the known offer still downloads. + Effect.catchTags({ + ElectronUpdaterCheckForUpdatesError: (error) => + logUpdaterWarning(error.message, { + errorTag: error._tag, + cause: describeUpdateErrorCause(error.cause), + }), + }), + ); + } + state = yield* Ref.get(updateStateRef); + if (state.status !== "available") { + return { accepted: true, completed: false }; + } yield* setState(reduceDesktopUpdateStateOnDownloadStart(state)); yield* electronUpdater.setDisableDifferentialDownload( isArm64HostRunningIntelBuild(environment.runtimeInfo), @@ -618,12 +689,13 @@ export const make = Effect.gen(function* () { Effect.catchTags({ ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")( function* (error) { + const cause = describeUpdateErrorCause(error.cause); yield* updateState((current) => - reduceDesktopUpdateStateOnDownloadFailure(current, error.message), + reduceDesktopUpdateStateOnDownloadFailure(current, `${error.message} ${cause}`), ); yield* logUpdaterError(error.message, { errorTag: error._tag, - cause: describeUpdateErrorCause(error.cause), + cause, channel: error.channel, }); return { accepted: true, completed: false }; @@ -654,9 +726,38 @@ export const make = Effect.gen(function* () { }), Effect.ensuring(finishUpdateAction("download")), ); - }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate")); + }); const runtimeDir = environment.path.join(environment.baseDir, "runtime"); + const updateInProgressMarkerPath = environment.path.join( + runtimeDir, + DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE, + ); + const encodeUpdateMarker = Schema.encodeEffect( + Schema.fromJsonString(Schema.Struct({ startedAt: Schema.Number, expiresAt: Schema.Number })), + ); + const updateInProgressTempPath = `${updateInProgressMarkerPath}.tmp`; + const writeUpdateInProgressMarker = Effect.gen(function* () { + yield* fileSystem.makeDirectory(runtimeDir, { recursive: true }); + const startedAt = DateTime.toEpochMillis(yield* DateTime.now); + const contents = yield* encodeUpdateMarker({ + startedAt, + expiresAt: startedAt + DESKTOP_UPDATE_IN_PROGRESS_TTL_MS, + }); + yield* fileSystem.writeFileString(updateInProgressTempPath, contents); + yield* fileSystem.rename(updateInProgressTempPath, updateInProgressMarkerPath); + }).pipe( + Effect.ensuring( + fileSystem.remove(updateInProgressTempPath, { force: true }).pipe(Effect.ignore), + ), + Effect.catch((error) => + logUpdaterWarning("Could not write the update-in-progress marker.", { errorTag: error._tag }), + ), + ); + const removeUpdateInProgressMarker = fileSystem + .remove(updateInProgressMarkerPath, { force: true }) + .pipe(Effect.ignore); + const installRecordPath = environment.path.join(runtimeDir, DESKTOP_UPDATE_INSTALL_RECORD_FILE); const writeInstallRecord = (targetVersion: string) => encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe( @@ -704,6 +805,7 @@ export const make = Effect.gen(function* () { finishUpdateAction("install"), Ref.set(desktopState.quitting, false), Ref.set(installRunningBackendsRef, []), + removeUpdateInProgressMarker, removeInstallRecord, ], { discard: true }, @@ -720,6 +822,7 @@ export const make = Effect.gen(function* () { if (!ownsRecovery) return; yield* Ref.set(desktopState.quitting, false); + yield* removeUpdateInProgressMarker; yield* removeInstallRecord; yield* Effect.gen(function* () { const runningInstances = yield* Ref.getAndSet(installRunningBackendsRef, []); @@ -745,47 +848,35 @@ export const make = Effect.gen(function* () { const installDownloadedUpdate = (expectedVersion?: string) => Effect.scoped( Effect.gen(function* () { - const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions); - let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check"; - while (admission === "wait-for-check") { - admission = yield* stateMutex.withPermits(1)( - Effect.gen(function* () { - const state = yield* Ref.get(updateStateRef); - const activeAction = yield* Ref.get(activeUpdateActionRef); - const hasExpectedDownload = - state.downloadedVersion !== null && - (expectedVersion === undefined || state.downloadedVersion === expectedVersion); - if ( - (yield* Ref.get(desktopState.quitting)) || - !(yield* Ref.get(updaterConfiguredRef)) || - !hasExpectedDownload - ) { - return "refused" as const; - } - if (Option.isSome(activeAction)) { - return activeAction.value === "check" && expectedVersion !== undefined - ? ("wait-for-check" as const) - : ("refused" as const); - } - const hasInstallableDownload = - state.status === "downloaded" || - (state.status === "error" && - (state.errorContext === null || state.errorContext === "install")); - if (!hasInstallableDownload) return "refused" as const; - return (yield* tryStartUpdateAction("install")) - ? ("admitted" as const) + const admission = yield* admitAfterCheck( + Effect.gen(function* () { + const state = yield* Ref.get(updateStateRef); + const activeAction = yield* Ref.get(activeUpdateActionRef); + const hasExpectedDownload = + state.downloadedVersion !== null && + (expectedVersion === undefined || state.downloadedVersion === expectedVersion); + if ( + (yield* Ref.get(desktopState.quitting)) || + !(yield* Ref.get(updaterConfiguredRef)) || + !hasExpectedDownload + ) { + return "refused" as const; + } + if (Option.isSome(activeAction)) { + return activeAction.value === "check" + ? ("wait-for-check" as const) : ("refused" as const); - }), - ); - if (admission === "wait-for-check") { - const finishedAction = yield* PubSub.take(actionCompletions).pipe( - Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT), - ); - if (Option.isNone(finishedAction)) { - admission = "refused"; } - } - } + const hasInstallableDownload = + state.status === "downloaded" || + (state.status === "error" && + (state.errorContext === null || state.errorContext === "install")); + if (!hasInstallableDownload) return "refused" as const; + return (yield* tryStartUpdateAction("install")) + ? ("admitted" as const) + : ("refused" as const); + }), + ); if (admission === "refused") { return { accepted: false, completed: false, failed: false }; } @@ -794,6 +885,7 @@ export const make = Effect.gen(function* () { yield* Ref.set(installRunningBackendsRef, []); return yield* Effect.gen(function* () { + yield* writeUpdateInProgressMarker; const { downloadedVersion } = yield* Ref.get(updateStateRef); if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion); // Stop pooled backends before quitAndInstall can outrun their scope finalizers. @@ -861,7 +953,42 @@ export const make = Effect.gen(function* () { state: yield* Ref.get(updateStateRef), }; } - const result = yield* installDownloadedUpdate(expectedVersion); + let installVersion = expectedVersion; + // A download can be hours old: a release published since replaces it before restarting. + const retained = yield* Ref.get(updateStateRef); + if ( + retained.downloadedVersion !== null && + (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) && + (yield* checkForUpdates( + "install", + "acquire", + retained.channel !== desktopUpdateChannelOf(environment.appVersion), + )) && + (yield* Ref.get(updateStateRef)).status === "available" + ) { + const refreshed = yield* Ref.get(updateStateRef); + // electron-updater compares a stale feed with the running build, not the retained download. + if ( + refreshed.availableVersion === null || + compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0 + ) { + yield* setState(retained); + } else { + const download = yield* downloadAvailableUpdate(false); + if (!download.completed) { + return { + accepted: download.accepted, + completed: false, + failed: download.accepted, + state: yield* Ref.get(updateStateRef), + }; + } + if (expectedVersion !== undefined) { + installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion; + } + } + } + const result = yield* installDownloadedUpdate(installVersion); return { accepted: result.accepted, completed: result.completed, @@ -921,6 +1048,7 @@ export const make = Effect.gen(function* () { yield* Ref.set(lastLoggedDownloadMilestoneRef, -1); return; } + if (isOffered(state) && state.availableVersion === info.version) return; const checkedAt = yield* currentIsoTimestamp; const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes( @@ -1100,6 +1228,8 @@ export const make = Effect.gen(function* () { ), configure: Effect.gen(function* () { const context = yield* Effect.context(); + // Runs synchronously up to the first await, so a check's outcome is applied before the + // check's promise resolves and wakes the actions waiting on it. const runEffect = (effect: Effect.Effect) => { void Effect.runPromiseWith(context)(effect); }; @@ -1131,6 +1261,8 @@ export const make = Effect.gen(function* () { const settings = yield* desktopSettings.get; const disabledReason = yield* resolveDisabledReason; + // A blocked nightly channel still lets the user switch back to stable, so it stays updatable. + yield* Ref.set(desktopState.canInstallUpdates, Option.isNone(disabledReason)); yield* setState( yield* baseUpdateState( settings.updateChannel, @@ -1207,7 +1339,10 @@ export const make = Effect.gen(function* () { } return yield* Effect.gen(function* () { - yield* Ref.set(releaseFloorRef, Option.fromNullishOr(options?.minimumVersion)); + const previousFloor = yield* Ref.getAndSet( + releaseFloorRef, + Option.fromNullishOr(options?.minimumVersion), + ); const state = yield* Ref.get(updateStateRef); const retained = state.downloadedVersion ?? state.availableVersion; // A build from another track re-checks, so retrying a track switch finds an older release. @@ -1220,13 +1355,12 @@ export const make = Effect.gen(function* () { return state; } - yield* desktopSettings - .setUpdateChannel(nextChannel) - .pipe( - Effect.mapError( - (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }), - ), - ); + yield* desktopSettings.setUpdateChannel(nextChannel).pipe( + Effect.onError(() => Ref.set(releaseFloorRef, previousFloor)), + Effect.mapError( + (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }), + ), + ); const disabledReason = yield* resolveDisabledReason; yield* setState(yield* baseUpdateState(nextChannel, disabledReason)); @@ -1263,7 +1397,7 @@ export const make = Effect.gen(function* () { }; }), download: Effect.gen(function* () { - const result = yield* downloadAvailableUpdate; + const result = yield* downloadAvailableUpdate(true); return { accepted: result.accepted, completed: result.completed, diff --git a/apps/desktop/src/updates/releaseNotes.test.ts b/apps/desktop/src/updates/releaseNotes.test.ts index 6f05b1e9e9..a8fcc70ea3 100644 --- a/apps/desktop/src/updates/releaseNotes.test.ts +++ b/apps/desktop/src/updates/releaseNotes.test.ts @@ -241,14 +241,20 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { }); }); - it("does not throw on out-of-range numeric entities and keeps the literal", () => { + it("keeps unsupported entities literal, including out-of-range and Object.prototype names", () => { const result = normalizeDesktopUpdateReleaseNotes( - "- Broken entity �", + "- Broken entity �\n- Mentions &constructor; and &toString;", "1.0.0", "latest", ); expect(result).toEqual({ - releaseNotes: [{ version: "1.0.0", items: ["Broken entity �"], totalItems: 1 }], + releaseNotes: [ + { + version: "1.0.0", + items: ["Mentions &constructor; and &toString;", "Broken entity �"], + totalItems: 2, + }, + ], omittedReleaseCount: 0, }); }); diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts index 715c1767e6..30bfb9ace6 100644 --- a/apps/desktop/src/updates/releaseNotes.ts +++ b/apps/desktop/src/updates/releaseNotes.ts @@ -20,14 +20,14 @@ const MAX_RELEASE_NOTE_GROUPS = 6; const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8; const MAX_RELEASE_NOTE_ITEM_LENGTH = 220; -const HTML_ENTITY_REPLACEMENTS: Readonly> = { - amp: "&", - apos: "'", - gt: ">", - lt: "<", - nbsp: " ", - quot: '"', -}; +const HTML_ENTITY_REPLACEMENTS: ReadonlyMap = new Map([ + ["amp", "&"], + ["apos", "'"], + ["gt", ">"], + ["lt", "<"], + ["nbsp", " "], + ["quot", '"'], +]); function decodeCodePoint(codePoint: number, entity: string): string { if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) { @@ -37,7 +37,7 @@ function decodeCodePoint(codePoint: number, entity: string): string { } function decodeHtmlEntity(entity: string): string { - const named = HTML_ENTITY_REPLACEMENTS[entity]; + const named = HTML_ENTITY_REPLACEMENTS.get(entity); if (named) return named; if (entity.startsWith("#x")) { return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity); diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index 7ff7ea451f..e9ed3363cc 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -27,7 +27,7 @@ export interface UpdatesHarnessOptions { readonly beforeSetUpdateChannel?: Effect.Effect; readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError; readonly setDisableDifferentialDownload?: Effect.Effect; - readonly downloadUpdate?: Effect.Effect; + readonly downloadUpdate?: Effect.Effect; readonly quitAndInstall?: Effect.Effect; readonly stopBackend?: Effect.Effect; readonly startBackend?: Effect.Effect; @@ -236,6 +236,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { } satisfies DesktopAppSettings.DesktopAppSettings["Service"]) : DesktopAppSettings.layer; + const updateMarkerContents = new Map(); const installRecords = new Map(); let previousInstallRecord = options.installRecord; const isInstallRecord = (path: string) => @@ -261,9 +262,17 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { writeFileString: (path, data) => Effect.sync(() => { if (isInstallRecord(path)) installRecords.set(path, data); + else updateMarkerContents.set(path, data); + }), + rename: (from, to) => + Effect.sync(() => { + const contents = updateMarkerContents.get(from); + if (contents !== undefined) updateMarkerContents.set(to, contents); + updateMarkerContents.delete(from); }), remove: (path) => Effect.sync(() => { + updateMarkerContents.delete(path); installRecords.delete(path); if (isInstallRecord(path)) previousInstallRecord = undefined; }), @@ -294,6 +303,8 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { checkCount: () => checkCount, quitAndInstalls: () => quitAndInstallCount, installSteps, + updateInProgressMarker: () => + [...updateMarkerContents].find(([path]) => path.endsWith("/desktop-update-in-progress"))?.[1], installRecords, previousInstallRecord: () => previousInstallRecord, downloadCount: () => downloadCount, diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 612ec441ba..46004ca302 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -3,7 +3,9 @@ import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import type { DesktopUpdateCheckResult, DesktopUpdateState } from "@t3tools/contracts"; import * as Electron from "electron"; import { vi } from "vite-plus/test"; @@ -18,6 +20,7 @@ import * as DesktopApplicationMenu from "./DesktopApplicationMenu.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopUpdates from "../updates/DesktopUpdates.ts"; +import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts"; import * as DesktopWindow from "./DesktopWindow.ts"; const environmentInput = { @@ -56,27 +59,37 @@ const layerElectronApp = Layer.succeed(ElectronApp.ElectronApp, { on: () => Effect.void, } satisfies ElectronApp.ElectronApp["Service"]); -const layerElectronDialog = Layer.succeed(ElectronDialog.ElectronDialog, { - pickFolder: () => Effect.succeedNone, - pickFiles: () => Effect.succeed([]), - showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }), - showErrorBox: () => Effect.void, -} satisfies ElectronDialog.ElectronDialog["Service"]); - -const layerDesktopUpdates = Layer.succeed(DesktopUpdates.DesktopUpdates, { - getState: Effect.die("unexpected getState"), - isActionActive: Effect.succeed(false), - isInstallActive: Effect.succeed(false), - subscribe: Effect.die("unexpected subscribe"), - emitState: Effect.void, - disabledReason: Effect.succeedNone, - configure: Effect.void, - setChannel: () => Effect.die("unexpected setChannel"), - check: () => Effect.die("unexpected check"), - download: Effect.die("unexpected download"), - install: Effect.die("unexpected install"), - installPrepared: () => Effect.die("unexpected installPrepared"), -} satisfies DesktopUpdates.DesktopUpdates["Service"]); +interface MenuServices { + readonly checkResult?: DesktopUpdateCheckResult; + readonly shownMessageBox?: Deferred.Deferred; +} + +const layerElectronDialog = ({ shownMessageBox }: MenuServices) => + Layer.succeed(ElectronDialog.ElectronDialog, { + pickFolder: () => Effect.succeedNone, + pickFiles: () => Effect.succeed([]), + showMessageBox: (options) => + (shownMessageBox ? Deferred.succeed(shownMessageBox, options) : Effect.void).pipe( + Effect.as({ response: options.cancelId ?? 0, checkboxChecked: false }), + ), + showErrorBox: () => Effect.void, + } satisfies ElectronDialog.ElectronDialog["Service"]); + +const layerDesktopUpdates = ({ checkResult }: MenuServices) => + Layer.succeed(DesktopUpdates.DesktopUpdates, { + getState: Effect.die("unexpected getState"), + isActionActive: Effect.succeed(false), + isInstallActive: Effect.succeed(false), + subscribe: Effect.die("unexpected subscribe"), + emitState: Effect.void, + disabledReason: Effect.succeedNone, + configure: Effect.void, + setChannel: () => Effect.die("unexpected setChannel"), + check: () => (checkResult ? Effect.succeed(checkResult) : Effect.die("unexpected check")), + download: Effect.die("unexpected download"), + install: Effect.die("unexpected install"), + installPrepared: () => Effect.die("unexpected installPrepared"), + } satisfies DesktopUpdates.DesktopUpdates["Service"]); const layerDesktopWindow = (selectedAction: Deferred.Deferred) => Layer.succeed(DesktopWindow.DesktopWindow, { @@ -113,6 +126,7 @@ const configureMenu = ( selectedAction: Deferred.Deferred, applicationMenuTemplate: Deferred.Deferred, environment: Partial = {}, + services: MenuServices = {}, ) => Effect.gen(function* () { const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu; @@ -122,8 +136,8 @@ const configureMenu = ( DesktopApplicationMenu.layer.pipe( Layer.provideMerge(layerElectronMenu(applicationMenuTemplate)), Layer.provideMerge(layerDesktopWindow(selectedAction)), - Layer.provideMerge(layerDesktopUpdates), - Layer.provideMerge(layerElectronDialog), + Layer.provideMerge(layerDesktopUpdates(services)), + Layer.provideMerge(layerElectronDialog(services)), Layer.provideMerge(layerElectronApp), Layer.provideMerge( DesktopEnvironment.layer({ ...environmentInput, ...environment }).pipe( @@ -134,6 +148,54 @@ const configureMenu = ( ), ); +const checkForUpdatesFromMacMenu = (state: Partial) => + Effect.gen(function* () { + const applicationMenuTemplate = + yield* Deferred.make(); + const shownMessageBox = yield* Deferred.make(); + yield* configureMenu( + yield* Deferred.make(), + applicationMenuTemplate, + { platform: "darwin" }, + { + checkResult: { + checked: true, + state: { + ...createInitialDesktopUpdateState( + "0.1.5", + { hostArch: "arm64", appArch: "arm64", runningUnderArm64Translation: false }, + "latest", + ), + enabled: true, + ...state, + }, + }, + shownMessageBox, + }, + ); + + const appMenu = (yield* Deferred.await(applicationMenuTemplate))[0]; + if (!Array.isArray(appMenu?.submenu)) { + throw new Error("Expected the macOS app menu submenu to be an array."); + } + const checkForUpdates = appMenu.submenu.find((item) => item.label === "Check for Updates..."); + if (typeof checkForUpdates?.click !== "function") { + throw new Error("Expected Check for Updates... menu item to have a click handler."); + } + + // Every stub completes synchronously, so the menu action has finished when click returns. + checkForUpdates.click( + {} as Electron.MenuItem, + {} as Electron.BrowserWindow, + {} as KeyboardEvent, + ); + const dialog = yield* Deferred.poll(shownMessageBox); + if (Option.isNone(dialog)) { + throw new Error("Check for Updates... finished without showing any dialog."); + } + return yield* dialog.value; + }); + describe("DesktopApplicationMenu", () => { it.effect("leaves the accelerator to Chromium instead of injecting a paste", () => Effect.gen(function* () { @@ -285,4 +347,25 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); + it.effect("tells the user which update the menu check found", () => + Effect.gen(function* () { + const dialog = yield* checkForUpdatesFromMacMenu({ + status: "available", + availableVersion: "0.1.7", + }); + assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7"); + }), + ); + + it.effect("tells the user a downloaded update is ready when the menu check runs", () => + Effect.gen(function* () { + const dialog = yield* checkForUpdatesFromMacMenu({ + status: "downloaded", + availableVersion: "0.1.7", + downloadedVersion: "0.1.7", + downloadPercent: 100, + }); + assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7"); + }), + ); }); diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 5f89126978..f666d0699a 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -65,6 +65,9 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")( yield* desktopWindow.runMainContentsCommand(command); }); +const describeUpdate = (version: string | null) => + version === null ? `A new version of ${DESKTOP_APP_NAME}` : `${DESKTOP_APP_NAME} ${version}`; + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -78,6 +81,35 @@ const checkForUpdatesFromMenu = Effect.gen(function* () { message: `${DESKTOP_APP_NAME} ${updateState.currentVersion} is currently the newest version available.`, buttons: ["OK"], }); + } else if (updateState.status === "available") { + const { response } = yield* electronDialog.showMessageBox({ + type: "info", + title: "Update available", + message: `${describeUpdate(updateState.availableVersion)} is available.`, + detail: `You're running ${DESKTOP_APP_NAME} ${updateState.currentVersion}.`, + buttons: ["Download", "Later"], + defaultId: 0, + cancelId: 1, + }); + if (response === 0) yield* updates.download; + } else if (updateState.status === "downloading") { + yield* electronDialog.showMessageBox({ + type: "info", + title: "Update downloading", + message: `${describeUpdate(updateState.availableVersion)} is already downloading.`, + buttons: ["OK"], + }); + } else if (updateState.status === "downloaded") { + const { response } = yield* electronDialog.showMessageBox({ + type: "info", + title: "Update ready", + message: `${describeUpdate(updateState.downloadedVersion ?? updateState.availableVersion)} is ready to install.`, + detail: `${DESKTOP_APP_NAME} will restart to install it. Any running tasks will be interrupted.`, + buttons: ["Restart", "Later"], + defaultId: 0, + cancelId: 1, + }); + if (response === 0) yield* updates.install; } else if (updateState.status === "error") { yield* electronDialog.showMessageBox({ type: "warning", diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 91d034cbd7..46311dbba8 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -36,6 +36,7 @@ vi.mock("electron", async (importOriginal) => ({ import * as DesktopAssets from "../app/DesktopAssets.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import * as DesktopPrimaryPaste from "../app/DesktopPrimaryPaste.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; @@ -48,6 +49,10 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import { SNAP_SHOT_EVENT_CHANNEL } from "../ipc/channels.ts"; import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; import * as DesktopWindow from "./DesktopWindow.ts"; +import { + PASSKEY_BRIDGE_ARGUMENT, + PRIMARY_PASTE_DISABLED_ARGUMENT, +} from "../preview/GuestProtocol.ts"; import * as PreviewManager from "../preview/Manager.ts"; import * as PreviewPasskeys from "../preview/Passkeys.ts"; @@ -202,17 +207,20 @@ const layerElectronTheme = Layer.succeed(ElectronTheme.ElectronTheme, { onUpdated: () => Effect.void, } satisfies ElectronTheme.ElectronTheme["Service"]); -const layerDesktopEnvironment = DesktopEnvironment.layer(environmentInput).pipe( - Layer.provide( - Layer.mergeAll( - NodeServices.layer, - DesktopConfig.layerTest({ - T3CODE_PORT: "3773", - VITE_DEV_SERVER_URL: "http://127.0.0.1:5733", - }), +const layerDesktopEnvironmentFor = (platform: NodeJS.Platform) => + DesktopEnvironment.layer({ ...environmentInput, platform }).pipe( + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + DesktopConfig.layerTest({ + T3CODE_PORT: "3773", + VITE_DEV_SERVER_URL: "http://127.0.0.1:5733", + }), + ), ), - ), -); + ); + +const layerDesktopEnvironment = layerDesktopEnvironmentFor(environmentInput.platform); const desktopWindowBoundsEquivalence = Schema.toEquivalence( DesktopAppSettings.DesktopWindowBoundsSchema, @@ -238,6 +246,14 @@ function layerTest(input: { readonly previewZoomReapplies?: number[]; readonly onReveal?: (window: Electron.BrowserWindow) => void; readonly focusedWindow?: Electron.BrowserWindow; + readonly fallbackWindow?: Electron.BrowserWindow; + readonly platform?: NodeJS.Platform; + readonly appearanceWindows?: ReadonlyArray<{ + readonly window: Electron.BrowserWindow; + readonly titleBarOverlay: boolean; + }>; + readonly primaryPasteEnabled?: boolean; + readonly previewPasskeyBridgeEnabled?: boolean; }) { let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS; const layerDesktopAppSettings = Layer.succeed(DesktopAppSettings.DesktopAppSettings, { @@ -284,7 +300,9 @@ function layerTest(input: { Effect.as(input.window), ), main: Ref.get(input.mainWindow), - currentMainOrFirst: Ref.get(input.mainWindow), + currentMainOrFirst: Ref.get(input.mainWindow).pipe( + Effect.map(Option.orElse(() => Option.fromNullishOr(input.fallbackWindow ?? null))), + ), focusedMainOrFirst: input.focusedWindow === undefined ? Ref.get(input.mainWindow) @@ -295,7 +313,14 @@ function layerTest(input: { reveal: (window) => Effect.sync(() => input.onReveal?.(window)), sendAll: () => Effect.void, destroyAll: input.destroyAll ?? Effect.void, - syncAllAppearance: (sync) => sync(input.window), + syncAllAppearance: (sync) => + input.appearanceWindows === undefined + ? sync(input.window, { titleBarOverlay: true }) + : Effect.forEach( + input.appearanceWindows, + ({ window, titleBarOverlay }) => sync(window, { titleBarOverlay }), + { discard: true }, + ), } satisfies ElectronWindow.ElectronWindow["Service"]); return DesktopWindow.layer.pipe( @@ -307,7 +332,9 @@ function layerTest(input: { recordMetrics: () => Effect.void, shutdown: Effect.void, }), - layerDesktopEnvironment, + input.platform === undefined + ? layerDesktopEnvironment + : layerDesktopEnvironmentFor(input.platform), layerDesktopAppSettings, layerDesktopClientSettings, layerDesktopServerExposure, @@ -329,8 +356,11 @@ function layerTest(input: { } satisfies ElectronShell.ElectronShell["Service"]), layerElectronTheme, layerElectronWindow, + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { + enabled: input.primaryPasteEnabled ?? true, + }), Layer.mock(PreviewPasskeys.PreviewPasskeys)({ - bridgeEnabled: false, + bridgeEnabled: input.previewPasskeyBridgeEnabled ?? false, installSessionHandlers: () => {}, attachGuest: () => () => {}, }), @@ -413,7 +443,8 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]), sendAll: () => Effect.void, destroyAll: Effect.void, - syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void), + syncAllAppearance: (sync) => + fallbackWindow ? sync(fallbackWindow, { titleBarOverlay: true }) : Effect.void, } satisfies ElectronWindow.ElectronWindow["Service"]; const layer = DesktopWindow.layer.pipe( @@ -439,6 +470,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n } satisfies ElectronShell.ElectronShell["Service"]), layerElectronTheme, Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape), + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), Layer.mock(PreviewPasskeys.PreviewPasskeys)({ bridgeEnabled: false, installSessionHandlers: () => {}, @@ -815,7 +847,7 @@ describe("DesktopWindow", () => { }), ); - it.effect("reloads and inspects the main window even when a popup has focus", () => + it.effect("routes menu commands to the main window even when a popup has focus", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); const popup = makeFakeBrowserWindow(); @@ -835,7 +867,10 @@ describe("DesktopWindow", () => { yield* desktopWindow.runMainContentsCommand("reload"); yield* desktopWindow.runMainContentsCommand("forceReload"); yield* desktopWindow.runMainContentsCommand("toggleDevTools"); + yield* desktopWindow.dispatchMenuAction("open-settings"); + assert.deepEqual(fakeWindow.send.mock.calls, [["desktop:menu-action", "open-settings"]]); + assert.equal(popup.send.mock.calls.length, 0); assert.equal(fakeWindow.reload.mock.calls.length, 1); assert.equal(fakeWindow.reloadIgnoringCache.mock.calls.length, 1); assert.equal(fakeWindow.toggleDevTools.mock.calls.length, 1); @@ -846,6 +881,38 @@ describe("DesktopWindow", () => { }), ); + it.effect("recreates main for Settings when only an unregistered popup survives", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const auxiliary = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.dispatchMenuAction("open-settings"); + assert.deepEqual(main.send.mock.calls, [["desktop:menu-action", "open-settings"]]); + assert.equal(auxiliary.send.mock.calls.length, 0); + assert.equal(yield* Ref.get(createCount), 1); + assert.strictEqual(yield* windows.ensureMain, main.window); + assert.equal(yield* Ref.get(createCount), 1); + }).pipe( + Effect.provide( + layerTest({ + window: main.window, + createCount, + mainWindow, + fallbackWindow: auxiliary.window, + desktopSettings: { + ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, + localEnvironmentEnabled: false, + }, + }), + ), + ); + }), + ); + it.effect("does not open main or splash windows once quitting has started", () => Effect.gen(function* () { const fake = makeFakeBrowserWindow(); @@ -1012,11 +1079,75 @@ describe("DesktopWindow", () => { assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]); assert.deepEqual(mainWindowMaximizedUpdates, [true]); assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1); - assert.equal(fakeWindow.getBounds.mock.calls.length, 0); }).pipe(Effect.provide(layer)); }), ); + it.effect.each([ + { normal: "on display 1", width: 1920, height: 1080, x: 220 }, + { normal: "on display 1", width: 1280, height: 720, x: 220 }, + { normal: "straddling both displays", width: 1920, height: 1080, x: 1800 }, + ])( + "persists bounds on the display a maximized window was moved to ($width x $height, normal $normal)", + ({ width, height, x }) => + Effect.gen(function* () { + const displayOne = { x: 0, y: 0, width: 1920, height: 1080 }; + const displayTwo = { x: 1920, y: 0, width, height }; + const getAllDisplays = vi.mocked(Electron.screen.getAllDisplays); + getAllDisplays.mockReturnValue([ + { bounds: displayOne, workArea: displayOne }, + { bounds: displayTwo, workArea: displayTwo }, + ] as unknown as Electron.Display[]); + const fakeWindow = makeFakeBrowserWindow(); + fakeWindow.isMaximized.mockReturnValue(true); + fakeWindow.getBounds.mockReturnValue(displayTwo); + fakeWindow.getNormalBounds.mockReturnValue({ x, y: 140, width: 1380, height: 920 }); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; + const mainWindowMaximizedUpdates: boolean[] = []; + const layer = layerTest({ + window: fakeWindow.window, + createCount, + mainWindow, + mainWindowBoundsUpdates, + mainWindowMaximizedUpdates, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const move = fakeWindow.windowListeners.get("move"); + if (!move) { + return yield* Effect.die("window move listener was not registered"); + } + move(); + yield* TestClock.adjust(500); + yield* Effect.promise(() => Promise.resolve()); + + const persisted = mainWindowBoundsUpdates.at(-1); + assert.isDefined(persisted, "maximized window bounds were not persisted"); + const persistedDisplay = [displayOne, displayTwo].findIndex( + (display) => + persisted.x >= display.x && + persisted.y >= display.y && + persisted.x + persisted.width <= display.x + display.width && + persisted.y + persisted.height <= display.y + display.height, + ); + assert.equal( + persistedDisplay, + 1, + `window maximized on display 2 persisted bounds ${JSON.stringify(persisted)}, which restore on display ${persistedDisplay + 1}`, + ); + assert.deepEqual(mainWindowMaximizedUpdates, [true]); + }).pipe( + Effect.provide(layer), + Effect.ensuring(Effect.sync(() => getAllDisplays.mockReset())), + ); + }), + ); + it.effect("preserves unrestorable bounds until the user changes the window", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1060,8 +1191,7 @@ describe("DesktopWindow", () => { it.effect("flushes normal bounds when minimized before the debounce completes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); - fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 }); - fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 }); + fakeWindow.getBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 }); const createCount = yield* Ref.make(0); const mainWindow = yield* Ref.make>(Option.none()); const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; @@ -1082,17 +1212,149 @@ describe("DesktopWindow", () => { } resize(); yield* TestClock.adjust(250); + // Windows reports a minimized window at -32000. fakeWindow.isMinimized.mockReturnValue(true); + fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 }); yield* desktopWindow.flushMainWindowBounds; + resize(); + yield* TestClock.adjust(500); + yield* Effect.promise(() => Promise.resolve()); assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]); - assert.equal(fakeWindow.getBounds.mock.calls.length, 0); - assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1); }).pipe(Effect.provide(layer)); }), ); + it.effect( + "brings the window back after the renderer dies more often than the reload budget", + () => + Effect.gen(function* () { + const fakeWindow = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const renderProcessGone = fakeWindow.webContentsListeners.get("render-process-gone"); + if (!renderProcessGone) { + return yield* Effect.die("render-process-gone listener was not registered"); + } + for (let crash = 1; crash <= 4; crash++) { + const loadsBefore = fakeWindow.loadURL.mock.calls.length; + renderProcessGone({}, { reason: "oom", exitCode: -536870904 }); + yield* TestClock.adjust(crash < 4 ? 1_000 : 60_000); + yield* Effect.promise(() => Promise.resolve()); + assert.isAbove( + fakeWindow.loadURL.mock.calls.length, + loadsBefore, + `window shows nothing after renderer crash ${crash}`, + ); + } + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect("updates title bar overlays only on windows created with one", () => + Effect.gen(function* () { + const framed = makeFakeBrowserWindow(); + vi.mocked(framed.window.setTitleBarOverlay).mockImplementation(() => { + throw new TypeError("Titlebar overlay is not enabled"); + }); + const overlay = makeFakeBrowserWindow(); + const layer = layerTest({ + window: overlay.window, + createCount: yield* Ref.make(0), + mainWindow: yield* Ref.make>(Option.none()), + platform: "win32", + appearanceWindows: [ + { window: framed.window, titleBarOverlay: false }, + { window: overlay.window, titleBarOverlay: true }, + ], + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.syncAppearance; + }).pipe(Effect.provide(layer)); + + assert.deepEqual(vi.mocked(framed.window.setBackgroundColor).mock.calls, [["#ffffff"]]); + assert.lengthOf(vi.mocked(framed.window.setTitleBarOverlay).mock.calls, 0); + assert.deepEqual(vi.mocked(overlay.window.setBackgroundColor).mock.calls, [["#ffffff"]]); + assert.lengthOf(vi.mocked(overlay.window.setTitleBarOverlay).mock.calls, 1); + }), + ); + + it.effect.each([ + { window: "normal", write: "flush" }, + { window: "normal", write: "debounce" }, + { window: "maximized", write: "flush" }, + { window: "maximized", write: "debounce" }, + ] as const)("persists a $window window change minimized before its $write", (input) => + Effect.gen(function* () { + const displayOne = { x: 0, y: 0, width: 1920, height: 1080 }; + const displayTwo = { x: 1920, y: 0, width: 1920, height: 1080 }; + const getAllDisplays = vi.mocked(Electron.screen.getAllDisplays); + getAllDisplays.mockReturnValue([ + { bounds: displayOne, workArea: displayOne }, + { bounds: displayTwo, workArea: displayTwo }, + ] as unknown as Electron.Display[]); + const maximized = input.window === "maximized"; + const fakeWindow = makeFakeBrowserWindow(); + fakeWindow.isMaximized.mockReturnValue(maximized); + fakeWindow.getBounds.mockReturnValue( + maximized ? displayTwo : { x: 220, y: 140, width: 1380, height: 920 }, + ); + fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 }); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; + const mainWindowMaximizedUpdates: boolean[] = []; + const layer = layerTest({ + window: fakeWindow.window, + createCount, + mainWindow, + mainWindowBoundsUpdates, + mainWindowMaximizedUpdates, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const move = fakeWindow.windowListeners.get("move"); + if (!move) { + return yield* Effect.die("window move listener was not registered"); + } + move(); + yield* TestClock.adjust(250); + // Minimized windows report stale state: macOS unmaximized at the pre-move frame. + fakeWindow.isMinimized.mockReturnValue(true); + fakeWindow.isMaximized.mockReturnValue(false); + fakeWindow.getBounds.mockReturnValue({ x: 100, y: 100, width: 1100, height: 780 }); + fakeWindow.getNormalBounds.mockReturnValue({ x: 100, y: 100, width: 1100, height: 780 }); + if (input.write === "debounce") { + yield* TestClock.adjust(250); + yield* Effect.promise(() => Promise.resolve()); + } + yield* desktopWindow.flushMainWindowBounds; + + assert.deepEqual(mainWindowBoundsUpdates, [ + maximized + ? { x: 2140, y: 140, width: 1380, height: 920 } + : { x: 220, y: 140, width: 1380, height: 920 }, + ]); + assert.deepEqual(mainWindowMaximizedUpdates, [maximized]); + }).pipe( + Effect.provide(layer), + Effect.ensuring(Effect.sync(() => getAllDisplays.mockReset())), + ); + }), + ); + it.effect("maps macOS horizontal swipes to available history navigation", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1183,6 +1445,43 @@ describe("DesktopWindow", () => { }), ); + it.effect.each([ + { + primaryPasteEnabled: false, + expected: [PASSKEY_BRIDGE_ARGUMENT, PRIMARY_PASTE_DISABLED_ARGUMENT], + }, + { primaryPasteEnabled: true, expected: [PASSKEY_BRIDGE_ARGUMENT] }, + ])( + "passes the primary-paste setting to preview guests (enabled: $primaryPasteEnabled)", + ({ primaryPasteEnabled, expected }) => + Effect.gen(function* () { + const fakeWindow = makeFakeBrowserWindow(); + const layer = layerTest({ + window: fakeWindow.window, + createCount: yield* Ref.make(0), + mainWindow: yield* Ref.make>(Option.none()), + primaryPasteEnabled, + previewPasskeyBridgeEnabled: true, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const willAttachWebview = fakeWindow.webContentsListeners.get("will-attach-webview"); + if (!willAttachWebview) { + return yield* Effect.die("will-attach-webview listener was not registered"); + } + const webPreferences: Electron.WebPreferences = {}; + willAttachWebview({ preventDefault: () => {} }, webPreferences, { + partition: "persist:t3code-preview-test", + }); + + assert.deepEqual(webPreferences.additionalArguments, expected); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("opens safe off-origin renderer navigations in the system browser", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 73f5b41810..4628be44d5 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -14,6 +14,7 @@ import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/con import * as DesktopAssets from "../app/DesktopAssets.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import * as DesktopPrimaryPaste from "../app/DesktopPrimaryPaste.ts"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; @@ -29,7 +30,10 @@ import { TRACKPAD_SCROLL_END_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL, } from "../ipc/channels.ts"; -import { PASSKEY_BRIDGE_ARGUMENT } from "../preview/GuestProtocol.ts"; +import { + PASSKEY_BRIDGE_ARGUMENT, + PRIMARY_PASTE_DISABLED_ARGUMENT, +} from "../preview/GuestProtocol.ts"; import * as PreviewManager from "../preview/Manager.ts"; import * as PreviewPasskeys from "../preview/Passkeys.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; @@ -179,6 +183,58 @@ function windowFitsWithinDisplay( ); } +function overlapArea(left: DisplayBounds, right: DisplayBounds): number { + const width = Math.min(left.x + left.width, right.x + right.width) - Math.max(left.x, right.x); + const height = Math.min(left.y + left.height, right.y + right.height) - Math.max(left.y, right.y); + return width > 0 && height > 0 ? width * height : 0; +} + +function displayMatching( + bounds: DisplayBounds, + displays: readonly DisplayBounds[], +): DisplayBounds | undefined { + let match: DisplayBounds | undefined; + let matchArea = 0; + for (const display of displays) { + const area = overlapArea(bounds, display); + if (area > matchArea) { + match = display; + matchArea = area; + } + } + return match; +} + +// Normal bounds of a maximized window can sit on, or straddle into, another display than the window. +function normalBoundsOnWindowDisplay( + normalBounds: DisplayBounds, + windowBounds: DisplayBounds, + displays: readonly DisplayBounds[], +): DisplayBounds { + const target = displayMatching(windowBounds, displays); + if (target === undefined || windowFitsWithinDisplay(normalBounds, target)) { + return normalBounds; + } + const source = displayMatching(normalBounds, displays) ?? target; + const width = Math.min(normalBounds.width, target.width); + const height = Math.min(normalBounds.height, target.height); + const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max); + return { + x: clamp(target.x + normalBounds.x - source.x, target.x, target.x + target.width - width), + y: clamp(target.y + normalBounds.y - source.y, target.y, target.y + target.height - height), + width, + height, + }; +} + +function readDisplayBoundsOrEmpty(): readonly DisplayBounds[] { + try { + return Electron.screen.getAllDisplays().map((display) => display.bounds); + } catch { + return []; + } +} + function windowBoundsEqual( left: DesktopAppSettings.DesktopWindowBounds, right: DesktopAppSettings.DesktopWindowBounds, @@ -287,6 +343,7 @@ function getWindowTitleBarOptions( function syncWindowAppearance( window: Electron.BrowserWindow, + hasTitleBarOverlay: boolean, shouldUseDarkColors: boolean, platform: NodeJS.Platform, ): Effect.Effect { @@ -297,7 +354,7 @@ function syncWindowAppearance( window.setBackgroundColor(getInitialWindowBackgroundColor(shouldUseDarkColors)); const { titleBarOverlay } = getWindowTitleBarOptions(shouldUseDarkColors, platform); - if (typeof titleBarOverlay === "object") { + if (hasTitleBarOverlay && typeof titleBarOverlay === "object") { window.setTitleBarOverlay(titleBarOverlay); } }); @@ -331,6 +388,7 @@ export const make = Effect.gen(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; const previewManager = yield* PreviewManager.PreviewManager; const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys; + const primaryPaste = yield* DesktopPrimaryPaste.DesktopPrimaryPaste; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; const clientSettings = yield* DesktopClientSettings.DesktopClientSettings; const electronApp = yield* ElectronApp.ElectronApp; @@ -367,7 +425,6 @@ export const make = Effect.gen(function* () { ); const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash)); - const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash)); const zoomWindow = Effect.fn("desktop.window.zoomWindow")(function* ( window: Electron.BrowserWindow, @@ -453,33 +510,52 @@ export const make = Effect.gen(function* () { let boundsPersistFiber: Fiber.Fiber | undefined; let pendingBoundsPersistFiber: Fiber.Fiber | undefined; let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds; - const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => { + let lastPersistableState: { + readonly bounds: DesktopAppSettings.DesktopWindowBounds; + readonly isMaximized: boolean; + } | null = null; + const readPersistableState = () => { if (window.isDestroyed()) { return null; } + // Minimized windows report stale state on some platforms (macOS: not maximized, the + // pre-move normal frame; Windows: -32000), so they keep the state seen before minimizing. + if (window.isMinimized()) { + return lastPersistableState; + } + const isMaximized = window.isMaximized(); const bounds = - window.isFullScreen() || window.isMaximized() || window.isMinimized() - ? window.getNormalBounds() + window.isFullScreen() || isMaximized + ? normalBoundsOnWindowDisplay( + window.getNormalBounds(), + window.getBounds(), + readDisplayBoundsOrEmpty(), + ) : window.getBounds(); - return DesktopAppSettings.normalizeMainWindowBounds({ + const persistableBounds = DesktopAppSettings.normalizeMainWindowBounds({ x: Math.round(bounds.x), y: Math.round(bounds.y), width: Math.round(bounds.width), height: Math.round(bounds.height), }); + lastPersistableState = + persistableBounds === null ? null : { bounds: persistableBounds, isMaximized }; + return lastPersistableState; }; - const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds(); + const fallbackWindowBounds = boundsPersistenceEnabled + ? null + : (readPersistableState()?.bounds ?? null); const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { if (!boundsPersistenceEnabled) { return pendingBoundsPersistFiber; } - const bounds = readPersistableBounds(); - if (bounds === null) { + const state = readPersistableState(); + if (state === null) { return pendingBoundsPersistFiber; } pendingBoundsPersistFiber = runFork( - desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe( + desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe( Effect.asVoid, Effect.catch((error) => logWindowWarning("failed to persist main window bounds", { @@ -491,16 +567,15 @@ export const make = Effect.gen(function* () { return pendingBoundsPersistFiber; }; const scheduleBoundsPersist = () => { - if (!boundsPersistenceEnabled) { - const currentBounds = readPersistableBounds(); - if ( - currentBounds === null || + const state = readPersistableState(); + if ( + !boundsPersistenceEnabled && + (state === null || (fallbackWindowBounds !== null && - windowBoundsEqual(currentBounds, fallbackWindowBounds) && - window.isMaximized() === fallbackWindowMaximized) - ) { - return; - } + windowBoundsEqual(state.bounds, fallbackWindowBounds) && + state.isMaximized === fallbackWindowMaximized)) + ) { + return; } boundsPersistenceEnabled = true; if (boundsPersistFiber !== undefined) { @@ -561,6 +636,12 @@ export const make = Effect.gen(function* () { PASSKEY_BRIDGE_ARGUMENT, ]; } + if (!primaryPaste.enabled) { + webPreferences.additionalArguments = [ + ...(webPreferences.additionalArguments ?? []), + PRIMARY_PASTE_DISABLED_ARGUMENT, + ]; + } }); const contextMenuContents = new WeakSet(); @@ -734,7 +815,10 @@ export const make = Effect.gen(function* () { runFork(zoomWindow(window, direction)); }); - window.on("page-title-updated", (event) => { + // The renderer titles the window after the open thread; only a blank title + // falls back to the app name. + window.on("page-title-updated", (event, title) => { + if (title.trim() !== "") return; event.preventDefault(); window.setTitle(environment.displayName); }); @@ -817,7 +901,6 @@ export const make = Effect.gen(function* () { } clearDevelopmentLoadRetry(); developmentLoadRetryIndex = 0; - window.setTitle(environment.displayName); if (environment.platform === "darwin") syncMacosWindowButtons(window); }); window.webContents.on( @@ -859,20 +942,33 @@ export const make = Effect.gen(function* () { rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter( (timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS, ); - const shouldRecover = - recoverable && - !window.isDestroyed() && - rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS; + const shouldRecover = recoverable && !window.isDestroyed(); + // Past the budget, wait for the oldest attempt to leave the window instead of + // giving up, so a crash loop backs off but never leaves the window blank. + const oldestAttempt = + rendererRecoveryTimestamps.length >= RENDERER_RECOVERY_MAX_ATTEMPTS + ? rendererRecoveryTimestamps[ + rendererRecoveryTimestamps.length - RENDERER_RECOVERY_MAX_ATTEMPTS + ] + : undefined; + const reloadInMs = + oldestAttempt === undefined + ? RENDERER_RECOVERY_RELOAD_DELAY_MS + : Math.max( + RENDERER_RECOVERY_RELOAD_DELAY_MS, + oldestAttempt + RENDERER_RECOVERY_WINDOW_MS - now, + ); yield* logWindowWarning("main window render process gone", { reason: details.reason, exitCode: details.exitCode, recovering: shouldRecover, + ...(shouldRecover ? { reloadInMs } : {}), }); if (!shouldRecover) { return; } - rendererRecoveryTimestamps.push(now); - yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS); + rendererRecoveryTimestamps.push(now + reloadInMs); + yield* Effect.sleep(reloadInMs); if (!window.isDestroyed()) { loadApplication(); } @@ -935,7 +1031,7 @@ export const make = Effect.gen(function* () { const ensureMain = Effect.gen(function* () { if (yield* Ref.get(desktopState.quitting)) return Option.none(); - const existingWindow = yield* currentMainWindow; + const existingWindow = yield* electronWindow.main; if (Option.isSome(existingWindow)) { return existingWindow; } @@ -1022,7 +1118,8 @@ export const make = Effect.gen(function* () { { reveal = true }: { readonly reveal?: boolean } = {}, ) { if (yield* Ref.get(desktopState.quitting)) return; - const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main; + // Only the main renderer loads the app preload that listens on these channels. + const existingWindow = yield* electronWindow.main; if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return; const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain; if (Option.isNone(window) || window.value.isDestroyed()) return; @@ -1119,8 +1216,8 @@ export const make = Effect.gen(function* () { }), syncAppearance: Effect.gen(function* () { const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; - yield* electronWindow.syncAllAppearance((window) => - syncWindowAppearance(window, shouldUseDarkColors, environment.platform), + yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) => + syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform), ); }).pipe(Effect.withSpan("desktop.window.syncAppearance")), }); diff --git a/apps/desktop/src/wsl/DesktopWslBackend.test.ts b/apps/desktop/src/wsl/DesktopWslBackend.test.ts index 8468a95386..d9ae6e76c2 100644 --- a/apps/desktop/src/wsl/DesktopWslBackend.test.ts +++ b/apps/desktop/src/wsl/DesktopWslBackend.test.ts @@ -154,7 +154,7 @@ describe("DesktopWslBackend", () => { assert.equal(startCount, 1); assert.deepEqual(yield* backend.lastPreflightError, refusal); - yield* clearFailure(new URL("http://127.0.0.1:41773")); + yield* clearFailure(new URL("http://127.0.0.1:41773"), 123); assert.deepEqual(yield* backend.lastPreflightError, Option.none()); yield* recordOwnershipFailure(); const settings = yield* DesktopAppSettings.DesktopAppSettings; diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 69962f52e4..7f4a2507a7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -1,16 +1,25 @@ // @effect-diagnostics nodeBuiltinImport:off - the executed suite runs the generated install script through a real POSIX shell. +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Redacted from "effect/Redacted"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { afterAll, expect } from "vite-plus/test"; import * as NodeChildProcess from "node:child_process"; import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts"; import { + DesktopWslEnvironment, + layer as layerDesktopWslEnvironment, buildWslRuntimeInstallScript, makeIsAvailable, buildWslRuntimeInvalidateScript, @@ -18,6 +27,7 @@ import { buildWslRuntimeProbeScript, parseResolvedPath, parseWslRuntimeRoot, + windowsToWslPathImpl, } from "./DesktopWslEnvironment.ts"; // The install script only fails the way this file cares about when a real shell @@ -162,7 +172,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed " }", ' eval "$2"', "); }", - buildWslRuntimeProbeScript(fixture.runtimeRoot), + buildWslRuntimeProbeScript(), ].join("\n"), ); @@ -197,7 +207,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed [ "bash() { return 127; }", 'export PATH="/fixture/bin:/usr/bin:/bin"', - buildWslRuntimeProbeScript(fixture.runtimeRoot), + buildWslRuntimeProbeScript(), ].join("\n"), ); @@ -380,6 +390,93 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0); }); + // Runs the distro side on the local bash, so a Windows dev box using the wsl.exe runner skips it. + describe.skipIf(posixShellRunner?.file !== "bash")("prepareRuntime through wsl.exe", () => { + // Emulates `wsl.exe [-d ] [--cd ] [--|--exec] ` in a distro with automount off. + const layerFakeWslExe = (home: string) => + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.map(ChildProcessSpawner.ChildProcessSpawner, (local) => + ChildProcessSpawner.make((command) => { + if (!ChildProcess.isStandardCommand(command) || command.command !== "wsl.exe") { + return local.spawn(command); + } + const args = command.args.map((word) => + Redacted.isRedacted(word) ? Redacted.value(word) : word, + ); + while (args.length > 0) { + const flag = args[0]; + if (flag === "-d" || flag === "--distribution" || flag === "--cd") { + args.splice(0, 2); + } else if (flag === "--" || flag === "--exec" || flag === "-e") { + args.shift(); + break; + } else { + break; + } + } + const [file = "sh", ...rest] = + args[0] === "wslpath" + ? [ + "sh", + "-c", + 'printf "wslpath: %s\\n" "$1" >&2; exit 1', + "wslpath", + args.at(-1) ?? "", + ] + : args; + return local.spawn( + ChildProcess.make(file, rest, { + ...command.options, + env: { ...command.options.env, HOME: home }, + extendEnv: true, + }), + ); + }), + ), + ); + + const layerWslEnvironment = (home: string) => + layerDesktopWslEnvironment.pipe( + Layer.provide( + Layer.mergeAll( + layerFakeWslExe(home), + DesktopManagedPolicy.layerTest(), + Layer.effect( + DesktopEnvironment.DesktopEnvironment, + Effect.map( + Path.Path, + (path) => + ({ platform: "win32", path }) as DesktopEnvironment.DesktopEnvironment["Service"], + ), + ), + ), + ), + Layer.provide(NodeServices.layer), + ); + + it.live("installs the runtime when wslpath cannot translate the archive's Windows path", () => { + const fixture = createFixture(); + return Effect.gen(function* () { + const wsl = yield* DesktopWslEnvironment; + // The archive's Windows path; with no drives mounted, wslpath cannot map it into the distro. + const translated = yield* wsl.windowsToWslPath("Ubuntu", fixture.archivePath); + expect(translated._tag).toBe("None"); + + const prepared = yield* wsl.prepareRuntime("Ubuntu", { + windowsPath: fixture.archivePath, + runtimeId: fixture.runtimeId, + sha256: fixture.archiveSha, + }); + + expect(prepared).toEqual({ ok: true, linuxAppRoot: fixture.runtimeRoot }); + const version = runShell(`${sh(fixture.serverEntry)} --version`); + expect(version.status, version.stderr).toBe(0); + expect(version.stdout).toBe("t3code wsl runtime test server 0.0.0\n"); + }).pipe(Effect.provide(layerWslEnvironment(`${fixture.work}/home`))); + }); + }); + it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => { const result = runShell( [ @@ -459,3 +556,48 @@ describe("makeIsAvailable", () => { }), ); }); + +describe("windowsToWslPathImpl", () => { + it.effect("runs wslpath without a shell so folder names stay one literal argument", () => + Effect.gen(function* () { + const spawned: Array = []; + const stdout = Stream.make(new TextEncoder().encode("/mnt/c/a$b & c;(d)\n")); + const spawner = ChildProcessSpawner.make((command) => { + spawned.push(command); + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout, + stderr: Stream.empty, + all: stdout, + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ); + }); + + const converted = yield* windowsToWslPathImpl("Ubuntu", "C:\\a$b & c;(d)").pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + assert.deepStrictEqual(converted, Option.some("/mnt/c/a$b & c;(d)")); + assert.lengthOf(spawned, 1); + const [command] = spawned; + assert(command?._tag === "StandardCommand"); + assert.strictEqual(command.command, "wsl.exe"); + assert.deepStrictEqual(command.args, [ + "-d", + "Ubuntu", + "--exec", + "wslpath", + "-u", + "C:/a$b & c;(d)", + ]); + }), + ); +}); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index d8450ca833..a504acdc2b 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -5,6 +5,8 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import type * as PlatformError from "effect/PlatformError"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -109,10 +111,7 @@ export class DesktopWslEnvironment extends Context.Service< ) => Effect.Effect; readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect; readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly probeRuntime: ( - distro: string | null, - linuxAppRoot: string, - ) => Effect.Effect; + readonly probeRuntime: (distro: string | null) => Effect.Effect; readonly ensureNodePty: ( distro: string | null, linuxAppRoot: string, @@ -174,37 +173,19 @@ const buildWslNodeEnvPreamble = ( ensure_remote_node_path || true `; -// wsl.exe re-escaping mangles quotes inside bash -lc scripts. -const runWslShell = ( - distro: string | null, - bashScript: string, +const runWslProcess = ( + args: ReadonlyArray, + stdin: Stream.Stream, timeout: Duration.Duration, - options: { - readonly nodeEngineRange?: string | null; - readonly resolveNode?: boolean; - } = {}, ): Effect.Effect => { const spawner = ChildProcessSpawner.ChildProcessSpawner; - const resolveNode = options.resolveNode !== false; - const command = ChildProcess.make( - "wsl.exe", - resolveNode - ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"] - : [...buildDistroArgs(distro), "--exec", "sh", "-s"], - { - stdin: Stream.encodeText( - Stream.make( - resolveNode - ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}` - : bashScript, - ), - ), - stdout: "pipe", - stderr: "pipe", - killSignal: "SIGTERM", - forceKillAfter: PROCESS_TERMINATE_GRACE, - }, - ); + const command = ChildProcess.make("wsl.exe", args, { + stdin, + stdout: "pipe", + stderr: "pipe", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }); return Effect.scoped( Effect.gen(function* () { @@ -250,6 +231,32 @@ const runWslShell = ( ); }; +// wsl.exe re-escaping mangles quotes inside bash -lc scripts. +const runWslShell = ( + distro: string | null, + bashScript: string, + timeout: Duration.Duration, + options: { + readonly nodeEngineRange?: string | null; + readonly resolveNode?: boolean; + } = {}, +): Effect.Effect => { + const resolveNode = options.resolveNode !== false; + return runWslProcess( + resolveNode + ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"] + : [...buildDistroArgs(distro), "--exec", "sh", "-s"], + Stream.encodeText( + Stream.make( + resolveNode + ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}` + : bashScript, + ), + ), + timeout, + ); +}; + const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`; const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready"; @@ -258,13 +265,14 @@ const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5; const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_"); +// A null archive path asks for a staging directory to copy the archive into, unless the cache is ready. export const buildWslRuntimeInstallScript = ( - linuxArchivePath: string, + linuxArchivePath: string | null, runtimeId: string, archiveSha256: string, ): string => { const safeRuntimeId = sanitizeWslRuntimeId(runtimeId); - return [ + const readyCheck = [ "set -eu", 'runtime_parent="$HOME/.t3/wsl-runtime"', `runtime_root="$runtime_parent/${safeRuntimeId}"`, @@ -293,6 +301,17 @@ export const buildWslRuntimeInstallScript = ( ` printf 'runtimeRoot:%s\\n' "$runtime_root"`, " exit 0", "fi", + ]; + if (linuxArchivePath === null) { + return [ + ...readyCheck, + // The .tmp. name lets pruning collect a stage orphaned by a crash. + `archive_stage=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`, + `printf 'archiveStage:%s\\n' "$archive_stage"`, + ].join("\n"); + } + return [ + ...readyCheck, `archive_sha=$(sha256sum ${shellQuote(linuxArchivePath)} | cut -d ' ' -f 1)`, `if [ "$archive_sha" != ${shellQuote(archiveSha256)} ]; then`, ` printf 'WSL runtime archive does not match its recorded SHA-256 (expected %s, got %s)\\n' ${shellQuote(archiveSha256)} "$archive_sha" >&2`, @@ -410,14 +429,17 @@ export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => { ].join("\n"); }; -export const parseWslRuntimeRoot = (stdout: string): string | null => { - const prefix = "runtimeRoot:"; +const parseAbsolutePathField = (stdout: string, field: string): string | null => { + const prefix = `${field}:`; const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix)); if (line === undefined) return null; - const runtimeRoot = line.slice(prefix.length).replace(/\r$/, ""); - return runtimeRoot.startsWith("/") ? runtimeRoot : null; + const value = line.slice(prefix.length).replace(/\r$/, ""); + return value.startsWith("/") ? value : null; }; +export const parseWslRuntimeRoot = (stdout: string): string | null => + parseAbsolutePathField(stdout, "runtimeRoot"); + const NODE_PTY_BINARY_MISSING_EXIT_CODE = 4; const formatNodePtyProbeFailureReason = (exitCode: number): string | null => @@ -459,11 +481,9 @@ require("node-pty"); NODE`; // Resolve version-managed Node for providers without making runtime readiness depend on it. -export const buildWslRuntimeProbeScript = (linuxAppRoot: string) => - [ - `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`, - `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`, - ].join("\n"); +// The install script already ran the staged t3, so running it again here only adds a second startup. +export const buildWslRuntimeProbeScript = () => + `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`; const TOOLCHAIN_CHECK_SCRIPT = [ "for tool in node make g++ python3; do", @@ -577,30 +597,17 @@ const formatMissingToolsReason = ( const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* ( distro: string | null, - linuxAppRoot: string, ): Effect.fn.Return { - const probe = yield* runWslShell( - distro, - buildWslRuntimeProbeScript(linuxAppRoot), - PROBE_TIMEOUT, - { - resolveNode: false, - }, - ); + const probe = yield* runWslShell(distro, buildWslRuntimeProbeScript(), PROBE_TIMEOUT, { + resolveNode: false, + }); const transportFailureReason = formatWslShellTransportFailureReason( probe.transportFailure, - "the staged runtime", + "the login-shell PATH", ); if (transportFailureReason !== null) { return { ok: false, reason: transportFailureReason } as const; } - if (probe.exitCode !== 0) { - const trimmedTail = probe.stderr.trim().slice(-500); - return { - ok: false, - reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`, - } as const; - } const resolvedPath = parseResolvedPath(probe.stdout); if (resolvedPath === null) { return { @@ -776,25 +783,18 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f } as const; }); -const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* ( +type WslRuntimeInstallOutcome = + | { readonly ok: true; readonly stdout: string } + | { readonly ok: false; readonly reason: string }; + +const runWslRuntimeInstall = Effect.fn("desktop.wsl.runRuntimeInstall")(function* ( distro: string | null, archive: WslRuntimeArchive, - windowsToWslPath: ( - distro: string | null, - windowsPath: string, - ) => Effect.Effect>, -): Effect.fn.Return { - const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath); - if (Option.isNone(linuxArchivePath)) { - return { - ok: false, - reason: `wslpath conversion failed for ${archive.windowsPath}`, - } as const; - } - + linuxArchivePath: string | null, +): Effect.fn.Return { const install = yield* runWslShell( distro, - buildWslRuntimeInstallScript(linuxArchivePath.value, archive.runtimeId, archive.sha256), + buildWslRuntimeInstallScript(linuxArchivePath, archive.runtimeId, archive.sha256), RUNTIME_INSTALL_TIMEOUT, { resolveNode: false }, ); @@ -814,14 +814,106 @@ const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(functi reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`, } as const; } + return { ok: true, stdout: install.stdout } as const; +}); - const linuxAppRoot = parseWslRuntimeRoot(install.stdout); +const toPrepareWslRuntimeResult = (outcome: WslRuntimeInstallOutcome): PrepareWslRuntimeResult => { + if (!outcome.ok) return outcome; + const linuxAppRoot = parseWslRuntimeRoot(outcome.stdout); return linuxAppRoot === null ? { ok: false, reason: "WSL runtime installation completed without reporting its cache path.", } : { ok: true, linuxAppRoot }; +}; + +// Without drive mounts (`[automount] enabled=false`) wslpath cannot reach the archive, so copy it in over stdin. +const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromHostCopy")( + function* ( + distro: string | null, + archive: WslRuntimeArchive, + archiveBytes: Stream.Stream, + ): Effect.fn.Return { + const staged = yield* runWslRuntimeInstall(distro, archive, null); + if (!staged.ok || parseWslRuntimeRoot(staged.stdout) !== null) { + return toPrepareWslRuntimeResult(staged); + } + const stage = parseAbsolutePathField(staged.stdout, "archiveStage"); + if (stage === null) { + return { + ok: false, + reason: `wslpath conversion failed for ${archive.windowsPath}, and the distro did not provide a directory to copy the runtime archive into.`, + } as const; + } + const linuxArchivePath = `${stage}/runtime.tar.gz`; + + const copyAndInstall = Effect.gen(function* () { + const readError = yield* Ref.make(Option.none()); + // dd reads fd 0 itself; reopening /dev/stdin fails when WSL relays stdin as a socket. + const copy = yield* runWslProcess( + [...buildDistroArgs(distro), "--exec", "dd", `of=${linuxArchivePath}`, "bs=65536"], + archiveBytes.pipe( + // Ending stdin on a read error lets dd exit instead of waiting out the timeout. + Stream.catch((error) => + Stream.drain(Stream.fromEffect(Ref.set(readError, Option.some(error)))), + ), + ), + RUNTIME_INSTALL_TIMEOUT, + ); + const failedRead = yield* Ref.get(readError); + if (Option.isSome(failedRead)) { + return { + ok: false, + reason: `Could not read the WSL runtime archive at ${archive.windowsPath}: ${failedRead.value.message}`, + } as const; + } + if (copy.transportFailure !== null || copy.exitCode !== 0) { + const trimmedTail = copy.stderr.trim().slice(-500); + return { + ok: false, + reason: `Could not copy the WSL runtime archive into the distro (exit ${copy.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`, + } as const; + } + return toPrepareWslRuntimeResult( + yield* runWslRuntimeInstall(distro, archive, linuxArchivePath), + ); + }); + + return yield* copyAndInstall.pipe( + Effect.ensuring( + runWslShell(distro, `rm -rf ${shellQuote(stage)}`, RUNTIME_INVALIDATE_TIMEOUT, { + resolveNode: false, + }), + ), + ); + }, +); + +const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* ( + distro: string | null, + archive: WslRuntimeArchive, + windowsToWslPath: ( + distro: string | null, + windowsPath: string, + ) => Effect.Effect>, +): Effect.fn.Return< + PrepareWslRuntimeResult, + never, + ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem +> { + const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath); + if (Option.isNone(linuxArchivePath)) { + const fileSystem = yield* FileSystem.FileSystem; + return yield* installWslRuntimeFromHostCopy( + distro, + archive, + fileSystem.stream(archive.windowsPath), + ); + } + return toPrepareWslRuntimeResult( + yield* runWslRuntimeInstall(distro, archive, linuxArchivePath.value), + ); }); const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* ( @@ -926,7 +1018,7 @@ const preWarmImpl = ( }), ).pipe(Effect.timeoutOption(PRE_WARM_TIMEOUT), Effect.ignore); -const windowsToWslPathImpl = ( +export const windowsToWslPathImpl = ( distro: string | null, windowsPath: string, ): Effect.Effect, never, ChildProcessSpawner.ChildProcessSpawner> => { @@ -937,7 +1029,8 @@ const windowsToWslPathImpl = ( const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const command = ChildProcess.make( "wsl.exe", - [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized], + // --exec skips the distro shell, which would expand `$`, `&` or `;` in folder names. + [...buildDistroArgs(distro), "--exec", "wslpath", "-u", normalized], { stdin: "ignore", stdout: "pipe", @@ -1065,7 +1158,7 @@ export interface DesktopWslEnvironmentTestStub { ) => PrepareWslRuntimeResult; readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect; readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult; + readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult; readonly ensureNodePty?: ( distro: string | null, linuxAppRoot: string, @@ -1112,16 +1205,14 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => { return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void; }, ), - probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")( - function (distro, linuxAppRoot) { - return Effect.succeed( - stub.probeRuntime?.(distro, linuxAppRoot) ?? { - ok: true, - resolvedPath: "/usr/bin:/bin", - }, - ); - }, - ), + probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(function (distro) { + return Effect.succeed( + stub.probeRuntime?.(distro) ?? { + ok: true, + resolvedPath: "/usr/bin:/bin", + }, + ); + }), ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")( function (distro, linuxAppRoot, options) { return Effect.succeed( @@ -1199,7 +1290,11 @@ export const layer = Layer.effect( getUserHome, getDistroIp, prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) { - return provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath)); + return provideSpawner( + prepareWslRuntimeImpl(distro, archive, windowsToWslPath).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + ), + ); }), pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) { return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)); @@ -1207,8 +1302,8 @@ export const layer = Layer.effect( invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) { return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)); }), - probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) { - return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot)); + probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) { + return provideSpawner(probeWslRuntimeImpl(distro)); }), ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")( function (distro, linuxAppRoot, options) { diff --git a/apps/desktop/src/wsl/DesktopWslServerTree.test.ts b/apps/desktop/src/wsl/DesktopWslServerTree.test.ts index 7eaf362a32..34dcbea08a 100644 --- a/apps/desktop/src/wsl/DesktopWslServerTree.test.ts +++ b/apps/desktop/src/wsl/DesktopWslServerTree.test.ts @@ -6,7 +6,6 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; -import * as Scope from "effect/Scope"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; @@ -42,20 +41,14 @@ const layerEnvironment = (input: { ), ); -const withTempDir = ( - run: (tempDir: string) => Effect.Effect, -): Effect.Effect< - A, - E | PlatformError.PlatformError, - FileSystem.FileSystem | Exclude -> => +const withTempDir = (run: (tempDir: string) => Effect.Effect) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-wsl-server-tree-test-", }); return yield* run(tempDir); - }).pipe(Effect.scoped); + }); const ensureWith = (input: { readonly baseDir: string; diff --git a/apps/desktop/src/wsl/wslPathParsing.test.ts b/apps/desktop/src/wsl/wslPathParsing.test.ts index 0a81422966..ed491f5838 100644 --- a/apps/desktop/src/wsl/wslPathParsing.test.ts +++ b/apps/desktop/src/wsl/wslPathParsing.test.ts @@ -77,8 +77,15 @@ describe("wslUncPathToLinuxPath", () => { expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Debian\\")).toBe("/"); }); + it("maps UNC paths of distros whose names start or end with a dot or hyphen", () => { + for (const name of ["Ubuntu-", "Ubuntu.", ".Ubuntu", "-Ubuntu"]) { + expect(wslUncPathToLinuxPath(`\\\\wsl.localhost\\${name}\\home\\josh`)).toBe("/home/josh"); + } + }); + it("rejects invalid distro names and non-WSL paths", () => { expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull(); + expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\..\\home")).toBeNull(); expect(wslUncPathToLinuxPath("C:\\Users\\Josh\\repo")).toBeNull(); }); }); @@ -107,9 +114,13 @@ describe("resolveWslPickFolderDefaultPath", () => { }); describe("isValidDistroName", () => { - it("rejects names with trailing whitespace, hyphen, or dot", () => { - for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) { - expect(isValidDistroName(name)).toBe(false); + it("rejects names with trailing whitespace", () => { + expect(isValidDistroName("Ubuntu ")).toBe(false); + }); + + it("accepts names WSL registers with a leading or trailing dot or hyphen", () => { + for (const name of ["Ubuntu-", "Ubuntu.", ".Ubuntu", "-Ubuntu"]) { + expect(isValidDistroName(name)).toBe(true); } }); diff --git a/apps/desktop/src/wsl/wslPathParsing.ts b/apps/desktop/src/wsl/wslPathParsing.ts index a1ce99c129..1df64f91da 100644 --- a/apps/desktop/src/wsl/wslPathParsing.ts +++ b/apps/desktop/src/wsl/wslPathParsing.ts @@ -9,7 +9,8 @@ export interface WslConfig { } // Literal spaces only; \s would accept controls and corrupt UNC distro paths. -const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/; +// "." and ".." would be path segments in a UNC path, not distro names. +const DISTRO_NAME_PATTERN = /^(?!\.{1,2}$)[\w.-](?:[\w .-]*[\w.-])?$/; export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] { const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe; diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 8068309400..4cb78d2ea1 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -1,12 +1,23 @@ import "vite-plus/test/config"; +import * as NodeOS from "node:os"; + import { defaultInclude, defineConfig } from "vite-plus"; import { isDesktopRuntimeExternalDependency } from "../../scripts/lib/desktop-external-packages.ts"; +const domTests = ["src/preview/PickPreload.test.ts"]; + // Install only bundle externals; the server bundle already carries its dependency tree. const isMainProcessExternal = (id: string) => id === "electron" || id.startsWith("electron/") || isDesktopRuntimeExternalDependency(id); const shouldLaunchElectronAfterPack = process.env.T3CODE_DESKTOP_DEV === "1"; +// tsdown runs onSuccess through a shell. dash forks instead of exec'ing the last command, which +// would leave an `sh` between `vp pack` and the supervisor and hide `vp pack` dying from it. +const devElectronCommand = + // oxlint-disable-next-line t3code/no-global-process-runtime -- Build config has no Effect runtime. + NodeOS.platform() === "win32" + ? "node scripts/dev-electron.mjs" + : "exec node scripts/dev-electron.mjs"; const buildDefine = { __FINCKE_DESKTOP__: "true", }; @@ -65,7 +76,7 @@ export default defineConfig({ neverBundle: isMainProcessExternal, onlyBundle: false, }, - ...(shouldLaunchElectronAfterPack ? { onSuccess: "node scripts/dev-electron.mjs" } : {}), + ...(shouldLaunchElectronAfterPack ? { onSuccess: devElectronCommand } : {}), }, { format: "cjs", @@ -142,13 +153,35 @@ export default defineConfig({ }, ], test: { - include: [...defaultInclude, "../../native/kde-snap-shot/src/*.test.ts"], // The Windows lane runs workspace suites concurrently; filesystem-heavy // desktop integration tests can exceed Vitest's 5 second default there. testTimeout: 15_000, - setupFiles: [ - "../../packages/shared/src/testing/longTempDir.ts", - "../../packages/shared/src/testing/providerEnv.ts", + // `require("electron")` downloads a missing binary, so concurrent workers race to + // extract it into the same dist/. Install it once before any worker starts. + globalSetup: ["./scripts/ensure-electron-runtime.mjs"], + projects: [ + { + extends: true, + test: { + name: "unit", + include: [...defaultInclude, "../../native/kde-snap-shot/src/*.test.ts"], + exclude: ["**/node_modules/**", ...domTests], + setupFiles: [ + "../../packages/shared/src/testing/longTempDir.ts", + "../../packages/shared/src/testing/providerEnv.ts", + ], + }, + }, + { + extends: true, + test: { + name: "dom", + include: domTests, + // Guest preloads run in the page; these tests drive them against a DOM. + environment: "jsdom", + setupFiles: ["../../packages/shared/src/testing/providerEnv.ts"], + }, + }, ], }, }); diff --git a/apps/mobile/deps/README.md b/apps/mobile/deps/README.md index 2abb1858b3..4a42287173 100644 --- a/apps/mobile/deps/README.md +++ b/apps/mobile/deps/README.md @@ -1,4 +1,4 @@ -The Enriched Markdown tarball comes from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`) and the iOS streaming memory bounds are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), iOS Copy as Markdown keeping bold spans whole ([#1143](https://github.com/software-mansion/enriched-markdown/pull/1143)), line breaks in copied table cells written as `
` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)). +The Enriched Markdown tarball comes from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`) and the iOS streaming memory bounds are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), iOS Copy as Markdown keeping bold spans whole ([#1143](https://github.com/software-mansion/enriched-markdown/pull/1143)), line breaks in copied table cells written as `
` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)). It also carries two fork-only changes: iOS code blocks too big for one backing store draw through tiles, so a tall block with long lines no longer shows an empty pane ([pingdotgg/enriched-markdown#15](https://github.com/pingdotgg/enriched-markdown/pull/15)), and a long-pressed iOS blockquote lifts on the background it sits on instead of drawing its text over the thread. To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Keep the package version aligned with Julius's `fork/t3-mobile` branch. Rename the archive to include the first eight characters of the source commit, such as `react-native-enriched-markdown-1.2.0-t3.18-4287c5d3.tgz`, so each build has a distinct dependency path without version bumps. Update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes. diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz new file mode 100644 index 0000000000..10495faf6f Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz differ diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-497fbe63.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-497fbe63.tgz deleted file mode 100644 index 2dbfd6d796..0000000000 Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-497fbe63.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.48.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.48.tgz deleted file mode 100644 index f1eb3858e9..0000000000 Binary files a/apps/mobile/deps/react-native-screens-5.0.0-t3.48.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz new file mode 100644 index 0000000000..06f9fc0fa9 Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz differ diff --git a/apps/mobile/gt.config.json b/apps/mobile/gt.config.json new file mode 100644 index 0000000000..707f56d736 --- /dev/null +++ b/apps/mobile/gt.config.json @@ -0,0 +1,9 @@ +{ + "defaultLocale": "en", + "locales": ["es", "zh", "pt-BR", "fr", "de", "ja", "ko", "ru"], + "files": { + "gt": { + "output": "src/i18n/translations/[locale].json" + } + } +} diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index da2508d5f2..d0ffaaef48 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -3,8 +3,9 @@ import ExpoModulesCore import UIKit +import UniformTypeIdentifiers -private struct ComposerTokenPayload: Decodable { +private struct ComposerTokenPayload: Decodable, Equatable { let type: String let source: String let label: String @@ -12,8 +13,16 @@ private struct ComposerTokenPayload: Decodable { let accent: String? let tintsIcon: Bool? let detail: String? - let start: Int - let end: Int + var start: Int + var end: Int + + func rendersLike(_ other: Self) -> Bool { + var moved = other + moved.start = start + moved.end = end + // String == accepts canonically equivalent sources, but their UTF-16 lengths differ. + return moved == self && source.utf16.elementsEqual(other.source.utf16) + } } private struct ComposerSelectionPayload: Decodable, Equatable { @@ -42,12 +51,12 @@ private enum ComposerEnterBehavior: String { } private final class ComposerTextAttachment: NSTextAttachment { - let source: String - let label: String + let token: ComposerTokenPayload + var source: String { token.source } + var label: String { token.label } - init(source: String, label: String, image: UIImage, size: CGSize, baselineOffset: CGFloat) { - self.source = source - self.label = label + init(token: ComposerTokenPayload, image: UIImage, size: CGSize, baselineOffset: CGFloat) { + self.token = token super.init(data: nil, ofType: nil) self.image = image bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height) @@ -84,7 +93,6 @@ private final class ComposerTextView: UITextView { var onPasteContext: (([String: String]) -> Void)? var onPasteText: ((String, NSRange) -> Void)? var clipboardFragment = "" - var onAttributedMutation: (() -> Void)? var onSubmit: ((Bool) -> Void)? var isReadOnly = false var textPasteThresholdBytes = 0 @@ -246,8 +254,9 @@ private final class ComposerTextView: UITextView { return } } + // pasteboard.string is only the first item; super.paste inserts every text item. if !bypassTextPasteInterception, - let text = pasteboard.string, shouldInterceptTextPaste(text) { + let text = pasteboard.strings?.joined(), shouldInterceptTextPaste(text) { onPasteText?(text, selectedRange) return } @@ -305,18 +314,28 @@ private final class ComposerTextView: UITextView { func loadImages(from providers: [NSItemProvider]) { let group = DispatchGroup() let lock = NSLock() - var images = [UIImage?](repeating: nil, count: providers.count) + var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count) for (index, provider) in providers.enumerated() { group.enter() - provider.loadObject(ofClass: UIImage.self) { object, _ in - defer { group.leave() } - guard let image = object as? UIImage else { - return - } + let store = { (image: (data: Data, fileExtension: String)?) in lock.lock() images[index] = image lock.unlock() + group.leave() + } + let loadPNG = { + _ = provider.loadObject(ofClass: UIImage.self) { object, _ in + store((object as? UIImage)?.pngData().map { ($0, "png") }) + } + } + // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through. + if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) { + _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in + if let data { store((data, "gif")) } else { loadPNG() } + } + } else { + loadPNG() } } @@ -324,7 +343,9 @@ private final class ComposerTextView: UITextView { guard let self, !self.isReadOnly else { return } - let urls = images.compactMap { $0 }.compactMap(Self.writeTemporaryImage) + let urls = images.compactMap { $0 }.compactMap { + Self.writeTemporaryImage($0.data, fileExtension: $0.fileExtension) + } if !urls.isEmpty { self.onPasteImages?(urls) } @@ -346,9 +367,7 @@ private final class ComposerTextView: UITextView { return super.cut(sender) } copy(sender) - textStorage.replaceCharacters(in: selectedRange, with: "") - selectedRange = NSRange(location: selectedRange.location, length: 0) - onAttributedMutation?() + replaceDisplayRange(selectedRange) } func serializedText() -> String { @@ -404,9 +423,10 @@ private final class ComposerTextView: UITextView { } private static func writeTemporaryImage(_ image: UIImage) -> String? { - guard let data = image.pngData() else { - return nil - } + image.pngData().flatMap { writeTemporaryImage($0, fileExtension: "png") } + } + + private static func writeTemporaryImage(_ data: Data, fileExtension: String) -> String? { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(pastedImageDirectoryName, isDirectory: true) do { @@ -415,7 +435,7 @@ private final class ComposerTextView: UITextView { withIntermediateDirectories: true ) removeStaleTemporaryImages(in: directory) - let url = directory.appendingPathComponent("\(UUID().uuidString).png") + let url = directory.appendingPathComponent("\(UUID().uuidString).\(fileExtension)") try data.write(to: url, options: .atomic) return url.absoluteString } catch { @@ -547,9 +567,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro "selection": ["start": selection.start, "end": selection.end], ]) } - textView.onAttributedMutation = { [weak self] in - self?.emitTextChange() - } textView.onSubmit = { [weak self] alternate in self?.onComposerSubmit(["alternate": alternate]) } @@ -719,8 +736,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro hasControlledDocument = true if tokensJson != document.tokensJson { tokensJson = document.tokensJson - tokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? [] - tokensNeedRebuild = true + let nextTokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? [] + // Rebuild only when a chip on screen would look different: typing before a chip moves its + // offsets, and Undo restores the chip it removed. A rebuild there makes iOS autocorrect + // behind the caret, and replacing the text drops UIKit's Redo. + tokensNeedRebuild = tokensNeedRebuild || !nextTokens.elementsEqual(renderedChipTokens(), by: { $0.rendersLike($1) }) + tokens = nextTokens } let previousSelection = sourceSelection() value = document.value @@ -744,6 +765,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro func setPlaceholder(_ placeholder: String) { placeholderLabel.text = placeholder + textView.accessibilityLabel = placeholder setNeedsLayout() } @@ -1032,8 +1054,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro font: chipFont ) let attachment = ComposerTextAttachment( - source: token.source, - label: token.label, + token: token, image: image, size: image.size, baselineOffset: chipFont.ascender - image.size.height @@ -1333,9 +1354,22 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro } } + private func renderedChipTokens() -> [ComposerTokenPayload] { + var rendered: [ComposerTokenPayload] = [] + textView.textStorage.enumerateAttribute( + .attachment, + in: NSRange(location: 0, length: textView.textStorage.length) + ) { value, _, _ in + if let attachment = value as? ComposerTextAttachment { + rendered.append(attachment.token) + } + } + return rendered + } + private func documentMatchesExpectedTokens() -> Bool { let source = value as NSString - let expectedSources = tokens.compactMap { token -> String? in + let expectedChips = tokens.compactMap { token -> (Int, String)? in guard token.start >= 0, token.end > token.start, token.end <= source.length, @@ -1344,18 +1378,22 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro ) == token.source else { return nil } - return token.source + return (token.start, token.source) } - var renderedSources: [String] = [] + var renderedChips: [(Int, String)] = [] + var sourceOffset = 0 textView.attributedText.enumerateAttribute( .attachment, in: NSRange(location: 0, length: textView.attributedText.length) - ) { value, _, _ in + ) { value, range, _ in if let attachment = value as? ComposerTextAttachment { - renderedSources.append(attachment.source) + renderedChips.append((sourceOffset, attachment.source)) + sourceOffset += (attachment.source as NSString).length + } else { + sourceOffset += range.length } } - return renderedSources == expectedSources + return renderedChips.elementsEqual(expectedChips, by: ==) } } diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift index 4435b10221..6b69f29d30 100644 --- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift +++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift @@ -11,13 +11,16 @@ func check(_ passed: Bool, _ message: String) { extension T3ComposerEditorView { var editor: UITextView { textView } var text: String { textView.serializedText() } + func chip(at location: Int) -> NSTextAttachment? { + textView.textStorage.attribute(.attachment, at: location, effectiveRange: nil) as? NSTextAttachment + } } -func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false) -> String { +func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false, tokensJson: String = "[]") -> String { let payload: [String: Any] = [ "value": value, "selection": NSNull(), - "tokensJson": "[]", + "tokensJson": tokensJson, "mostRecentEventCount": revision, "isNativeEcho": isNativeEcho, "resetGeneration": resetGeneration, @@ -33,10 +36,14 @@ func replace(_ view: T3ComposerEditorView, _ target: String, with replacement: S editor.replace(editor.textRange(from: start, to: end)!, withText: replacement) } -func makeEditor(_ value: String) -> T3ComposerEditorView { +func mention(_ label: String, at start: Int, source: String = "@README.md") -> String { + #"[{"type":"mention","source":"\#(source)","label":"\#(label)","start":\#(start),"end":\#(start + source.utf16.count)}]"# +} + +func makeEditor(_ value: String, tokensJson: String = "[]") -> T3ComposerEditorView { let view = T3ComposerEditorView() view.frame = CGRect(x: 0, y: 0, width: 320, height: 200) - view.setControlledDocumentJson(document(value, revision: 0)) + view.setControlledDocumentJson(document(value, revision: 0, tokensJson: tokensJson)) check(view.text == value, "Initial controlled value was not applied") return view } @@ -108,6 +115,62 @@ do { ) } +// An echo that only shifts a chip keeps the rendered text; moving or relabeling the chip redraws it. +do { + let draft = "hi! @README.md @README.md" + let view = makeEditor("hi @README.md @README.md", tokensJson: mention("README.md", at: 3)) + let rendered = view.chip(at: 3) + check(rendered != nil, "Harness could not render the chip") + view.editor.selectedRange = NSRange(location: 2, length: 0) + view.editor.insertText("!") + let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0 + view.setControlledDocumentJson(document(draft, revision: revision, isNativeEcho: true, tokensJson: mention("README.md", at: 4))) + check(view.chip(at: 4) === rendered, "An echo that only moved a chip replaced the text") + view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 4))) + check((view.chip(at: 4) as? ComposerTextAttachment)?.label == "Readme", "A relabeled chip was not redrawn") + view.setControlledDocumentJson(document(draft, revision: revision, tokensJson: mention("Readme", at: 15))) + check(view.chip(at: 4) == nil && view.chip(at: 15) != nil, "A chip moved to another copy of its source stayed on the old one") +} + +// A chip source that changes only in Unicode normalization is rebuilt from the new text. +do { + let view = makeEditor("@\u{00E9}", tokensJson: mention("e", at: 0, source: "@\u{00E9}")) + view.setControlledDocumentJson(document("@e\u{0301}", revision: 0, tokensJson: mention("e", at: 0, source: "@e\u{0301}"))) + check(view.text.utf16.elementsEqual("@e\u{0301}".utf16), "A renormalized chip source kept the old text") +} + +// The placeholder label is hidden from VoiceOver, so the text view must carry it. +do { + let view = makeEditor("") + view.setPlaceholder("Ask anything") + check(view.editor.accessibilityLabel == "Ask anything", "VoiceOver label: \(String(describing: view.editor.accessibilityLabel))") +} + +// Cutting a chip is undoable: Undo restores the chip and tells the parent, Redo removes it again. +// The parent echoes each edit with its re-derived chips; those echoes must not rebuild the text. +do { + let view = makeEditor("hi @README.md ok", tokensJson: mention("README.md", at: 3)) + func echo() { + let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0 + let chips = view.text.contains("@README.md") ? mention("README.md", at: 3) : "[]" + view.setControlledDocumentJson(document(view.text, revision: revision, isNativeEcho: true, tokensJson: chips)) + } + view.editor.selectedRange = NSRange(location: 3, length: 2) + view.editor.cut(nil) + check(view.text == "hi ok", "Cut left the selection behind: \(view.text)") + check(view.onComposerChange.payloads.last?["value"] as? String == "hi ok", "Cut did not emit the new value") + echo() + view.editor.undoManager?.undo() + check(view.text == "hi @README.md ok", "Undo did not restore the cut text: \(view.text)") + let restored = view.chip(at: 3) + check(restored is ComposerTextAttachment, "Undo did not restore the cut chip") + check(view.onComposerChange.payloads.last?["value"] as? String == "hi @README.md ok", "Undo did not emit the restored value") + echo() + check(view.chip(at: 3) === restored, "The parent's echo of the restored chip rebuilt the text and dropped Redo") + view.editor.undoManager?.redo() + check(view.text == "hi ok", "Redo did not cut again: \(view.text)") +} + print("composer editor tests passed") private let dropEditor = ComposerTextView() @@ -174,6 +237,40 @@ for readOnly in [true, false] { check(provider.loadCount == 0, "Locked inputs must not load pasted image providers") } +func interceptedPaste(_ items: [String]) -> String? { + let savedItems = UIPasteboard.general.items + defer { UIPasteboard.general.items = savedItems } + let editor = ComposerTextView() + editor.textPasteThresholdBytes = 32 * 1024 + var intercepted: String? + editor.onPasteText = { text, _ in intercepted = text } + UIPasteboard.general.items = items.map { [UTType.utf8PlainText.identifier: $0] } + editor.paste(nil) + return intercepted +} +let halfA = String(repeating: "A", count: 20_000) +let halfB = String(repeating: "B", count: 20_000) +check(interceptedPaste([halfA, halfB]) == halfA + halfB, "Text items that together reach the threshold must fold") + +// Two-frame animated GIF: a mixed paste keeps the GIF's original bytes and the still image's PNG, in order. +private let gifBytes = Data(base64Encoded: "R0lGODlhAQABAIEAAP8AAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAAIBAABBAQAIfkEAAoAAAAsAAAAAAEAAQCBAP8AAAAAAAAAAAAACAQAAQQEADs=")! +private let gifProvider = NSItemProvider() +gifProvider.registerDataRepresentation(forTypeIdentifier: UTType.gif.identifier, visibility: .all) { completion in + completion(gifBytes, nil) + return nil +} +private let gifEditor = ComposerTextView() +gifEditor.onPasteImages = { urls in + let files = urls.compactMap(URL.init(string:)) + let contents = files.compactMap { try? Data(contentsOf: $0) } + files.forEach { try? FileManager.default.removeItem(at: $0) } + check(files.map(\.pathExtension) == ["gif", "png"], "A mixed paste must keep each image's format, in order: \(urls)") + check(contents.first == gifBytes, "A pasted animated GIF must keep its original bytes") + check(contents.count == 2 && contents[1] == image.pngData(), "The still image beside a GIF must still attach as PNG") + print("Composer GIF-paste checks passed") + exit(0) +} + // Inline provider completion places the attachment callback before this main-queue check. DispatchQueue.main.async { check(pastedImages.count == 1, "An accepted provider-based paste must emit exactly one attachment batch") @@ -190,6 +287,7 @@ DispatchQueue.main.async { "The attachment must contain the pasted image's pixels") check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text") print("Composer provider-paste checks passed") - exit(0) + check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") + gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) } dispatchMain() diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift index e1377442f1..8cab6676b6 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -10,6 +10,10 @@ public final class T3NativeControlsModule: Module { private let presentationSources = T3PresentationSources() private var videoPresentation: T3NativeVideoPresentation? private var filePresentation: T3NativeFilePresentation? + private var imageViewer: T3NativeImageViewer? + /// The last file preview that closed. Written on main, read synchronously from JS. + private let filePreviewActivity = NSLock() + private var finishedFilePreview: String? public func definition() -> ModuleDefinition { Events("videoPlaybackChange") @@ -75,26 +79,42 @@ public final class T3NativeControlsModule: Module { else { throw URLError(.badURL) } - let file = try self.makeFilePresentation(sourceIdentifiers: sourceIdentifiers, identifier: identifier, - promise: promise) - guard let presenter = self.appContext?.utilities?.currentViewController() else { - file.dismiss() - return - } - file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter) + // A viewer still animating closed must not block the next one, as Quick Look's error alert did. + self.imageViewer?.finishImmediately() + guard self.filePresentation == nil, self.videoPresentation == nil, + let presenter = self.appContext?.utilities?.currentViewController() + else { throw URLError(.cannotLoadFromNetwork) } + let viewer = T3NativeImageViewer( + identifier: identifier, sources: self.presentationSources, sourceIdentifiers: sourceIdentifiers, + onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) }, + completion: { [weak self] error in + if self?.imageViewer?.identifier == identifier { self?.imageViewer = nil } + if let error { promise.reject(error) } else { promise.resolve(nil) } + } + ) + self.imageViewer = viewer + viewer.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter) }.runOnQueue(.main) + // A tap can reach JS before the old viewer's close does; this tells it whether that viewer is gone. + // A presentation main has not started yet reads as still open. + Function("isFilePreviewFinished") { (identifier: String) -> Bool in + self.filePreviewActivity.withLock { self.finishedFilePreview == identifier } + } + // A nil URL marks the item as one that could not be resolved. AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in - if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) } + if self.imageViewer?.identifier == identifier { self.imageViewer?.update(index: index, url: url) } }.runOnQueue(.main) OnDestroy { let presentation = self.videoPresentation let file = self.filePresentation + let images = self.imageViewer DispatchQueue.main.async { presentation?.dismiss() file?.dismiss() + images?.dismiss() } } @@ -251,7 +271,7 @@ public final class T3NativeControlsModule: Module { let isPlayableURL = url.isFileURL ? FileManager.default.isReadableFile(atPath: url.path) : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil) - guard videoPresentation == nil, filePresentation == nil, + guard videoPresentation == nil, filePresentation == nil, imageViewer == nil, let presenter = appContext?.utilities?.currentViewController(), isPlayableURL else { @@ -279,29 +299,37 @@ public final class T3NativeControlsModule: Module { if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() } } - private func makeFilePresentation(sourceIdentifiers: [String], identifier: String, + private func makeFilePresentation(sourceIdentifier: String, identifier: String, promise: Promise) throws -> T3NativeFilePresentation { - guard filePresentation == nil, videoPresentation == nil, + guard filePresentation == nil, videoPresentation == nil, imageViewer == nil, appContext?.utilities?.currentViewController() != nil else { throw URLError(.cannotLoadFromNetwork) } - let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources, - sourceIdentifiers: sourceIdentifiers) { [weak self] error in - self?.filePresentation = nil - if let error { promise.reject(error) } else { promise.resolve(nil) } - } + let file = T3NativeFilePresentation( + identifier: identifier, sources: presentationSources, sourceIdentifier: sourceIdentifier, + onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) }, + completion: { [weak self] error in + self?.filePresentation = nil + if let error { promise.reject(error) } else { promise.resolve(nil) } + } + ) filePresentation = file return file } + private func setFinishedFilePreview(_ identifier: String) { + filePreviewActivity.withLock { finishedFilePreview = identifier } + } + private func presentFile(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws { - let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise) + let file = try makeFilePresentation(sourceIdentifier: sourceIdentifier, identifier: identifier, promise: promise) guard let presenter = appContext?.utilities?.currentViewController() else { file.dismiss(); return } file.present(url: url, title: title, from: presenter) } private func dismissFilePresentation(identifier: String) { if filePresentation?.identifier == identifier { filePresentation?.dismiss() } + if imageViewer?.identifier == identifier { imageViewer?.dismiss() } } private static func saveImageToLibrary(url: URL, mimeType: String, name: String, promise: Promise) { diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift index 791e39b284..a939fc473f 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift @@ -8,232 +8,149 @@ private final class FilePreviewItem: NSObject, QLPreviewItem { var previewItemTitle: String? } -private enum FilePreviewState { case loading, ready, failed } - private final class FilePreviewController: QLPreviewController { var onAppear: (() -> Void)? - // Quick Look shows a blank page for an item without a file, so loading and failure are ours to show. - private let spinner = UIActivityIndicatorView(style: .large) - private let failure = UILabel() - var state = FilePreviewState.ready { - didSet { if isViewLoaded { showState() } } - } - - override func viewDidLoad() { - super.viewDidLoad() - failure.text = "This image could not be loaded." - failure.textColor = .secondaryLabel - failure.textAlignment = .center - failure.numberOfLines = 0 - for status in [spinner, failure] as [UIView] { - status.isUserInteractionEnabled = false - status.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(status) - NSLayoutConstraint.activate([ - status.centerXAnchor.constraint(equalTo: view.centerXAnchor), - status.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 64), - status.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -48), - ]) - } - showState() - } - - override func viewDidLayoutSubviews() { - super.viewDidLayoutSubviews() - view.bringSubviewToFront(spinner) - view.bringSubviewToFront(failure) - } + var onDismiss: (() -> Void)? override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) onAppear?() } - private func showState() { - if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() } - failure.isHidden = state != .failed + // Quick Look's own didDismiss callback can lag well behind the screen being tappable again, + // so a tap on the thumbnail in that gap would land while JS still thinks the viewer is open. + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + if isBeingDismissed { onDismiss?() } } } +/// A load faster than this zooms straight from the thumbnail without a spinner. +private let spinnerDelayNanoseconds: UInt64 = 250_000_000 + +/// Quick Look for PDFs and documents; images open in T3NativeImageViewer. final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate { let identifier: String private var controller: FilePreviewController? private let completion: (Error?) -> Void + private let onFinish: () -> Void private weak var sources: T3PresentationSources? - private let sourceIdentifiers: [String] - private var items: [FilePreviewItem] = [] - private var urls: [URL?] = [] - private var states: [FilePreviewState] = [] - private var selectedIndex = 0 - private weak var presenter: UIViewController? - /// Files that arrived while their page was off screen; Quick Look may still hold the blank page. - private var staleIndices = Set() - private var currentIndexObservation: NSKeyValueObservation? - private var download: (index: Int, task: Task)? - private var placeholder: Task? + private let sourceIdentifier: String + private var file: URL? + private var item: FilePreviewItem? + private var download: Task? + private var spinnerDelay: Task? + private var spinner: UIView? private var openError: Error? private var dismissRequested = false private var finished = false - init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String], - completion: @escaping (Error?) -> Void) { + init(identifier: String, sources: T3PresentationSources, sourceIdentifier: String, + onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) { self.identifier = identifier self.sources = sources - self.sourceIdentifiers = sourceIdentifiers + self.sourceIdentifier = sourceIdentifier + self.onFinish = onFinish self.completion = completion super.init() } /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead. func present(url: URL, title: String, from presenter: UIViewController) { - load(urls: [url], titles: [title], selectedIndex: 0, from: presenter, opensWhileLoading: false) - } - - /// Opens the selected image once it is ready, or a loading page if it is slow, and loads the rest - /// of the gallery behind it so a slow or broken sibling never holds the viewer back. - func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) { - load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true) - } - - /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will. - func update(index: Int, url: URL?) { - guard !finished, urls.indices.contains(index), urls[index] == nil, states[index] == .loading else { return } - guard let url else { - failed(index, error: URLError(.resourceUnavailable)) - return - } - urls[index] = url - loadNext() - } - - private func load(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController, - opensWhileLoading: Bool) { - items = titles.map { title in - let item = FilePreviewItem() - item.previewItemTitle = title - return item - } - self.urls = urls - self.selectedIndex = selectedIndex - self.presenter = presenter - states = Array(repeating: .loading, count: urls.count) - if opensWhileLoading { - // A short grace keeps the zoom from the thumbnail into a loaded image when the file is quick. - placeholder = Task { @MainActor [self] in - try? await Task.sleep(nanoseconds: 250_000_000) - guard !Task.isCancelled, !finished, controller == nil else { return } - show() - } + spinnerDelay = Task { @MainActor [self] in + try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds) + guard !Task.isCancelled else { return } + showSpinner() } - loadNext() - } - - /// Downloads one file at a time, nearest the page on screen first. The page on screen takes over - /// from a background download, which restarts later. - private func loadNext() { - guard !finished, !dismissRequested else { return } - let current = controller?.currentPreviewItemIndex ?? selectedIndex - guard let next = urls.indices - .filter({ urls[$0] != nil && states[$0] == .loading }) - .min(by: { abs($0 - current) < abs($1 - current) }) - else { return } - if let download { - guard next == current, download.index != current else { return } - download.task.cancel() - } - guard let url = urls[next] else { return } - let title = items[next].previewItemTitle ?? "" - let task = Task { @MainActor [self] in + download = Task { @MainActor [self] in let result: Result do { result = .success(try await Self.prepareFile(url: url, title: title)) } catch { result = .failure(error) } - guard !finished, !Task.isCancelled else { - if case .success(let file) = result { - try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) - } - return - } download = nil - switch result { - case .success(let file): loaded(next, file: file) - case .failure(let error): failed(next, error: error) - } - loadNext() + settle(result, title: title, presenter: presenter) } - download = (next, task) } - private func loaded(_ index: Int, file: URL) { - // Quick Look knows which formats it renders; refuse before presenting so the caller - // can fall back instead of showing an "unsupported format" page. - guard QLPreviewController.canPreview(file as NSURL) else { - try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) - failed(index, error: NSError( - domain: "T3NativePresentation", - code: 3, - userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."] - )) + private func settle(_ result: Result, title: String, presenter: UIViewController) { + guard !finished, controller == nil, !dismissRequested else { + if case .success(let file) = result { Self.remove(file) } return } - items[index].previewItemURL = file - states[index] = .ready - if controller != nil { refresh(index) } else if index == selectedIndex { show() } - } - - private func failed(_ index: Int, error: Error) { - guard index != selectedIndex else { + switch result { + case .success(let file): + // Quick Look knows which formats it renders; refuse before presenting so the caller + // can fall back instead of showing an "unsupported format" page. + guard QLPreviewController.canPreview(file as NSURL) else { + Self.remove(file) + openError = NSError( + domain: "T3NativePresentation", + code: 3, + userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."] + ) + finish() + return + } + self.file = file + show(file: file, title: title, presenter: presenter) + case .failure(let error): openError = error - dismiss() - return + finish() } - states[index] = .failed - refresh(index) } - private func show() { - guard let presenter else { finish(); return } - placeholder?.cancel() + private func show(file: URL, title: String, presenter: UIViewController) { + cancelLoading() + let item = FilePreviewItem() + item.previewItemURL = file + item.previewItemTitle = title + self.item = item let preview = FilePreviewController() preview.delegate = self preview.dataSource = self - preview.currentPreviewItemIndex = selectedIndex preview.onAppear = { [weak self] in self?.resumePendingDismissal() } + preview.onDismiss = { [weak self] in self?.finish() } controller = preview - preview.state = states[selectedIndex] - currentIndexObservation = preview.observe(\.currentPreviewItemIndex) { [weak self] _, _ in - DispatchQueue.main.async { self?.currentItemChanged() } - } presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in resumePendingDismissal() } preview.presentationController?.delegate = self } - private func refresh(_ index: Int) { - guard let controller else { return } - guard controller.currentPreviewItemIndex == index else { - if states[index] == .ready { staleIndices.insert(index) } - return - } - if states[index] == .ready { controller.refreshCurrentPreviewItem() } - controller.state = states[index] + /// Shows over the tapped thumbnail that a slow open is on its way. + private func showSpinner() { + guard !finished, controller == nil, spinner == nil, + let source = sources?.view(for: sourceIdentifier), + let window = source.window + else { return } + let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) + backing.backgroundColor = UIColor.black.withAlphaComponent(0.55) + backing.layer.cornerRadius = 22 + backing.isUserInteractionEnabled = false + let indicator = UIActivityIndicatorView(style: .medium) + indicator.color = .white + indicator.center = CGPoint(x: 22, y: 22) + indicator.startAnimating() + backing.addSubview(indicator) + backing.center = source.convert(CGPoint(x: source.bounds.midX, y: source.bounds.midY), to: window) + window.addSubview(backing) + spinner = backing } - private func currentItemChanged() { - guard !finished, let controller, states.indices.contains(controller.currentPreviewItemIndex) else { return } - let index = controller.currentPreviewItemIndex - if staleIndices.remove(index) != nil { controller.refreshCurrentPreviewItem() } - controller.state = states[index] - loadNext() + private func cancelLoading() { + download?.cancel() + download = nil + spinnerDelay?.cancel() + spinnerDelay = nil + spinner?.removeFromSuperview() + spinner = nil } func dismiss() { dismissRequested = true - download?.task.cancel() guard !finished else { return } guard let controller else { finish(); return } // Drain Close from viewDidAppear after opening or cancelling an interactive dismissal. @@ -249,27 +166,23 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, } } - func numberOfPreviewItems(in controller: QLPreviewController) -> Int { items.count } + func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item == nil ? 0 : 1 } func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { - items[index] + item ?? FilePreviewItem() } - private func sourceView(for item: QLPreviewItem) -> UIView? { - guard !UIAccessibility.isReduceMotionEnabled, - let index = items.firstIndex(where: { $0 === item }), - sourceIdentifiers.indices.contains(index) - else { return nil } - return sources?.view(for: sourceIdentifiers[index]) + private var sourceView: UIView? { + UIAccessibility.isReduceMotionEnabled ? nil : sources?.view(for: sourceIdentifier) } func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? { - sourceView(for: item) + sourceView } func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem, inSourceView view: AutoreleasingUnsafeMutablePointer) -> CGRect { - guard let source = sourceView(for: item) else { return .zero } + guard let source = sourceView else { return .zero } view.pointee = source return source.bounds } @@ -278,47 +191,49 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() } - private func finish(error: Error? = nil) { + private func finish() { guard !finished else { return } finished = true - download?.task.cancel() - download = nil - placeholder?.cancel() - placeholder = nil - currentIndexObservation = nil - for item in items { - if let file = item.previewItemURL { - try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) - } + cancelLoading() + if let file { Self.remove(file) } + file = nil + item = nil + DispatchQueue.main.async { [completion, openError] in completion(openError) } + // After queueing the completion, so a new presentation JS starts on seeing this lands behind it. + onFinish() + } + + private static func remove(_ file: URL) { + try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) + } + + /// Writes the bytes behind a file, data or http(s) URL to `destination`, returning the MIME type it declares. + nonisolated private static func copyOriginal(_ url: URL, to destination: URL) async throws -> String? { + if url.isFileURL { + try FileManager.default.copyItem(at: url, to: destination) + return nil + } + if url.scheme == "data" { + try Data(contentsOf: url).write(to: destination, options: .atomic) + return url.absoluteString.lowercased().hasPrefix("data:image/svg+xml") ? "image/svg+xml" : nil + } + guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { throw URLError(.unsupportedURL) } + let (temporaryFile, response) = try await URLSession.shared.download(from: url) + guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { + throw URLError(.badServerResponse) } - items.removeAll() - urls.removeAll() - states.removeAll() - let result = error ?? openError - DispatchQueue.main.async { [completion] in completion(result) } + try FileManager.default.moveItem(at: temporaryFile, to: destination) + return response.mimeType } /// Copy original bytes so preview and sharing do not mutate a draft or workspace file. - nonisolated private static func prepareFile(url: URL, title: String) async throws -> URL { + nonisolated static func prepareFile(url: URL, title: String) async throws -> URL { try Task.checkCancellation() let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)") try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) do { let download = directory.appendingPathComponent("original") - if url.isFileURL { - try FileManager.default.copyItem(at: url, to: download) - } else if url.scheme == "data" { - try Data(contentsOf: url).write(to: download, options: .atomic) - } else { - guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { - throw URLError(.unsupportedURL) - } - let (temporaryFile, response) = try await URLSession.shared.download(from: url) - guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { - throw URLError(.badServerResponse) - } - try FileManager.default.moveItem(at: temporaryFile, to: download) - } + let mimeType = try await copyOriginal(url, to: download) try Task.checkCancellation() // Detect images and PDFs by content; preserve other extensions so Quick Look can decide support. let filename = URL(fileURLWithPath: title).lastPathComponent as NSString @@ -330,7 +245,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, type = detectedType } else if CGPDFDocument(download as CFURL) != nil { type = .pdf - } else if originalExtension.lowercased() == "svg" { + } else if originalExtension.lowercased() == "svg" || mimeType == "image/svg+xml" { + // ImageIO cannot read SVG, and served images such as QR codes often have no extension. type = .svg } let fileExtension: String diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift new file mode 100644 index 0000000000..382e92875f --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift @@ -0,0 +1,952 @@ +import ImageIO +import Photos +import UIKit + +/// Full-screen image gallery modelled on Messages. It opens at once from the tapped thumbnail's +/// own pixels and sharpens when the original arrives, so a slow or failed load never holds it back. +final class T3NativeImageViewer: NSObject { + let identifier: String + private let completion: (Error?) -> Void + private let onFinish: () -> Void + private weak var sources: T3PresentationSources? + private let sourceIdentifiers: [String] + private var titles: [String] = [] + private var urls: [URL?] = [] + /// The original bytes on disk, kept for sharing. + private var files: [URL?] = [] + private var placeholders: [UIImage?] = [] + private var loads: [Int: Task] = [:] + private var decodes: [Int: Task] = [:] + /// The last queued decode; each one waits for it, so one original decodes at a time. + private var decodeQueue: Task? + /// Pages showing their decoded original; only the current page and its neighbours keep one. + private var decoded: Set = [] + private var currentIndex = 0 + private var controller: T3ImageViewerController? + private var finished = false + + init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String], + onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) { + self.identifier = identifier + self.sources = sources + self.sourceIdentifiers = sourceIdentifiers + self.onFinish = onFinish + self.completion = completion + super.init() + } + + func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) { + self.urls = urls + self.titles = titles + files = Array(repeating: nil, count: urls.count) + currentIndex = selectedIndex + let viewer = T3ImageViewerController(titles: titles, selectedIndex: selectedIndex) + viewer.sourceView = { [weak self] index in self?.sourceView(index) } + viewer.fileForPage = { [weak self] index in self?.file(at: index) } + viewer.onRetry = { [weak self] index in self?.load(index, retry: true) } + viewer.onDismissed = { [weak self] in self?.finish() } + viewer.onPageChange = { [weak self] index in self?.show(page: index) } + controller = viewer + viewer.loadViewIfNeeded() + placeholders = urls.indices.map { sourceView($0).flatMap(Self.thumbnail(of:)) } + for (index, placeholder) in placeholders.enumerated() { + if let placeholder { viewer.setImage(placeholder, at: index, full: false) } + } + presenter.present(T3ImageViewerNavigation(viewer: viewer), animated: false) { viewer.animateIn() } + for index in urls.indices { load(index, retry: false) } + } + + /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will. + func update(index: Int, url: URL?) { + guard !finished, urls.indices.contains(index), urls[index] == nil else { return } + guard let url else { + controller?.setFailed(at: index, retryable: false) + return + } + urls[index] = url + load(index, retry: false) + } + + func dismiss() { + guard !finished else { return } + guard let controller else { finish(); return } + controller.close() + } + + /// Ends at once, for a new viewer that must open while this one is still animating away. + func finishImmediately() { + guard !finished else { return } + controller?.presentingViewController?.dismiss(animated: false) + finish() + } + + private func file(at index: Int) -> URL? { + files.indices.contains(index) ? files[index] : nil + } + + private func sourceView(_ index: Int) -> UIView? { + guard sourceIdentifiers.indices.contains(index), !sourceIdentifiers[index].isEmpty else { return nil } + return sources?.view(for: sourceIdentifiers[index]) + } + + private func load(_ index: Int, retry: Bool) { + guard !finished, urls.indices.contains(index), let url = urls[index], loads[index] == nil else { return } + if retry { controller?.setLoading(at: index) } + let title = titles[index] + loads[index] = Task { @MainActor [self] in + defer { loads[index] = nil } + do { + let file = try await T3NativeFilePresentation.prepareFile(url: url, title: title) + guard !finished, !Task.isCancelled else { Self.remove(file); return } + if let previous = files[index] { Self.remove(previous) } + files[index] = file + decoded.remove(index) + if isNearCurrent(index) { decode(index) } + } catch { + guard !finished, !Task.isCancelled else { return } + controller?.setFailed(at: index, retryable: true) + } + } + } + + /// Every original downloads up front, but a decoded one costs far more memory than its file, + /// so only pages next to the current one decode, and pages further away fall back to their thumbnail. + private func show(page index: Int) { + currentIndex = index + for other in decoded where !isNearCurrent(other) { + decoded.remove(other) + controller?.release(at: other, placeholder: placeholders[other]) + } + // Queued decodes for pages paged past are skipped before they start. + for (other, task) in decodes where !isNearCurrent(other) { task.cancel() } + for near in files.indices where isNearCurrent(near) { decode(near) } + } + + private func isNearCurrent(_ index: Int) -> Bool { abs(index - currentIndex) <= 1 } + + private func decode(_ index: Int) { + guard !finished, let file = file(at: index), !decoded.contains(index), decodes[index] == nil else { return } + let source = sourceView(index) + let previous = decodeQueue + let task = Task { @MainActor [self] in + await previous?.value + var settled = false + defer { + decodes[index] = nil + // Paged away and back while this run waited: it was cancelled, so the page asks again. + if !settled, !finished, isNearCurrent(index), !decoded.contains(index) { decode(index) } + } + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } + // ImageIO reads SVG poorly or not at all; the thumbnail is vector, so redraw it at full-screen size. + let isSVG = file.pathExtension.lowercased() == "svg" + let image = isSVG ? nil : await Task.detached(priority: .userInitiated) { Self.decode(file) }.value + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } + if isSVG { + // The open transition hides the thumbnail, which draws blank until it is back. + await controller?.untilRevealed() + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } + } + settled = true + if let image = image ?? (isSVG ? source.flatMap(Self.render(_:)) : nil) { + decoded.insert(index) + controller?.setImage(image, at: index, full: true) + } else { + // A corrupt download or an SVG whose thumbnail is scrolled away; retrying downloads it again. + // A file that is not an image must not reach Share. + if !isSVG { + Self.remove(file) + files[index] = nil + } + controller?.setFailed(at: index, retryable: true) + } + } + decodes[index] = task + decodeQueue = task + } + + private func finish() { + guard !finished else { return } + finished = true + for task in loads.values { task.cancel() } + loads.removeAll() + for task in decodes.values { task.cancel() } + decodes.removeAll() + decodeQueue = nil + for file in files.compactMap({ $0 }) { Self.remove(file) } + files.removeAll() + controller = nil + DispatchQueue.main.async { [completion] in completion(nil) } + // After queueing the completion, so a new presentation JS starts on seeing this lands behind it. + onFinish() + } + + private static func remove(_ file: URL) { + try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) + } + + /// The decoded image a thumbnail already shows, uncropped, or a snapshot of a view that draws one. + /// The largest image view wins, so an overlaid icon is never mistaken for the picture. + private static func thumbnail(of view: UIView) -> UIImage? { + var queue = [view] + var best: (image: UIImage, area: CGFloat)? + while let candidate = queue.popLast() { + queue.append(contentsOf: candidate.subviews) + guard let image = (candidate as? UIImageView)?.image, image.size.width > 0, image.size.height > 0 else { continue } + let area = candidate.bounds.width * candidate.bounds.height + if area > best?.area ?? 0 { best = (image, area) } + } + if let best, best.area >= view.bounds.width * view.bounds.height / 2 { return best.image } + return snapshot(view, scale: view.window?.screen.scale ?? 2) + } + + private static func render(_ view: UIView) -> UIImage? { + let screen = view.window?.screen.bounds.size ?? CGSize(width: 1024, height: 1024) + let fit = min(screen.width / max(view.bounds.width, 1), screen.height / max(view.bounds.height, 1)) + // The thumbnail was shown again after the open transition, in a frame not yet on screen. + return snapshot(view, scale: max(1, fit) * (view.window?.screen.scale ?? 2), afterScreenUpdates: true) + } + + private static func snapshot(_ view: UIView, scale: CGFloat, afterScreenUpdates: Bool = false) -> UIImage? { + guard view.bounds.width > 1, view.bounds.height > 1, view.window != nil else { return nil } + let format = UIGraphicsImageRendererFormat() + format.scale = scale + format.opaque = false + return UIGraphicsImageRenderer(bounds: view.bounds, format: format).image { _ in + view.drawHierarchy(in: view.bounds, afterScreenUpdates: afterScreenUpdates) + } + } + + /// Decodes off the main thread at no more than zooming needs, and keeps GIFs animated. + nonisolated private static func decode(_ file: URL) -> UIImage? { + guard let source = CGImageSourceCreateWithURL(file as CFURL, nil) else { return nil } + let count = CGImageSourceGetCount(source) + guard count > 0 else { return nil } + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: 4096, + ] + var animationOptions = options + animationOptions[kCGImageSourceThumbnailMaxPixelSize] = 1024 + animationOptions[kCGImageSourceShouldCacheImmediately] = nil + // Every frame stays decoded while it plays, so an animation over this budget shows its first frame. + if count > 1, let first = CGImageSourceCreateThumbnailAtIndex(source, 0, animationOptions as CFDictionary), + first.bytesPerRow * first.height * count <= animationByteBudget { + var frames: [(image: UIImage, delay: Double)] = [(UIImage(cgImage: first), frameDuration(source, 0))] + for index in 1.. 1 { return UIImage.animatedImage(with: timeline, duration: Double(timeline.count) * tick) } + } + return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary).map { UIImage(cgImage: $0) } + } + + nonisolated private static func frameDuration(_ source: CGImageSource, _ index: Int) -> Double { + let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any] + let gif = properties?[kCGImagePropertyGIFDictionary] as? [CFString: Any] + let png = properties?[kCGImagePropertyPNGDictionary] as? [CFString: Any] + let delay = gif?[kCGImagePropertyGIFUnclampedDelayTime] as? Double + ?? gif?[kCGImagePropertyGIFDelayTime] as? Double + ?? png?[kCGImagePropertyAPNGUnclampedDelayTime] as? Double + ?? png?[kCGImagePropertyAPNGDelayTime] as? Double + ?? 0.1 + // Browsers treat near-zero delays as 0.1s. + return delay < 0.011 ? 0.1 : delay + } +} + +private let animationByteBudget = 64 * 1024 * 1024 + +private extension Array { + subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil } +} + +/// One zoomable page. Its content never exceeds its bounds at the fitted zoom, so a vertical +/// drag has nothing to scroll and always reaches the dismiss gesture. +private final class T3ImageViewerPage: UIView, UIScrollViewDelegate { + let scroll = UIScrollView() + let imageView = UIImageView() + private let spinner = UIActivityIndicatorView(style: .large) + private let failure = UIStackView() + private var spinnerDelay: DispatchWorkItem? + private var laidOutSize = CGSize.zero + private(set) var isFull = false + var onRetry: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + scroll.delegate = self + scroll.showsVerticalScrollIndicator = false + scroll.showsHorizontalScrollIndicator = false + scroll.contentInsetAdjustmentBehavior = .never + scroll.decelerationRate = .fast + scroll.alwaysBounceVertical = false + scroll.alwaysBounceHorizontal = false + scroll.bouncesZoom = true + addSubview(scroll) + imageView.contentMode = .scaleAspectFill + imageView.clipsToBounds = true + imageView.isAccessibilityElement = true + imageView.accessibilityTraits = .image + scroll.addSubview(imageView) + spinner.color = .white + spinner.hidesWhenStopped = true + addSubview(spinner) + configureFailure() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + private func configureFailure() { + let icon = UIImageView(image: UIImage(systemName: "exclamationmark.triangle")) + icon.tintColor = UIColor(white: 1, alpha: 0.8) + icon.preferredSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 28, weight: .regular) + let label = UILabel() + label.text = "This image could not be loaded." + label.textColor = UIColor(white: 1, alpha: 0.8) + label.font = .preferredFont(forTextStyle: .subheadline) + label.adjustsFontForContentSizeCategory = true + label.textAlignment = .center + label.numberOfLines = 0 + var configuration = UIButton.Configuration.gray() + configuration.title = "Try Again" + configuration.cornerStyle = .capsule + configuration.baseForegroundColor = .white + configuration.baseBackgroundColor = UIColor(white: 1, alpha: 0.18) + let retry = UIButton(configuration: configuration, primaryAction: UIAction { [weak self] _ in self?.onRetry?() }) + failure.axis = .vertical + failure.alignment = .center + failure.spacing = 12 + failure.isHidden = true + for view in [icon, label, retry] { failure.addArrangedSubview(view) } + addSubview(failure) + } + + var image: UIImage? { imageView.image } + + func setImage(_ image: UIImage, full: Bool) { + guard full || !isFull else { return } + let previous = imageView.image?.size + imageView.image = image + isFull = full + stopLoading() + failure.isHidden = true + let ratio = { (size: CGSize) in size.width / max(size.height, 1) } + // A sharper copy of the same picture keeps the reader's zoom; a different shape starts over. + if previous == nil || abs(ratio(previous ?? .zero) - ratio(image.size)) > 0.01 { laidOutSize = .zero } + setNeedsLayout() + } + + /// Gives back a far-away page's decoded original, keeping the thumbnail until it returns. + func release(to placeholder: UIImage?) { + guard isFull else { return } + isFull = false + imageView.image = placeholder + laidOutSize = .zero + setNeedsLayout() + setLoading() + } + + func setLoading() { + failure.isHidden = true + imageView.alpha = 1 + guard imageView.image == nil, spinnerDelay == nil else { return } + let work = DispatchWorkItem { [weak self] in self?.spinner.startAnimating() } + spinnerDelay = work + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work) + } + + func setFailed(retryable: Bool) { + stopLoading() + guard !isFull else { return } + failure.arrangedSubviews.last?.isHidden = !retryable + failure.isHidden = false + // A thumbnail stays visible behind the message, dimmed. + imageView.alpha = imageView.image == nil ? 1 : 0.35 + } + + private func stopLoading() { + spinnerDelay?.cancel() + spinnerDelay = nil + spinner.stopAnimating() + imageView.alpha = 1 + } + + var isZoomed: Bool { scroll.zoomScale > scroll.minimumZoomScale + 0.01 } + + func resetZoom(animated: Bool) { scroll.setZoomScale(scroll.minimumZoomScale, animated: animated) } + + override func layoutSubviews() { + super.layoutSubviews() + scroll.frame = bounds + spinner.center = CGPoint(x: bounds.midX, y: bounds.midY) + let width = min(bounds.width - 48, 320) + let height = failure.systemLayoutSizeFitting(CGSize(width: width, height: 0), + withHorizontalFittingPriority: .required, + verticalFittingPriority: .fittingSizeLevel).height + failure.frame = CGRect(x: (bounds.width - width) / 2, y: (bounds.height - height) / 2, width: width, height: height) + guard bounds.size != laidOutSize, let size = imageView.image?.size, size.width > 0, size.height > 0 else { return } + laidOutSize = bounds.size + let fit = min(bounds.width / size.width, bounds.height / size.height) + scroll.minimumZoomScale = 1 + scroll.zoomScale = 1 + imageView.transform = .identity + imageView.frame = CGRect(x: 0, y: 0, width: size.width * fit, height: size.height * fit) + scroll.contentSize = imageView.frame.size + // Enough to fill the screen and then some, or to see the original's pixels. + let fill = max(bounds.width / imageView.frame.width, bounds.height / imageView.frame.height) + let pixels = 1 / fit / (window?.screen.scale ?? 2) + scroll.maximumZoomScale = max(3, fill * 1.5, pixels) + centerImage() + } + + /// The fitted frame of the image, for the opening transition. + func fittedFrame(in view: UIView) -> CGRect { + layoutIfNeeded() + return imageView.convert(imageView.bounds, to: view) + } + + func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView } + + func scrollViewDidZoom(_ scrollView: UIScrollView) { centerImage() } + + private func centerImage() { + let content = scroll.contentSize + imageView.center = CGPoint(x: max(content.width, scroll.bounds.width) / 2, + y: max(content.height, scroll.bounds.height) / 2) + } + + func toggleZoom(at point: CGPoint) { + if isZoomed { resetZoom(animated: true); return } + guard imageView.image != nil else { return } + let location = convert(point, to: imageView) + let fill = max(scroll.bounds.width / imageView.bounds.width, scroll.bounds.height / imageView.bounds.height) + let scale = min(scroll.maximumZoomScale, fill > 1.2 ? fill : 2.5) + let width = scroll.bounds.width / scale + let height = scroll.bounds.height / scale + scroll.zoom(to: CGRect(x: location.x - width / 2, y: location.y - height / 2, width: width, height: height), + animated: true) + } +} + +/// System bars, so UIKit places Close, the title, Save and Share: at the top and bottom of an iPhone, +/// and in the side bar of an unfolded iPhone Duo. +private final class T3ImageViewerNavigation: UINavigationController { + init(viewer: T3ImageViewerController) { + super.init(rootViewController: viewer) + modalPresentationStyle = .overFullScreen + modalPresentationCapturesStatusBarAppearance = true + overrideUserInterfaceStyle = .dark + view.backgroundColor = .clear + if #unavailable(iOS 26.0) { + // Before iOS 26 bars at the scroll edge are transparent; iOS 26 gives them its edge blur instead. + let bar = UINavigationBarAppearance() + bar.configureWithDefaultBackground() + navigationBar.scrollEdgeAppearance = bar + navigationBar.compactScrollEdgeAppearance = bar + let tools = UIToolbarAppearance() + tools.configureWithDefaultBackground() + toolbar.scrollEdgeAppearance = tools + toolbar.compactScrollEdgeAppearance = tools + } + setNavigationBarHidden(true, animated: false) + setToolbarHidden(true, animated: false) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + override var childForStatusBarHidden: UIViewController? { topViewController } + override var childForStatusBarStyle: UIViewController? { topViewController } + override var childForHomeIndicatorAutoHidden: UIViewController? { topViewController } +} + +final class T3ImageViewerController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate { + var sourceView: (Int) -> UIView? = { _ in nil } + var fileForPage: (Int) -> URL? = { _ in nil } + var onRetry: (Int) -> Void = { _ in } + var onPageChange: (Int) -> Void = { _ in } + var onDismissed: () -> Void = {} + + private let titles: [String] + private var currentIndex: Int + private let backdrop = UIView() + private let pager = UIScrollView() + private var pages: [T3ImageViewerPage] = [] + private let titleLabel = UILabel() + private let counterLabel = UILabel() + private lazy var dismissPan = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan(_:))) + private var chromeHidden = false + private var chromeHiddenBeforeDrag = false + private var dragAnchor = CGPoint.zero + private var transitioning = true + private var closeRequested = false + private var closing = false + private var revealed = false + private var revealWaiters: [CheckedContinuation] = [] + private var laidOutSize = CGSize.zero + private var isLayingOut = false + private lazy var saveItem = UIBarButtonItem( + title: "Save to Photos", image: UIImage(systemName: "square.and.arrow.down"), + primaryAction: UIAction { [weak self] _ in self?.save() }) + private lazy var shareItem = UIBarButtonItem( + systemItem: .action, primaryAction: UIAction { [weak self] _ in self?.share() }) + private static let pageGap: CGFloat = 20 + + init(titles: [String], selectedIndex: Int) { + self.titles = titles + currentIndex = selectedIndex + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + override var prefersStatusBarHidden: Bool { chromeHidden } + override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent } + override var prefersHomeIndicatorAutoHidden: Bool { chromeHidden } + override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { .fade } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .clear + backdrop.backgroundColor = .black + backdrop.alpha = 0 + view.addSubview(backdrop) + pager.isPagingEnabled = true + pager.showsHorizontalScrollIndicator = false + pager.showsVerticalScrollIndicator = false + pager.contentInsetAdjustmentBehavior = .never + pager.alwaysBounceVertical = false + pager.delegate = self + pager.isHidden = true + view.addSubview(pager) + for index in titles.indices { + let page = T3ImageViewerPage() + page.imageView.accessibilityLabel = titles[index] + page.onRetry = { [weak self] in self?.onRetry(index) } + page.scroll.panGestureRecognizer.require(toFail: dismissPan) + page.setLoading() + pages.append(page) + pager.addSubview(page) + } + pager.panGestureRecognizer.require(toFail: dismissPan) + dismissPan.delegate = self + dismissPan.maximumNumberOfTouches = 1 + view.addGestureRecognizer(dismissPan) + let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:))) + doubleTap.numberOfTapsRequired = 2 + pager.addGestureRecognizer(doubleTap) + let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap)) + singleTap.require(toFail: doubleTap) + pager.addGestureRecognizer(singleTap) + configureChrome() + updateTitle() + } + + private func configureChrome() { + navigationItem.leftBarButtonItem = UIBarButtonItem( + systemItem: .close, primaryAction: UIAction { [weak self] _ in self?.close() }) + if #unavailable(iOS 26.0) { + // Before iOS 26 a navigation item has no subtitle, so the count sits under the title by hand. + titleLabel.font = .preferredFont(forTextStyle: .headline) + counterLabel.font = .preferredFont(forTextStyle: .caption1) + counterLabel.textColor = .secondaryLabel + for label in [titleLabel, counterLabel] { + label.textAlignment = .center + label.adjustsFontForContentSizeCategory = true + label.lineBreakMode = .byTruncatingMiddle + } + let titles = UIStackView(arrangedSubviews: [titleLabel, counterLabel]) + titles.axis = .vertical + titles.alignment = .center + navigationItem.titleView = titles + } + toolbarItems = [.flexibleSpace(), saveItem, shareItem] + setContentScrollView(pager, for: .top) + setContentScrollView(pager, for: .bottom) + } + + /// Shows or hides the bars through UIKit, which also moves them out of an iPhone Duo's side bar. + private func setBarsVisible(_ visible: Bool) { + navigationController?.setNavigationBarHidden(!visible, animated: true) + navigationController?.setToolbarHidden(!visible, animated: true) + } + + private func updateTitle() { + updateActions() + let title = titles[safe: currentIndex] + let counter = titles.count > 1 ? "\(currentIndex + 1) of \(titles.count)" : nil + navigationItem.title = title + if #available(iOS 26.0, *) { navigationItem.subtitle = counter } + titleLabel.text = title + counterLabel.text = counter + counterLabel.isHidden = counter == nil + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + backdrop.frame = view.bounds + guard view.bounds.size != laidOutSize else { return } + laidOutSize = view.bounds.size + // Resizing the pager scrolls it; that must not move the reader to another page. + isLayingOut = true + defer { isLayingOut = false } + // Pages sit a gap apart, like Photos, so the pager is a gap wider than the screen. + let pageWidth = view.bounds.width + Self.pageGap + pager.frame = CGRect(x: -Self.pageGap / 2, y: 0, width: pageWidth, height: view.bounds.height) + for (index, page) in pages.enumerated() { + page.transform = .identity + page.frame = CGRect(x: CGFloat(index) * pageWidth + Self.pageGap / 2, y: 0, + width: view.bounds.width, height: view.bounds.height) + } + pager.contentSize = CGSize(width: pageWidth * CGFloat(pages.count), height: view.bounds.height) + pager.contentOffset = CGPoint(x: CGFloat(currentIndex) * pageWidth, y: 0) + } + + func setImage(_ image: UIImage, at index: Int, full: Bool) { + guard let page = pages[safe: index] else { return } + page.setImage(image, full: full) + updateActions() + } + + func setLoading(at index: Int) { pages[safe: index]?.setLoading() } + + func release(at index: Int, placeholder: UIImage?) { + pages[safe: index]?.release(to: placeholder) + updateActions() + } + + func setFailed(at index: Int, retryable: Bool) { + pages[safe: index]?.setFailed(retryable: retryable) + updateActions() + } + + /// Save and Share act on the original, so they wait until the current page shows it. + private func updateActions() { + let ready = pages[safe: currentIndex]?.isFull == true + saveItem.isEnabled = ready + shareItem.isEnabled = ready + } + + // MARK: Transitions + + private var reduceMotion: Bool { UIAccessibility.isReduceMotionEnabled } + + private func visibleSource(_ index: Int) -> UIView? { + guard !reduceMotion, let source = sourceView(index), source.window === view.window, !source.isHidden else { return nil } + let frame = source.convert(source.bounds, to: view) + guard frame.width > 1, frame.height > 1, view.bounds.intersects(frame) else { return nil } + return source + } + + private static func cornerRadius(of view: UIView) -> CGFloat { + var queue = [view] + var depth = 0 + while !queue.isEmpty, depth < 4 { + for candidate in queue where candidate.layer.cornerRadius > 0 { return candidate.layer.cornerRadius } + queue = queue.flatMap(\.subviews) + depth += 1 + } + return 0 + } + + private func makeTransitionView(_ image: UIImage, frame: CGRect) -> UIImageView { + let transition = UIImageView(image: image) + transition.contentMode = .scaleAspectFill + transition.clipsToBounds = true + transition.frame = frame + view.addSubview(transition) + return transition + } + + /// Returns once the open transition has finished and the thumbnails are on screen again. + func untilRevealed() async { + guard !revealed else { return } + await withCheckedContinuation { revealWaiters.append($0) } + } + + func animateIn() { + view.layoutIfNeeded() + let page = pages[currentIndex] + let reveal = { [weak self] in + guard let self else { return } + self.pager.isHidden = false + self.transitioning = false + self.revealed = true + for waiter in self.revealWaiters { waiter.resume() } + self.revealWaiters.removeAll() + self.setNeedsStatusBarAppearanceUpdate() + UIAccessibility.post(notification: .screenChanged, argument: page.imageView) + if self.closeRequested { self.close() } + } + guard let image = page.image, let source = visibleSource(currentIndex) else { + pager.isHidden = false + pager.alpha = 0 + setBarsVisible(true) + UIView.animate(withDuration: reduceMotion ? 0.2 : 0.25, animations: { + self.backdrop.alpha = 1 + self.pager.alpha = 1 + }, completion: { _ in reveal() }) + return + } + let transition = makeTransitionView(image, frame: source.convert(source.bounds, to: view)) + transition.layer.cornerRadius = Self.cornerRadius(of: source) + let sourceAlpha = source.alpha + source.alpha = 0 + let target = page.fittedFrame(in: view) + let animator = UIViewPropertyAnimator(duration: 0.42, dampingRatio: 0.86) { + transition.frame = target + transition.layer.cornerRadius = 0 + self.backdrop.alpha = 1 + } + setBarsVisible(true) + animator.addCompletion { _ in + source.alpha = sourceAlpha + transition.removeFromSuperview() + reveal() + } + animator.startAnimation() + } + + /// Closes back into the current page's thumbnail, or away in the drag's direction when it is gone. + func close(velocity: CGPoint = .zero) { + closeRequested = true + guard !transitioning, !closing else { return } + closing = true + transitioning = true + setNeedsStatusBarAppearanceUpdate() + setBarsVisible(false) + let page = pages[currentIndex] + guard let image = page.image else { + UIView.animate(withDuration: 0.2, animations: { self.view.alpha = 0 }, completion: { _ in self.finishClose() }) + return + } + let transition = makeTransitionView(image, frame: page.imageView.convert(page.imageView.bounds, to: view)) + pager.isHidden = true + guard let source = visibleSource(currentIndex) else { + let direction: CGFloat = velocity.y < 0 ? -1 : 1 + let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeIn) { + transition.center.y += direction * self.view.bounds.height + self.backdrop.alpha = 0 + if self.reduceMotion { transition.alpha = 0 } + } + animator.addCompletion { _ in self.finishClose() } + animator.startAnimation() + return + } + let sourceAlpha = source.alpha + source.alpha = 0 + let target = source.convert(source.bounds, to: view) + let radius = Self.cornerRadius(of: source) + let speed = hypot(velocity.x, velocity.y) + let distance = hypot(target.midX - transition.center.x, target.midY - transition.center.y) + let initial = distance > 0 ? CGVector(dx: velocity.x / distance, dy: velocity.y / distance) : .zero + let timing = UISpringTimingParameters(dampingRatio: 0.88, initialVelocity: speed > 0 ? initial : .zero) + let animator = UIViewPropertyAnimator(duration: 0.4, timingParameters: timing) + animator.addAnimations { + transition.frame = target + transition.layer.cornerRadius = radius + self.backdrop.alpha = 0 + } + animator.addCompletion { _ in + source.alpha = sourceAlpha + self.finishClose() + } + animator.startAnimation() + } + + private func finishClose() { + presentingViewController?.dismiss(animated: false) { [onDismissed] in onDismissed() } + } + + // MARK: Gestures + + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + guard gestureRecognizer === dismissPan else { return true } + guard !transitioning, !pager.isDragging, !pager.isDecelerating, + let page = pages[safe: currentIndex], !page.isZoomed + else { return false } + let velocity = dismissPan.velocity(in: view) + return abs(velocity.y) > abs(velocity.x) + } + + @objc private func handleDismissPan(_ gesture: UIPanGestureRecognizer) { + let page = pages[currentIndex] + let translation = gesture.translation(in: view) + switch gesture.state { + case .began: + chromeHiddenBeforeDrag = chromeHidden + dragAnchor = gesture.location(in: page) + setChromeHidden(true) + case .changed: + // Shrink around the finger, as Photos does, so the touched spot stays under it. + let progress = min(1, abs(translation.y) / (view.bounds.height / 2)) + let scale = 1 - 0.3 * progress + let offset = CGPoint(x: dragAnchor.x - page.bounds.midX, y: dragAnchor.y - page.bounds.midY) + page.transform = CGAffineTransform(translationX: translation.x + (1 - scale) * offset.x, + y: translation.y + (1 - scale) * offset.y).scaledBy(x: scale, y: scale) + backdrop.alpha = 1 - progress + case .ended, .cancelled, .failed: + let velocity = gesture.velocity(in: view) + let flung = abs(velocity.y) > 800 && velocity.y * translation.y > 0 + if gesture.state == .ended, flung || abs(translation.y) > 120 { + close(velocity: velocity) + } else { + UIViewPropertyAnimator(duration: 0.35, dampingRatio: 0.8) { + page.transform = .identity + self.backdrop.alpha = 1 + }.startAnimation() + setChromeHidden(chromeHiddenBeforeDrag) + } + default: + break + } + } + + @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) { + guard !transitioning, let page = pages[safe: currentIndex] else { return } + page.toggleZoom(at: gesture.location(in: page)) + } + + @objc private func handleSingleTap() { + guard !transitioning else { return } + setChromeHidden(!chromeHidden) + } + + private func setChromeHidden(_ hidden: Bool) { + guard chromeHidden != hidden else { return } + chromeHidden = hidden + setBarsVisible(!hidden) + UIView.animate(withDuration: 0.2) { self.setNeedsStatusBarAppearanceUpdate() } + setNeedsUpdateOfHomeIndicatorAutoHidden() + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + guard scrollView === pager, !transitioning, !isLayingOut, pager.bounds.width > 0 else { return } + let index = Int((pager.contentOffset.x / pager.bounds.width).rounded()) + guard pages.indices.contains(index), index != currentIndex else { return } + pages[currentIndex].resetZoom(animated: false) + currentIndex = index + updateTitle() + onPageChange(index) + } + + private func scroll(to index: Int) { + guard pages.indices.contains(index), !transitioning else { return } + pager.setContentOffset(CGPoint(x: CGFloat(index) * pager.bounds.width, y: 0), animated: !reduceMotion) + } + + // MARK: Share, keyboard and accessibility + + private func save() { + let image = pages[currentIndex].isFull ? pages[currentIndex].image : nil + // Original bytes keep the format and metadata; an SVG only has its rendered image. The copy + // belongs to this save, since closing the viewer deletes its files before Photos may read them. + let original = fileForPage(currentIndex).flatMap { file -> URL? in + guard file.pathExtension.lowercased() != "svg", let source = CGImageSourceCreateWithURL(file as CFURL, nil), CGImageSourceGetCount(source) > 0 else { return nil } + let copy = FileManager.default.temporaryDirectory.appendingPathComponent("t3-save-\(UUID().uuidString)") + .appendingPathComponent(file.lastPathComponent) + do { + try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(at: file, to: copy) + return copy + } catch { + return nil + } + } + guard original != nil || image != nil else { return } + let cleanUp = { if let original { try? FileManager.default.removeItem(at: original.deletingLastPathComponent()) } } + PHPhotoLibrary.requestAuthorization(for: .addOnly) { [weak self] status in + guard status == .authorized || status == .limited else { + cleanUp() + DispatchQueue.main.async { self?.showSaveError("Allow T3 Code to add photos in Settings.") } + return + } + PHPhotoLibrary.shared().performChanges({ + if let original { + PHAssetCreationRequest.forAsset().addResource(with: .photo, fileURL: original, options: nil) + } else if let image { + PHAssetChangeRequest.creationRequestForAsset(from: image) + } + }, completionHandler: { saved, error in + cleanUp() + DispatchQueue.main.async { + if saved { + self?.confirmSaved() + } else { + self?.showSaveError(error?.localizedDescription ?? "Photos could not save this image.") + } + } + }) + } + } + + private func confirmSaved() { + UINotificationFeedbackGenerator().notificationOccurred(.success) + UIAccessibility.post(notification: .announcement, argument: "Saved to Photos") + saveItem.image = UIImage(systemName: "checkmark") + DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in + self?.saveItem.image = UIImage(systemName: "square.and.arrow.down") + } + } + + private func showSaveError(_ message: String) { + let alert = UIAlertController(title: "Could not save image", message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } + + private func share() { + let page = pages[currentIndex] + let item: Any? = fileForPage(currentIndex) ?? (page.isFull ? page.image : nil) + guard let item else { return } + let sheet = UIActivityViewController(activityItems: [item], applicationActivities: nil) + sheet.popoverPresentationController?.sourceItem = shareItem + present(sheet, animated: true) + } + + override var canBecomeFirstResponder: Bool { true } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + becomeFirstResponder() + } + + override var keyCommands: [UIKeyCommand]? { + [ + UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(handleEscape)), + UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(handlePrevious)), + UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(handleNext)), + ] + } + + @objc private func handleEscape() { close() } + @objc private func handlePrevious() { scroll(to: currentIndex - 1) } + @objc private func handleNext() { scroll(to: currentIndex + 1) } + + override func accessibilityPerformEscape() -> Bool { + close() + return true + } + + override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { + switch direction { + case .left: scroll(to: currentIndex + 1) + case .right: scroll(to: currentIndex - 1) + default: return false + } + UIAccessibility.post(notification: .pageScrolled, argument: counterLabel.text) + return true + } +} diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift index 932ed1d0a3..3b43334b12 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift @@ -7,21 +7,28 @@ final class T3PresentationSources { init(_ view: UIView) { self.view = view } } - private var entries: [String: Entry] = [:] + /// The same file embedded twice registers twice; removing one copy keeps the other. + private var entries: [String: [Entry]] = [:] func register(_ view: UIView, identifier: String) { - entries[identifier] = Entry(view) + var list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view } + list.append(Entry(view)) + entries[identifier] = list } func remove(_ view: UIView, identifier: String) { - if entries[identifier]?.view == nil || entries[identifier]?.view === view { - entries.removeValue(forKey: identifier) - } + let list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view } + entries[identifier] = list.isEmpty ? nil : list } func view(for identifier: String) -> UIView? { - // Use the child bounds, not the wrapper's potentially stretched layout bounds. - entries[identifier]?.view?.subviews.first + let views = (entries[identifier] ?? []).compactMap(\.view) + // Prefer an on-screen copy, the latest first; use the child bounds, not the wrapper's stretched ones. + let source = views.last(where: { view in + guard let window = view.window else { return false } + return window.bounds.intersects(view.convert(view.bounds, to: window)) + }) ?? views.last + return source?.subviews.first } } diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift index 0f4e70b20c..065eba4331 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift @@ -4,8 +4,9 @@ import UIKit /// Wraps a screen's header scroll view. Where a column pads its content away from the iPhone Duo's /// vertical bar, this widens the scroll view under the bar, like the system apps' lists. UIKit /// draws the header's scroll-edge effect inside the scroll view, so the blur reaches the bar while -/// the content stays in the safe area. Everything happens in UIKit layout, so folds move the blur -/// and the content together. +/// the content stays in the safe area, and the scroll indicator runs along the screen edge past the +/// bar, as in Messages. Everything happens in UIKit layout, so folds move the blur and the content +/// together. final class T3ScrollEdgeBleedView: ExpoView { // Fabric recycles scroll views, so everything changed here is put back before this view leaves // the window, which unmounting does before any recycling. @@ -19,6 +20,10 @@ final class T3ScrollEdgeBleedView: ExpoView { /// React Native's clipping, saved while bleeding. React Native only rewrites it when the /// `overflow` style changes, so it stays off while bleeding. private var containerClipped: Bool? + /// The bar's side is read from the root view controller, whose traits can settle after this + /// view's own during a fold; with no size change after that, nothing else would recheck. + private weak var observedWindow: UIWindow? + private var windowTraitRegistration: (any UITraitChangeRegistration)? required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -37,9 +42,33 @@ final class T3ScrollEdgeBleedView: ExpoView { override func didMoveToWindow() { super.didMoveToWindow() + observeWindowTraits() if window == nil { detach() } else { setNeedsLayout() } } + override func safeAreaInsetsDidChange() { + super.safeAreaInsetsDidChange() + setNeedsLayout() + } + + private func observeWindowTraits() { + guard observedWindow !== window else { return } + if let observedWindow, let windowTraitRegistration { + observedWindow.unregisterForTraitChanges(windowTraitRegistration) + } + observedWindow = window + windowTraitRegistration = nil + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), let window { + windowTraitRegistration = window.registerForTraitChanges( + UITraitCollection.systemTraitsAffectingVerticalBarEdge + ) { [weak self] (_: UIWindow, _: UITraitCollection) in + self?.setNeedsLayout() + } + } + #endif + } + override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) setNeedsLayout() @@ -136,11 +165,6 @@ final class T3ScrollEdgeBleedView: ExpoView { containerClipped = containerClipped ?? true container.layer.masksToBounds = false } - var indicators = scrollView.verticalScrollIndicatorInsets - if indicators.right != bleed.right { - indicators.right = bleed.right - scrollView.verticalScrollIndicatorInsets = indicators - } applied = bleeding } diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index 243490678c..78fd2ec1fe 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -56,6 +56,9 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { composeButton.isHidden = !showsCompose tabBarTrailing.constant = showsCompose ? (compact ? -64 : -76) : 0 setNeedsLayout() + // JS moves this view's edge by the same amount, so the bar keeps its frame and won't lay + // itself out; compose is placed only from that layout. + tabBar.setNeedsLayout() } } var appearance = "light" { diff --git a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift index 7f96dc17a2..4c60b20c1a 100644 --- a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift +++ b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift @@ -16,6 +16,13 @@ struct ReviewDiffCodeLineStarts: RandomAccessCollection { /// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights. /// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling. +/** A cut line's note, drawn in its own colors. */ +struct ReviewDiffCodeNote { + let range: NSRange + let color: UIColor + let background: UIColor +} + final class ReviewDiffCodeLayout: NSObject { static let unboundedWidth = CGFloat.greatestFiniteMagnitude @@ -84,7 +91,14 @@ final class ReviewDiffCodeLayout: NSObject { return layout } - func decorate(text: NSAttributedString, highlights: [NSRange], color: UIColor, version: Int) { + // A cut line's note is not code, so it takes the warning colors over any token color. + func decorate( + text: NSAttributedString, + highlights: [NSRange], + color: UIColor, + note: ReviewDiffCodeNote? = nil, + version: Int + ) { guard usesNativeLayout else { return } let layout = nativeLayout() guard layout.decorationVersion != version else { return } @@ -105,6 +119,13 @@ final class ReviewDiffCodeLayout: NSObject { storage.addAttribute(.backgroundColor, value: color, range: intersection) } } + if let note { + let intersection = NSIntersectionRange(note.range, fullRange) + if intersection.length > 0 { + storage.addAttribute(.foregroundColor, value: note.color, range: intersection) + storage.addAttribute(.backgroundColor, value: note.background, range: intersection) + } + } storage.endEditing() layout.decorationVersion = version } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift index 2fcb8a4801..d1be707b0d 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift @@ -88,6 +88,7 @@ public class T3ReviewDiffModule: Module { "onToggleViewedFile", "onPressLine", "onToggleComment", + "onPressNotice", "onPullToRefresh" ) diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index a80a391380..7fe4a068f9 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -19,6 +19,12 @@ private struct ReviewDiffNativeRow: Decodable, Sendable { let commentText: String? let commentRangeLabel: String? let commentSectionTitle: String? + /** A notice drawn in the warning colors. */ + let tone: String? + /** A notice that reports taps through `onPressNotice`. */ + let actionable: Bool? + /** Where a cut line's note starts in `content`, in UTF-16 units. */ + let noteStart: Int? } private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable { @@ -52,6 +58,8 @@ private struct ReviewDiffNativeThemePayload: Decodable { let deleteBar: String? let addText: String? let deleteText: String? + let warningText: String? + let warningBackground: String? } private struct ReviewDiffNativeTheme { @@ -68,6 +76,8 @@ private struct ReviewDiffNativeTheme { let deleteBar: UIColor let addText: UIColor let deleteText: UIColor + let warningText: UIColor + let warningBackground: UIColor static func resolve(_ scheme: String) -> ReviewDiffNativeTheme { resolve(scheme, payload: nil) @@ -95,7 +105,10 @@ private struct ReviewDiffNativeTheme { addBar: UIColor(reviewDiffHex: payload.addBar) ?? fallback.addBar, deleteBar: UIColor(reviewDiffHex: payload.deleteBar) ?? fallback.deleteBar, addText: UIColor(reviewDiffHex: payload.addText) ?? fallback.addText, - deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText + deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText, + warningText: UIColor(reviewDiffHex: payload.warningText) ?? fallback.warningText, + warningBackground: UIColor(reviewDiffHex: payload.warningBackground) + ?? fallback.warningBackground ) } @@ -114,7 +127,9 @@ private struct ReviewDiffNativeTheme { addBar: UIColor(red: 0.02, green: 0.82, blue: 0.54, alpha: 1), deleteBar: UIColor(red: 1.00, green: 0.36, blue: 0.50, alpha: 1), addText: UIColor(red: 0.10, green: 0.84, blue: 0.56, alpha: 1), - deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1) + deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1), + warningText: UIColor(red: 0.98, green: 0.80, blue: 0.40, alpha: 1), + warningBackground: UIColor(red: 0.20, green: 0.15, blue: 0.05, alpha: 1) ) } @@ -131,7 +146,9 @@ private struct ReviewDiffNativeTheme { addBar: UIColor(red: 0.02, green: 0.80, blue: 0.52, alpha: 1), deleteBar: UIColor(red: 1.00, green: 0.34, blue: 0.48, alpha: 1), addText: UIColor(red: 0.00, green: 0.56, blue: 0.34, alpha: 1), - deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1) + deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1), + warningText: UIColor(red: 0.55, green: 0.36, blue: 0.00, alpha: 1), + warningBackground: UIColor(red: 1.00, green: 0.96, blue: 0.84, alpha: 1) ) } } @@ -350,6 +367,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { let onToggleViewedFile = EventDispatcher() let onPressLine = EventDispatcher() let onToggleComment = EventDispatcher() + let onPressNotice = EventDispatcher() let onPullToRefresh = EventDispatcher() private let pullRefreshControl = UIRefreshControl() @@ -383,6 +401,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { contentView.onToggleComment = { [weak self] commentId in self?.onToggleComment(["commentId": commentId]) } + contentView.onPressNotice = { [weak self] payload in + self?.onPressNotice(payload) + } contentView.onDrawMetrics = { [weak self] metrics in self?.emitDebug("draw-metrics", metrics) } @@ -1214,6 +1235,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { var onToggleViewedFile: ((String) -> Void)? var onPressLine: (([String: Any]) -> Void)? var onToggleComment: ((String) -> Void)? + var onPressNotice: (([String: Any]) -> Void)? var onDrawMetrics: (([String: Any]) -> Void)? private var stickyWidth: CGFloat { @@ -1555,6 +1577,11 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } + if row.kind == "notice", row.actionable == true { + onPressNotice?(["rowId": row.id, "fileId": resolvedFileId(for: row)]) + return + } + if row.kind == "line" { onPressLine?(linePressPayload(for: row, gesture: "tap")) return @@ -2200,7 +2227,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } - theme.background.setFill() + let warning = row.tone == "warning" + (warning ? theme.warningBackground : theme.background).setFill() context.fill(rect) let hairline = 1 / traitCollection.displayScale @@ -2214,7 +2242,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { width: iconSize, height: iconSize ) - drawNoticeIcon(rect: iconRect, color: theme.mutedText) + let noticeColor = warning ? theme.warningText : theme.mutedText + drawNoticeIcon(rect: iconRect, color: noticeColor) drawSingleLineText( row.text ?? "", @@ -2224,7 +2253,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { width: max(24, viewportWidth - iconRect.maxX - 10 - style.fileHeaderHorizontalPadding), height: fileHeaderSubtextFont.lineHeight ), - color: theme.mutedText, + color: noticeColor, font: fileHeaderSubtextFont ) } @@ -2554,6 +2583,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { NSRange(location: $0.start, length: $0.end - $0.start) }, color: (change == "add" ? theme.addBar : theme.deleteBar).withAlphaComponent(0.28), + note: row.noteStart.map { + ReviewDiffCodeNote( + range: NSRange(location: $0, length: max(0, text.length - $0)), + color: theme.warningText, + background: theme.warningBackground + ) + }, version: codeDecorationVersion ) layout.draw( diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift index d8f0b29ebc..1ed02e6a16 100644 --- a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift @@ -285,7 +285,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte didSet { guard oldValue != fontSize else { return } inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) - resetSurface() + applyConfigInPlace() } } @@ -321,14 +321,14 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte didSet { guard oldValue != appearanceScheme else { return } appearance = TerminalAppearanceScheme(value: appearanceScheme) - resetSurface() + applyConfigInPlace() } } var themeConfig: String = "" { didSet { guard oldValue != themeConfig else { return } - resetSurface() + applyConfigInPlace() } } @@ -663,7 +663,8 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte surfaceCreationFailed = true return } - loadThemeConfig(into: config) + // Creation proceeds without the file, as before; font_size is also set on the surface config. + _ = loadThemeConfig(into: config) ghostty_config_finalize(config) defer { ghostty_config_free(config) } @@ -710,6 +711,27 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte setNeedsLayout() } + // Font and theme change in place: a new surface would replay output and re-answer its queries. + private func applyConfigInPlace() { + guard let app, let surface else { + resetSurface() + return + } + guard let config = ghostty_config_new() else { return } + defer { ghostty_config_free(config) } + let loaded = loadThemeConfig(into: config) + ghostty_config_finalize(config) + ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme) + ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme) + tickApp() + // Without the file, the config lacks font-size and would reset the surface to defaults. + if loaded { + ghostty_surface_update_config(surface, config) + } + resizeSurface() + setNeedsLayout() + } + private func destroySurface() { // Unblock the io thread before ghostty_surface_free joins it. tickApp() @@ -933,16 +955,16 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte terminalViewport.backgroundColor = backgroundColorValue } - private func loadThemeConfig(into config: ghostty_config_t) { - guard let path = writeThemeConfigFile() else { return } + private func loadThemeConfig(into config: ghostty_config_t) -> Bool { + guard let path = writeThemeConfigFile() else { return false } path.withCString { cString in ghostty_config_load_file(config, cString) } + return true } private func writeThemeConfigFile() -> String? { - guard !themeConfig.isEmpty else { return nil } - let configContents = themeConfig + let configContents = "\(themeConfig)\nfont-size = \(String(format: "%g", Double(fontSize)))\n" let url = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty") diff --git a/apps/mobile/package.json b/apps/mobile/package.json index d33f37103b..1d0e5f4e00 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -9,6 +9,8 @@ "dev:client:reset": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --lan", "dev:client:preview-env": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=development expo start --dev-client --scheme t3code-dev --lan --port 0'", "dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --lan'", + "i18n:generate": "gt generate", + "i18n:translate": "gt translate", "start": "expo start", "start:dev": "APP_VARIANT=development expo start", "start:preview": "APP_VARIANT=preview expo start", @@ -47,6 +49,9 @@ "@expo-google-fonts/jetbrains-mono": "^0.4.1", "@expo/metro-runtime": "~58.0.17", "@expo/ui": "58.0.27", + "@formatjs/intl-displaynames": "6.8.13", + "@formatjs/intl-getcanonicallocales": "2.5.6", + "@formatjs/intl-locale": "4.2.13", "@legendapp/list": "catalog:", "@pierre/diffs": "catalog:", "@pierre/highlights": "catalog:", @@ -101,17 +106,18 @@ "expo-video": "58.0.13", "expo-web-browser": "~58.0.7", "expo-widgets": "58.0.27", + "gt-react-native": "11.4.18", "pele": "catalog:", "react": "catalog:", "react-dom": "catalog:", "react-native": "0.88.1", - "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.18-497fbe63.tgz", + "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz", "react-native-gesture-handler": "~3.5.0", "react-native-keyboard-controller": "1.23.0", "react-native-nitro-modules": "0.37.2", "react-native-reanimated": "4.7.1", "react-native-safe-area-context": "~5.11.1", - "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.48.tgz", + "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.58.tgz", "react-native-svg": "15.16.1", "react-native-webview": "14.0.1", "react-native-worklets": "0.13.1", @@ -131,6 +137,7 @@ "@types/react-dom": "catalog:", "aws4fetch": "1.0.20", "babel-preset-expo": "~58.0.24", + "gt": "2.27.0", "jsdom": "^30.0.1", "nitrogen": "0.37.2", "tailwindcss": "^4.0.0" diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 032fb37cd0..f0f91c87ac 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -7,7 +7,7 @@ import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery"; import * as Linking from "expo-linking"; import * as SplashScreen from "expo-splash-screen"; import { requireNativeModule } from "expo"; -import { useEffect } from "react"; +import { useEffect, useRef, useState } from "react"; import { Platform, StatusBar } from "react-native"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import { KeyboardProvider } from "react-native-keyboard-controller"; @@ -23,7 +23,7 @@ import { } from "@react-navigation/native"; import { pipe } from "effect/Function"; -import { RegistryContext } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages"; import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet"; import * as Dialog from "./components/ui/Dialog"; @@ -47,7 +47,7 @@ import { RootStack, rootPathnameFromState } from "./Stack"; import { appAtomRegistry } from "./state/atom-registry"; import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; -import { environmentShell } from "./state/shell"; +import { environmentShell, shellCachesReadAtom } from "./state/shell"; import { OverlayPortalHost } from "./components/ui/OverlayPortal"; import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking"; import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state"; @@ -74,7 +74,16 @@ import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordin import { DenseWidgetCoordinator } from "./widgets/DenseWidgetCoordinator"; import { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage"; import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl"; -import { restoreSettingsLinkState } from "./features/settings/settings-navigation"; +import { + launchSplashHomeRowsPending, + settleLaunchSplashHomeRows, + splashCanHide, + useLaunchSplashHomeRowsPending, +} from "./features/home/home-launch-splash"; +import { + restoreSettingsLinkState, + settingsLinkAction, +} from "./features/settings/settings-navigation"; import { hydrateWorkspaceSelections, launchWorkspaceURL, @@ -128,14 +137,16 @@ const appLinking = { getActionFromState: ( state: Parameters[0], options: Parameters[1], - ): ReturnType => - // Our router handles the selection; React Navigation's type only lists its own actions. - (workspaceDetailLinkAction(state) as ReturnType) ?? - pairingFormLinkAction( - state, - rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined, - ) ?? - getActionFromState(state, options), + ): ReturnType => { + const current = rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined; + return ( + // Our router handles the selection; React Navigation's type only lists its own actions. + (workspaceDetailLinkAction(state) as ReturnType) ?? + pairingFormLinkAction(state, current) ?? + settingsLinkAction(state, current) ?? + getActionFromState(state, options) + ); + }, getStateFromPath: getAppStateFromPath, }; @@ -157,6 +168,8 @@ function handleNavigationStateChange(state: NavigationState | undefined): void { resolvePendingNewTaskPromptLink(state); resolvePendingThreadPromptLink(state); if (!state) return; + // A launch that opens another route has no Home rows for the splash to wait for. + if (state.routes[state.index]?.name !== "Home") settleLaunchSplashHomeRows(); recordAppShortcutNavigationState(state); pruneNewTaskFlowStates(state); pruneNewTaskBranchCheckouts(state); @@ -193,13 +206,38 @@ disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.ho for (const dispose of appServiceDisposers) dispose(); }); +// Cached shells are local reads that end in a fraction of this time; the limit keeps a failed +// read, or a list that does not lay out, from holding the splash screen. +const SPLASH_WAIT_MS = 1_500; + function SplashScreenCoordinator() { const { isReady } = useAppearancePreferences(); + const shellCachesRead = useAtomValue(shellCachesReadAtom); + const homeRowsPending = useLaunchSplashHomeRowsPending(); + const [waitEnded, setWaitEnded] = useState(false); + const hidden = useRef(false); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the limit on how long the native splash screen waits for cached shells and their rows + useEffect(() => { + const timer = setTimeout(() => setWaitEnded(true), SPLASH_WAIT_MS); + return () => clearTimeout(timer); + }, []); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once appearance preferences have loaded + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once preferences have loaded and the cached rows are laid out useEffect(() => { - if (isReady) void SplashScreen.hide(); - }, [isReady]); + const canHide = splashCanHide({ + preferencesReady: isReady, + shellCachesRead, + // Home holds the splash in a layout effect of the commit that gives it rows. That can be + // this commit, after this render read the store. + homeRowsPending: homeRowsPending || launchSplashHomeRowsPending(), + waitEnded, + }); + if (!canHide || hidden.current) return; + hidden.current = true; + settleLaunchSplashHomeRows(); + void SplashScreen.hide(); + }, [isReady, shellCachesRead, homeRowsPending, waitEnded]); return null; } diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 65a79523cc..564f313703 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -94,6 +94,7 @@ import { SettingsProviderAccountsRouteScreen } from "./features/settings/Setting import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; +import { SettingsLanguageRouteScreen } from "./features/settings/SettingsLanguageRouteScreen"; import { SettingsEnvironmentMaintenanceRouteScreen, SettingsThreadsRouteScreen, @@ -252,6 +253,11 @@ const SETTINGS_SCREENS = { linking: "settings/organization", options: settingsPage("General"), }), + SettingsLanguage: createNativeStackScreen({ + screen: SettingsLanguageRouteScreen, + linking: "settings/language", + options: settingsPage("Language"), + }), SettingsProjectOverview: createNativeStackScreen({ screen: SettingsProjectOverviewRouteScreen, linking: "settings/project", @@ -470,11 +476,11 @@ const RootStackConfig = createWorkspaceStackNavigator({ Home: createNativeStackScreen({ screen: WorkspaceRootScreen, linking: "", - listeners: { + listeners: ({ navigation }) => ({ transitionStart: ({ data }) => recordHomeTransitionStart(data.closing), - transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing), + transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing, navigation.isFocused()), focus: recordHomeFocus, - }, + }), options: { ...pageRoute({ duoMinimize: "never", root: true }), contentStyle: { backgroundColor: "transparent" }, diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 49d30e06e4..66393de96b 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -18,6 +18,7 @@ import { type DraftComposerImageAttachment, } from "../lib/composerImages"; import { resolveOwnedComposerAttachmentFileUri } from "../lib/composerAttachmentFiles"; +import { rememberDraftImage } from "../lib/sentImageHandoff"; import { VideoAttachmentTile } from "./VideoAttachmentTile"; import { type MediaActionsSource } from "../lib/mediaActionsSource"; import { PresentationSource } from "./ui/NativePresentation"; @@ -161,6 +162,13 @@ function ComposerImageAttachment( style={style} className="bg-subtle" resizeMode="cover" + onLoad={({ nativeEvent: { source } }) => { + if (previewUri !== null) + rememberDraftImage(attachment.id, { + uri: previewUri, + aspectRatio: source.width / source.height, + }); + }} /> diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx index 5e4b0b82e3..81d1194393 100644 --- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx +++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx @@ -131,7 +131,7 @@ vi.mock("../features/settings/appearance/AppearancePreferencesProvider", () => ( useAppearancePreferences: () => ({ themeId: "t3-classic" }), })); vi.mock("../features/settings/appearance/useScaledTextRole", () => ({ - useScaledTextRole: () => ({ fontSize: 16, lineHeight: 22 }), + useComposerTextRole: () => ({ fontSize: 16, lineHeight: 22 }), })); vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" })); vi.mock("../state/assets", () => ({ assetEnvironment: {} })); diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index f7118b95b4..bae452bad7 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -76,7 +76,7 @@ export function ComposerEditor({ props.onChangeText(text); if (draftKey) { setComposerDraftContext(draftKey, restored.context); - appendComposerDraftAttachments(draftKey, restored.attachments, { allowOverflow: true }); + appendComposerDraftAttachments(draftKey, restored.attachments, { restore: true }); } }; const [selected, setSelected] = useState<{ source: string; start: number; end: number } | null>( diff --git a/apps/mobile/src/components/MediaVideoPlayer.tsx b/apps/mobile/src/components/MediaVideoPlayer.tsx index ea901f2441..8edd7b3d78 100644 --- a/apps/mobile/src/components/MediaVideoPlayer.tsx +++ b/apps/mobile/src/components/MediaVideoPlayer.tsx @@ -138,6 +138,7 @@ interface MediaVideoPlayerProps { readonly thumbnailVisible?: boolean; readonly visible?: boolean; readonly unavailable?: boolean; + readonly unavailableDetail?: string | undefined; readonly expanded?: boolean; /** Fill the parent and size the frame to the video's shape instead of a fixed 16:9 slot. */ readonly fitToVideo?: boolean; @@ -154,6 +155,9 @@ function MediaVideoPlayerContent(props: MediaVideoPlayerProps) { const [playbackUri, setPlaybackUri] = useState(props.expanded ? props.uri : null); // Keep an opened player mounted while signing or reconnecting temporarily has no usable URL. if (playbackUri === null && props.expanded && props.uri !== null) setPlaybackUri(props.uri); + const unavailableText = props.unavailableDetail + ? `Video unavailable. ${props.unavailableDetail}` + : "Video unavailable"; const [videoSize, setVideoSize] = useState<{ width: number; height: number } | null>(null); const [bounds, setBounds] = useState<{ width: number; height: number } | null>(null); const sizeSource = props.fitToVideo && isFocused && videoSize === null ? props.uri : null; @@ -201,7 +205,9 @@ function MediaVideoPlayerContent(props: MediaVideoPlayerProps) { 0 ? "Touch and hold for media actions" : undefined } @@ -223,7 +229,7 @@ function MediaVideoPlayerContent(props: MediaVideoPlayerProps) { /> ) : null} {props.unavailable ? ( - Video unavailable + {unavailableText} ) : props.uri === null ? ( ) : ( diff --git a/apps/mobile/src/components/PdfPreview.tsx b/apps/mobile/src/components/PdfPreview.tsx index 07ad774d57..6bbe24a3b3 100644 --- a/apps/mobile/src/components/PdfPreview.tsx +++ b/apps/mobile/src/components/PdfPreview.tsx @@ -3,6 +3,7 @@ import { View } from "react-native"; import { WebView } from "react-native-webview"; import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback"; +import { webViewDecelerationRate } from "../lib/webViewDecelerationRate"; export function PdfPreview(props: { readonly uri: string }) { const [error, setError] = useState(null); @@ -13,6 +14,7 @@ export function PdfPreview(props: { readonly uri: string }) { source={{ uri: props.uri }} originWhitelist={["*"]} automaticallyAdjustContentInsets={false} + decelerationRate={webViewDecelerationRate} contentInsetAdjustmentBehavior="never" startInLoadingState onError={(event) => diff --git a/apps/mobile/src/components/ProjectFavicon.test.tsx b/apps/mobile/src/components/ProjectFavicon.test.tsx index d948895181..44d0379b89 100644 --- a/apps/mobile/src/components/ProjectFavicon.test.tsx +++ b/apps/mobile/src/components/ProjectFavicon.test.tsx @@ -13,6 +13,9 @@ vi.mock("./ui/AppSymbol", () => ({ SymbolView: () => null })); vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, })); +vi.mock("../features/settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({ themeAppearance: "light" }), +})); vi.mock("../state/assets", async () => { const { Atom } = await import("effect/reactivity"); const url = Atom.make("https://example.test/favicon.png"); diff --git a/apps/mobile/src/components/ProjectFavicon.tsx b/apps/mobile/src/components/ProjectFavicon.tsx index 7d2b489755..44b7bc1c56 100644 --- a/apps/mobile/src/components/ProjectFavicon.tsx +++ b/apps/mobile/src/components/ProjectFavicon.tsx @@ -3,7 +3,7 @@ import { SymbolView } from "./ui/AppSymbol"; import { AppText } from "./ui/AppText"; import { Image } from "expo-image"; -import { memo, useLayoutEffect, useState } from "react"; +import { memo, useLayoutEffect, useMemo, useState } from "react"; import { View } from "react-native"; import type { EnvironmentId, ProjectIconOverride } from "@t3tools/contracts"; import { @@ -13,9 +13,9 @@ import { } from "@t3tools/shared/projectFavicon"; import { useAtomValue } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; +import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider"; import { projectFaviconUrlAtom } from "../state/assets"; import { finckeFolderTint } from "@t3tools/shared/fincke-folder-tint"; -import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider"; import { countGlyphs, projectAutoMonogram, @@ -24,6 +24,7 @@ import { resolveProjectIconSymbol, type ProjectIconGlyph, } from "../lib/projectIcon"; +import { resolveProjectFaviconColorScheme } from "../lib/projectFaviconColorScheme"; import { beginProjectFaviconRequest, @@ -174,6 +175,16 @@ function ProjectFaviconImage(props: { : "loading", ); + const { themeAppearance } = useAppearancePreferences(); + const requestFaviconUrl = faviconRequest?.faviconUrl; + const inlineFaviconUrl = useMemo( + () => + requestFaviconUrl?.startsWith("data:") + ? resolveProjectFaviconColorScheme(requestFaviconUrl, themeAppearance) + : null, + [requestFaviconUrl, themeAppearance], + ); + const showImage = faviconRequest !== null && status === "loaded"; const fallbackGlyph = showImage || props.fallbackColor ? null : projectAutoMonogram(props.projectTitle); @@ -203,11 +214,11 @@ function ProjectFaviconImage(props: { setLaidOut(true)} + source={laidOut ? thumbnail : null} style={StyleSheet.absoluteFill} contentFit={props.contentFit ?? "cover"} recyclingKey={cacheKey} accessible={false} /> - ) : null; + ); } diff --git a/apps/mobile/src/components/ui/AppBar.tsx b/apps/mobile/src/components/ui/AppBar.tsx index 7f76d91066..b691faa300 100644 --- a/apps/mobile/src/components/ui/AppBar.tsx +++ b/apps/mobile/src/components/ui/AppBar.tsx @@ -1,8 +1,8 @@ import { Toolbar } from "./Toolbar"; import { AppActivityIndicator } from "./AppActivityIndicator"; -import type { HeaderBarButtonMailSearchToolbarItem } from "react-native-screens"; -import { NavigationContext } from "@react-navigation/native"; -import { use, useId, useLayoutEffect } from "react"; +import type { HeaderBarButtonMailSearchToolbarItem, SearchBarCommands } from "react-native-screens"; +import { NavigationContext, NavigationRouteContext } from "@react-navigation/native"; +import { use, useId, useLayoutEffect, useRef, useSyncExternalStore } from "react"; import { View } from "react-native"; import { createNativeHeaderMenu } from "./nativeHeaderMenu.ios"; import { ScreenHeaderButton } from "./ScreenHeaderButton"; @@ -63,6 +63,17 @@ export function AppBar(props: AppBarProps) { ? { ...props.backInSplitView, onPress: splitBackPress } : null; const navigation = use(NavigationContext); + const route = use(NavigationRouteContext); + // A thread opened from another thread sits on it, not beside the list, so it keeps Back. + const threadBelow = useSyncExternalStore( + (onChange) => navigation?.addListener("state", onChange) ?? (() => {}), + () => { + const routes = navigation?.getState()?.routes; + const index = routes?.findIndex((candidate) => candidate.key === route?.key) ?? -1; + return route?.name === "Thread" && index > 0 && routes?.[index - 1]?.name === "Thread"; + }, + ); + const listBeside = layout.usesSplitView && props.onBackToList !== undefined && !threadBelow; const rootBack = !layout.usesSplitView && props.onBackToList && navigation?.canGoBack() === false ? props.onBackToList @@ -78,6 +89,19 @@ export function AppBar(props: AppBarProps) { const usesNativeMailSearchToolbar = useNativeMailSearchToolbar(); const { search, menus } = props; const menu = menus?.[0]; + const searchBarRef = useRef(null); + const nativeSearchText = useRef(search?.value ?? ""); + const searchValue = search?.value; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the native search bar keeps its own text; a value the caller changes (a reset) has to be pushed into it + useLayoutEffect(() => { + if (searchValue === undefined || searchValue === nativeSearchText.current) return; + nativeSearchText.current = searchValue; + searchBarRef.current?.setText(searchValue); + }, [searchValue]); + const reportSearchText = (text: string) => { + nativeSearchText.current = text; + search?.onChangeText(text); + }; const compactSearch = search !== undefined && (search.compactToolbar ?? !layout.usesSplitView) && @@ -100,7 +124,7 @@ export function AppBar(props: AppBarProps) { headerBackVisible: props.onClose === undefined && splitBack === null && - !(layout.usesSplitView && props.onBackToList) && + !listBeside && !(props.guardBack && props.onBack), ...(props.guardBack ? { gestureEnabled: false } : undefined), title: props.title, @@ -142,8 +166,9 @@ export function AppBar(props: AppBarProps) { ? { obscureBackground: false } : undefined), placeholder: search.placeholder, - onChangeText: (event) => search.onChangeText(event.nativeEvent.text), - onCancelButtonPress: () => search.onChangeText(""), + ref: searchBarRef, + onChangeText: (event) => reportSearchText(event.nativeEvent.text), + onCancelButtonPress: () => reportSearchText(""), }, } : undefined), diff --git a/apps/mobile/src/components/ui/AppBar.types.ts b/apps/mobile/src/components/ui/AppBar.types.ts index 88d711be71..071b060960 100644 --- a/apps/mobile/src/components/ui/AppBar.types.ts +++ b/apps/mobile/src/components/ui/AppBar.types.ts @@ -78,7 +78,10 @@ export interface AppBarProps { readonly titleContent?: ReactNode; readonly subtitle?: string | null; readonly actions?: ReadonlyArray; - /** Pull-to-refresh is the gesture on both platforms; Android also lists this in the overflow menu. */ + /** + * Pull-to-refresh is the gesture on both platforms. Android also lists this in the overflow + * menu, or shows it as a button in a bottom sheet, where the sheet owns the pull. + */ readonly refresh?: Pick; readonly menus?: ReadonlyArray; readonly search?: AppBarSearch; diff --git a/apps/mobile/src/components/ui/BottomSheetContext.ts b/apps/mobile/src/components/ui/BottomSheetContext.ts new file mode 100644 index 0000000000..c635f860e0 --- /dev/null +++ b/apps/mobile/src/components/ui/BottomSheetContext.ts @@ -0,0 +1,4 @@ +import { createContext } from "react"; + +/** True inside a draggable bottom sheet, which owns the downward drag at the top of its content. */ +export const BottomSheetContext = createContext(false); diff --git a/apps/mobile/src/components/ui/ContentBand.tsx b/apps/mobile/src/components/ui/ContentBand.tsx new file mode 100644 index 0000000000..cb6bca78fd --- /dev/null +++ b/apps/mobile/src/components/ui/ContentBand.tsx @@ -0,0 +1,44 @@ +import { View } from "react-native"; + +import { cn } from "../../lib/cn"; +import { AppActivityIndicator } from "./AppActivityIndicator"; +import { AppText as Text } from "./AppText"; +import type { ContentBandProps, ContentStatusProps } from "./ContentBand.types"; +export type { ContentBandProps, ContentStatusProps } from "./ContentBand.types"; + +/** A full-width band above or in place of content, ruled off from what follows. */ +export function ContentBand(props: ContentBandProps) { + return ( + + {props.children} + + ); +} + +export function ContentStatus(props: ContentStatusProps) { + if (props.loading) { + return ( + + + {props.detail} + + ); + } + return ( + + {props.title ? ( + {props.title} + ) : null} + {props.detail} + + ); +} + +/** The scroll content style for a ContentStatus with nothing else in the scroll view. */ +export const contentStatusContainerStyle = undefined; diff --git a/apps/mobile/src/components/ui/ContentBand.types.ts b/apps/mobile/src/components/ui/ContentBand.types.ts new file mode 100644 index 0000000000..95843c3e07 --- /dev/null +++ b/apps/mobile/src/components/ui/ContentBand.types.ts @@ -0,0 +1,15 @@ +import type { ReactNode } from "react"; + +export interface ContentBandProps { + readonly tone?: "card" | "warning"; + /** "roomy" for a band holding a block of content, such as a raw patch. */ + readonly spacing?: "compact" | "roomy"; + readonly children: ReactNode; +} + +/** A status at the top of otherwise empty content, such as "No changes" or a loading diff. */ +export interface ContentStatusProps { + readonly title?: string; + readonly detail: string; + readonly loading?: boolean; +} diff --git a/apps/mobile/src/components/ui/FilePreviewModal.tsx b/apps/mobile/src/components/ui/FilePreviewModal.tsx index aff82eae47..eba89cdb28 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.tsx +++ b/apps/mobile/src/components/ui/FilePreviewModal.tsx @@ -31,6 +31,7 @@ const NativeControls = requireNativeModule<{ ): Promise; updateFile(identifier: string, index: number, uri: string | null): Promise; dismissFile(identifier: string): Promise; + isFilePreviewFinished(identifier: string): boolean; }>("T3NativeControls"); // Null tells the viewer an image failed; undefined means its URL has not arrived yet. @@ -38,10 +39,11 @@ const nativeUri = (image: FilePreviewImage) => (image.failed ? null : image.uri) function NativeFilePreview(props: FilePreviewViewerProps) { const identifier = useId(); - // Later URLs reach the open viewer through updateFile instead of presenting again. + // Later URLs reach the native presentation through updateFile instead of presenting again. const [presented] = useState(props.source); const delivered = useRef<(string | null | undefined)[]>([]); const onRequestClose = useEffectEvent(props.onRequestClose); + const onPresent = useEffectEvent((isFinished: () => boolean) => props.onPresent?.(isFinished)); const onOpenError = useEffectEvent((error: unknown) => { if (props.onOpenError) props.onOpenError(error); else Dialog.alert("Could not open preview", "The file could not be loaded. Please try again."); @@ -51,7 +53,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) { useEffect(() => { let canceled = false; let presentation: Promise; - // Images open while still loading; other files must download first so Quick Look can refuse them. + // Images hand over before every URL resolves; other files must download first so Quick Look can refuse them. if (presented.kind === "image") { const { images, selectedIndex } = presented; delivered.current = images.map((image) => image.uri); @@ -71,6 +73,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) { identifier, ); } + onPresent(() => NativeControls.isFilePreviewFinished(identifier)); void presentation .catch((error: unknown) => { if (!canceled) onOpenError(error); diff --git a/apps/mobile/src/components/ui/FilePreviewModal.types.ts b/apps/mobile/src/components/ui/FilePreviewModal.types.ts index 37dd9ea9e1..4311776b0a 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.types.ts +++ b/apps/mobile/src/components/ui/FilePreviewModal.types.ts @@ -54,4 +54,6 @@ export interface FilePreviewViewerProps { readonly source: ResolvedFilePreviewSource; readonly onRequestClose: () => void; readonly onOpenError?: (error: unknown) => void; + /** Called once the viewer hands its file to a native presentation, with a check for its close. */ + readonly onPresent?: (isFinished: () => boolean) => void; } diff --git a/apps/mobile/src/components/ui/FilePreviewSession.test.tsx b/apps/mobile/src/components/ui/FilePreviewSession.test.tsx index a5b51aa5cf..8a38a70605 100644 --- a/apps/mobile/src/components/ui/FilePreviewSession.test.tsx +++ b/apps/mobile/src/components/ui/FilePreviewSession.test.tsx @@ -1,4 +1,4 @@ -import { act, useState } from "react"; +import { act, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import { expect, it, vi } from "vite-plus/test"; import { @@ -14,6 +14,7 @@ const harness = vi.hoisted(() => ({ alert: vi.fn(), previews: [] as unknown[], mounts: 0, + presentationFinished: false, })); vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl })); @@ -32,6 +33,9 @@ import { FilePreviewSession } from "./FilePreviewSession"; function Viewer(props: FilePreviewViewerProps) { useState(() => harness.mounts++); harness.previews.push(props.source); + const { onPresent } = props; + // Stands in for the native presentation starting. + useEffect(() => onPresent?.(() => harness.presentationFinished), [onPresent]); return null; } @@ -171,3 +175,70 @@ it("names the checked path when the server cannot find the file", async () => { ); expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i); }); + +it.each([ + // Handed to native but not yet started there, or still on screen. + ["image", false, 1], + ["image", true, 2], + // A PDF is still resolving here, so its viewer never presented and a re-render must not restart it. + ["pdf", true, 1], +] as const)( + "a re-tap of the open %s restarts the preview only once its native viewer closed (closed: %s)", + async (kind, finished, starts) => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + harness.presentationFinished = finished; + harness.mounts = 0; + harness.refreshAssetUrl.mockReset(); + if (kind === "image") harness.refreshAssetUrl.mockResolvedValue("https://signed.test/a.png"); + else harness.refreshAssetUrl.mockReturnValue(new Promise(() => {})); + const selected: FilePreviewItem = { ...image("https://github.com/a.png"), kind }; + const root = createRoot(document.createElement("div")); + await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) }; + const render = () => + act(async () => + root.render( + {}} + progressiveGallery + Viewer={Viewer} + />, + ), + ); + await render(); + await render(); + expect(harness.refreshAssetUrl).toHaveBeenCalledTimes(starts); + }, +); + +it("does not carry a presented viewer over to a different item that is still resolving", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + harness.presentationFinished = true; + harness.refreshAssetUrl.mockReset(); + harness.refreshAssetUrl.mockImplementation((_environmentId, resource) => + resource.url.endsWith("a.png") + ? Promise.resolve("https://signed.test/a.png") + : new Promise(() => {}), + ); + const shown = image("https://github.com/a.png"); + const resolving: FilePreviewItem = { ...image("https://github.com/b.pdf"), kind: "pdf" }; + const root = createRoot(document.createElement("div")); + await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) }; + const render = (item: FilePreviewItem) => + act(async () => + root.render( + {}} + progressiveGallery + Viewer={Viewer} + />, + ), + ); + await render(shown); + await render(resolving); + await render(resolving); + expect( + harness.refreshAssetUrl.mock.calls.filter(([, r]) => r.url.endsWith("b.pdf")), + ).toHaveLength(1); +}); diff --git a/apps/mobile/src/components/ui/FilePreviewSession.tsx b/apps/mobile/src/components/ui/FilePreviewSession.tsx index 5df8acf001..c9d950a3b5 100644 --- a/apps/mobile/src/components/ui/FilePreviewSession.tsx +++ b/apps/mobile/src/components/ui/FilePreviewSession.tsx @@ -11,7 +11,12 @@ import { } from "../../lib/attachmentDownload"; import { usePreviewPresentation } from "../../lib/previewPresentation"; import { refreshAssetUrl } from "../../state/assets"; -import { filePreviewGallery, filePreviewKey, filePreviewName } from "../../lib/filePreviewGallery"; +import { + filePreviewGallery, + filePreviewKey, + filePreviewName, + filePreviewSourceIdentifier, +} from "../../lib/filePreviewGallery"; import { FilePreviewGallery } from "./FilePreviewGallery"; import type { MediaActionsSource } from "../../lib/mediaActionsSource"; import type { @@ -97,6 +102,7 @@ function ResolvedFilePreview( readonly source: FilePreviewSource; readonly onRequestClose: () => void; readonly onOpenError?: (error: unknown) => void; + readonly onPresent: (isFinished: () => boolean) => void; }, ) { const { progressiveGallery, Viewer } = props; @@ -154,6 +160,7 @@ function ResolvedFilePreview( return { ...item, name: filePreviewName(item), + sourceIdentifier: filePreviewSourceIdentifier(item), ...(uri ? { uri } : uri === null ? { failed: true } : {}), }; }); @@ -161,6 +168,7 @@ function ResolvedFilePreview( ); @@ -205,6 +213,7 @@ function ResolvedFilePreview( }} onRequestClose={props.onRequestClose} onOpenError={onOpenError} + onPresent={props.onPresent} /> ); } @@ -220,15 +229,43 @@ export function FilePreviewSession(props: FilePreviewModalProps & FilePreviewSes ? null : { ...props.source, gallery: filePreviewGallery(props.source, group) }; usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose); + // A tap can land after the native viewer closed but before its close reached the caller, which + // still holds the same item; that tap only opens a new viewer under a new key. + // Only a viewer that presented and has since closed reopens; one still resolving never does. + const [opening, setOpening] = useState<{ + readonly source: FilePreviewModalProps["source"]; + readonly count: number; + readonly presented: { readonly isFinished: () => boolean } | null; + }>({ source: props.source, count: 0, presented: null }); + if (opening.source !== props.source) { + const sameItem = + opening.source !== null && + props.source !== null && + filePreviewKey(opening.source) === filePreviewKey(props.source); + const reopened = sameItem && opening.presented?.isFinished() === true; + setOpening({ + source: props.source, + count: opening.count + (reopened ? 1 : 0), + presented: sameItem && !reopened ? opening.presented : null, + }); + } + const { count } = opening; + const onPresent = (isFinished: () => boolean) => + setOpening((current) => + current.count === count && current.presented === null + ? { ...current, presented: { isFinished } } + : current, + ); if (!source) return null; return ( ); diff --git a/apps/mobile/src/components/ui/FitSheet.tsx b/apps/mobile/src/components/ui/FitSheet.tsx new file mode 100644 index 0000000000..f783dbcd96 --- /dev/null +++ b/apps/mobile/src/components/ui/FitSheet.tsx @@ -0,0 +1,68 @@ +import type { ReactNode } from "react"; +import { ScrollView, View } from "react-native"; +import { KeyboardAvoidingView } from "react-native-keyboard-controller"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { fitSheetBottomInset, type FitSheetProps } from "./FitSheet.types"; +import { ScreenContent } from "./ScreenContent"; +export type { FitSheetProps } from "./FitSheet.types"; + +export function FitSheet({ + header, + footer, + avoidsKeyboard, + children, + contentContainerClassName = "gap-4 px-5 pt-2", + contentContainerStyle, + ...scrollProps +}: FitSheetProps) { + const insets = useSafeAreaInsets(); + return ( + + {header} + + + {children} + + {footer ? ( + + {footer} + + ) : null} + + + ); +} + +function SheetContainer(props: { + readonly avoidsKeyboard?: boolean; + readonly children: ReactNode; +}) { + return props.avoidsKeyboard ? ( + + {props.children} + + ) : ( + + {props.children} + + ); +} diff --git a/apps/mobile/src/components/ui/FitSheet.types.ts b/apps/mobile/src/components/ui/FitSheet.types.ts new file mode 100644 index 0000000000..a47fb124ea --- /dev/null +++ b/apps/mobile/src/components/ui/FitSheet.types.ts @@ -0,0 +1,17 @@ +import type { ReactNode } from "react"; +import type { ScrollViewProps } from "react-native"; + +/** The body of a `sheetRoute({ androidFit: true })` screen: a header over one scrolling form. */ +export interface FitSheetProps extends Omit< + ScrollViewProps, + "children" | "className" | "nestedScrollEnabled" | "contentInsetAdjustmentBehavior" +> { + readonly header: ReactNode; + readonly children: ReactNode; + /** Submit actions, kept reachable below the form. */ + readonly footer?: ReactNode; + /** Lifts the sheet above the keyboard, for forms whose inputs sit low. */ + readonly avoidsKeyboard?: boolean; +} + +export const fitSheetBottomInset = (bottom: number) => Math.max(bottom, 18) + 18; diff --git a/apps/mobile/src/components/ui/FormSection.tsx b/apps/mobile/src/components/ui/FormSection.tsx new file mode 100644 index 0000000000..7f3e7a5d80 --- /dev/null +++ b/apps/mobile/src/components/ui/FormSection.tsx @@ -0,0 +1,20 @@ +import { View } from "react-native"; + +import { AppText as Text, AppTextInput as TextInput } from "./AppText"; +import type { FormFieldProps, FormSectionProps } from "./FormSection.types"; +export type { FormFieldProps, FormSectionProps } from "./FormSection.types"; + +export function FormSection(props: FormSectionProps) { + return ( + + + {props.title} + + {props.children} + + ); +} + +export function FormField({ label: _label, ...props }: FormFieldProps) { + return ; +} diff --git a/apps/mobile/src/components/ui/FormSection.types.ts b/apps/mobile/src/components/ui/FormSection.types.ts new file mode 100644 index 0000000000..4ef7015aa9 --- /dev/null +++ b/apps/mobile/src/components/ui/FormSection.types.ts @@ -0,0 +1,15 @@ +import type { ReactNode } from "react"; + +import type { AppTextInputProps } from "./AppText"; + +/** A titled card holding a short form: its fields and the action that submits them. */ +export interface FormSectionProps { + readonly title: string; + readonly children: ReactNode; +} + +export interface FormFieldProps extends Omit { + /** Shown where the platform labels fields; the placeholder carries it elsewhere. */ + readonly label?: string; + readonly accessibilityLabel: string; +} diff --git a/apps/mobile/src/components/ui/KeyboardSheetBody.tsx b/apps/mobile/src/components/ui/KeyboardSheetBody.tsx new file mode 100644 index 0000000000..c09e9f5ce7 --- /dev/null +++ b/apps/mobile/src/components/ui/KeyboardSheetBody.tsx @@ -0,0 +1,30 @@ +import { View } from "react-native"; +import { KeyboardAvoidingView } from "react-native-keyboard-controller"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import type { KeyboardSheetBodyProps } from "./KeyboardSheetBody.types"; +import { useBarOverlap } from "./useBarInset"; +export type { KeyboardSheetBodyProps } from "./KeyboardSheetBody.types"; + +/** A sheet's body that stays above the keyboard, with its toolbar between the two. */ +export function KeyboardSheetBody(props: KeyboardSheetBodyProps) { + const insets = useSafeAreaInsets(); + // The sheet's glass bar floats over its content, and only scroll views inset for it on their own. + const barOverlap = useBarOverlap(); + return ( + + + {props.children} + + {props.toolbar ? ( + {props.toolbar} + ) : null} + + ); +} diff --git a/apps/mobile/src/components/ui/KeyboardSheetBody.types.ts b/apps/mobile/src/components/ui/KeyboardSheetBody.types.ts new file mode 100644 index 0000000000..00c2ac30f3 --- /dev/null +++ b/apps/mobile/src/components/ui/KeyboardSheetBody.types.ts @@ -0,0 +1,7 @@ +import type { ReactNode } from "react"; + +export interface KeyboardSheetBodyProps { + readonly children: ReactNode; + /** A row of actions that rides the keyboard, such as attach and send. */ + readonly toolbar?: ReactNode; +} diff --git a/apps/mobile/src/components/ui/PaneListItem.tsx b/apps/mobile/src/components/ui/PaneListItem.tsx new file mode 100644 index 0000000000..4a43468729 --- /dev/null +++ b/apps/mobile/src/components/ui/PaneListItem.tsx @@ -0,0 +1,22 @@ +import { Pressable } from "react-native"; + +import type { PaneListItemProps } from "./PaneListItem.types"; +export type { PaneListItemProps } from "./PaneListItem.types"; + +/** A selectable entry in a pane's navigation list, such as a changed file. */ +export function PaneListItem(props: PaneListItemProps) { + return ( + + {props.children} + + ); +} diff --git a/apps/mobile/src/components/ui/PaneListItem.types.ts b/apps/mobile/src/components/ui/PaneListItem.types.ts new file mode 100644 index 0000000000..2f661883ea --- /dev/null +++ b/apps/mobile/src/components/ui/PaneListItem.types.ts @@ -0,0 +1,7 @@ +import type { ReactNode } from "react"; + +export interface PaneListItemProps { + readonly selected: boolean; + readonly onPress: () => void; + readonly children: ReactNode; +} diff --git a/apps/mobile/src/components/ui/PaneSheet.tsx b/apps/mobile/src/components/ui/PaneSheet.tsx new file mode 100644 index 0000000000..422635120c --- /dev/null +++ b/apps/mobile/src/components/ui/PaneSheet.tsx @@ -0,0 +1,21 @@ +import { View } from "react-native"; +import { FormSheet } from "react-native-screens"; +import { useResolveClassNames } from "uniwind"; + +import { BottomSheetContext } from "./BottomSheetContext"; +import type { PaneSheetProps } from "./PaneSheet.types"; +export type { PaneSheetProps } from "./PaneSheet.types"; + +/** A native sheet holding a pane that draws its own bar. */ +export function PaneSheet({ children, ...props }: PaneSheetProps) { + const containerStyle = useResolveClassNames("bg-sheet"); + return ( + + + + {children} + + + + ); +} diff --git a/apps/mobile/src/components/ui/PaneSheet.types.ts b/apps/mobile/src/components/ui/PaneSheet.types.ts new file mode 100644 index 0000000000..3b9bc86341 --- /dev/null +++ b/apps/mobile/src/components/ui/PaneSheet.types.ts @@ -0,0 +1,7 @@ +import type { ComponentProps } from "react"; +import type { FormSheet } from "react-native-screens"; + +export type PaneSheetProps = Omit< + ComponentProps, + "prefersGrabberVisible" | "preferredCornerRadius" | "nativeContainerStyle" +>; diff --git a/apps/mobile/src/components/ui/RefreshControl.tsx b/apps/mobile/src/components/ui/RefreshControl.tsx new file mode 100644 index 0000000000..02b2b648b7 --- /dev/null +++ b/apps/mobile/src/components/ui/RefreshControl.tsx @@ -0,0 +1,2 @@ +// oxlint-disable-next-line eslint/no-restricted-imports -- The wrapper every screen must use. +export { RefreshControl } from "react-native"; diff --git a/apps/mobile/src/components/ui/SecretRevealButton.tsx b/apps/mobile/src/components/ui/SecretRevealButton.tsx new file mode 100644 index 0000000000..2ba628eec1 --- /dev/null +++ b/apps/mobile/src/components/ui/SecretRevealButton.tsx @@ -0,0 +1,25 @@ +import { Pressable } from "react-native"; + +import { SymbolView } from "./AppSymbol"; + +/** Eye toggle that shows or hides a secret field's typed text. */ +export function SecretRevealButton(props: { + readonly revealed: boolean; + readonly onPress: () => void; +}) { + return ( + + + + ); +} diff --git a/apps/mobile/src/components/ui/SecretTextInput.tsx b/apps/mobile/src/components/ui/SecretTextInput.tsx index ed8bba58da..643fe5acbb 100644 --- a/apps/mobile/src/components/ui/SecretTextInput.tsx +++ b/apps/mobile/src/components/ui/SecretTextInput.tsx @@ -1,24 +1,35 @@ +import { useState } from "react"; +import { View } from "react-native"; + import { AppTextInput } from "./AppText"; +import { SecretRevealButton } from "./SecretRevealButton"; import type { SecretTextInputProps } from "./SecretTextInput.types"; /** Masked field for a value that must stay out of password managers and suggestions. */ export function SecretTextInput(props: SecretTextInputProps) { + const [revealed, setRevealed] = useState(false); return ( - props.onSubmitEditing(event.nativeEvent.text)} - /> + + props.onSubmitEditing(event.nativeEvent.text)} + /> + + setRevealed(!revealed)} /> + + ); } diff --git a/apps/mobile/src/components/ui/SheetIntro.tsx b/apps/mobile/src/components/ui/SheetIntro.tsx new file mode 100644 index 0000000000..a3b8e50744 --- /dev/null +++ b/apps/mobile/src/components/ui/SheetIntro.tsx @@ -0,0 +1,21 @@ +import { View } from "react-native"; + +import { AppText as Text } from "./AppText"; +import type { SheetIntroProps } from "./SheetIntro.types"; +export type { SheetIntroProps } from "./SheetIntro.types"; + +export function SheetIntro(props: SheetIntroProps) { + return ( + + {props.eyebrow ? ( + + {props.eyebrow} + + ) : null} + {props.title} + + {props.description} + + + ); +} diff --git a/apps/mobile/src/components/ui/SheetIntro.types.ts b/apps/mobile/src/components/ui/SheetIntro.types.ts new file mode 100644 index 0000000000..d9ed545d6b --- /dev/null +++ b/apps/mobile/src/components/ui/SheetIntro.types.ts @@ -0,0 +1,7 @@ +/** The lead of a decision sheet: what is being asked, above the choices. */ +export interface SheetIntroProps { + /** A short kicker such as "Confirm", where the platform uses one. */ + readonly eyebrow?: string; + readonly title: string; + readonly description: string; +} diff --git a/apps/mobile/src/components/ui/SheetPane.tsx b/apps/mobile/src/components/ui/SheetPane.tsx new file mode 100644 index 0000000000..f420964034 --- /dev/null +++ b/apps/mobile/src/components/ui/SheetPane.tsx @@ -0,0 +1,16 @@ +import { View } from "react-native"; + +import type { SheetPaneProps } from "./SheetPane.types"; +export type { SheetPaneProps } from "./SheetPane.types"; + +/** The root of a pane or sheet that draws an AppBar above its ScreenContent. */ +export function SheetPane(props: SheetPaneProps) { + return ( + + {props.children} + + ); +} diff --git a/apps/mobile/src/components/ui/SheetPane.types.ts b/apps/mobile/src/components/ui/SheetPane.types.ts new file mode 100644 index 0000000000..743ff1cae1 --- /dev/null +++ b/apps/mobile/src/components/ui/SheetPane.types.ts @@ -0,0 +1,7 @@ +import type { ReactNode } from "react"; + +export interface SheetPaneProps { + /** The iOS surface under the bar: a sheet's, or the screen's where the pane sits in a column. */ + readonly surface?: "sheet" | "screen"; + readonly children: ReactNode; +} diff --git a/apps/mobile/src/components/ui/listMetrics.ts b/apps/mobile/src/components/ui/listMetrics.ts new file mode 100644 index 0000000000..c7f8e2f2d2 --- /dev/null +++ b/apps/mobile/src/components/ui/listMetrics.ts @@ -0,0 +1,10 @@ +/** Minimum heights of tappable rows: a header control, and a list item. */ +export const ROW_MIN_HEIGHT = { control: 44, item: 44 } as const; + +/** Keeps a list at a readable width. iOS sheets and columns already bound it. */ +export const READABLE_WIDTH_STYLE = undefined; + +/** Insets for a scroll view of grouped list sections. */ +export function groupedListInsets(inInspector: boolean) { + return { paddingHorizontal: inInspector ? 12 : 20, gap: 14 }; +} diff --git a/apps/mobile/src/components/ui/useBarInset.ts b/apps/mobile/src/components/ui/useBarInset.ts index f00b64c8e0..3a917d67de 100644 --- a/apps/mobile/src/components/ui/useBarInset.ts +++ b/apps/mobile/src/components/ui/useBarInset.ts @@ -65,3 +65,18 @@ export function useSearchToolbarInset(search: AppBarSearch | undefined): number ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET : 0; } + +/** Where a sheet's scrolling content ends: clear of the bottom safe area, with a little room. */ +export function useSheetContentBottomInset(): number { + const insets = useSafeAreaInsets(); + const columnMetrics = useNativeColumnLayoutMetrics(); + return Platform.OS === "ios" + ? (columnMetrics?.safeArea.bottom ?? insets.bottom) + 8 + : Math.max(insets.bottom, 18) + 18; +} + +/** The bottom safe area a list in a sheet pads itself: Android's, which its sheets don't adjust for. */ +export function useUnadjustedBottomInset(): number { + const insets = useSafeAreaInsets(); + return Platform.OS === "android" ? insets.bottom : 0; +} diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts index e9a24552ce..1205c746e9 100644 --- a/apps/mobile/src/connection/environment-cache-store.test.ts +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -24,6 +24,7 @@ import * as Fiber from "effect/Fiber"; import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; import * as MobileDatabase from "../persistence/mobile-database"; import { make } from "./environment-cache-store"; @@ -567,7 +568,7 @@ describe("mobile SQLite environment cache store", () => { }), ); - it.live("returns cached threads before their pull request links, which load after", () => + it.effect("returns cached threads before their pull request links, which load after", () => Effect.gen(function* () { const memory = makeDatabase(); const store = yield* make().pipe( @@ -592,12 +593,13 @@ describe("mobile SQLite environment cache store", () => { const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID)); expect(shell.threads.map((thread) => thread.pullRequests)).toEqual([undefined, undefined]); - const links = yield* shell.loadPullRequests!; - expect([...links]).toEqual([[THREAD_ID, [link]]]); + const links = yield* Effect.forkChild(shell.loadPullRequests!); + yield* TestClock.adjust("1 millis"); + expect([...(yield* Fiber.join(links))]).toEqual([[THREAD_ID, [link]]]); }), ); - it.live("keeps cached threads when their pull request links cannot be read", () => { + it.effect("keeps cached threads when their pull request links cannot be read", () => { const messages: Array = []; const logger = Logger.make(({ message }) => { messages.push(message); @@ -633,7 +635,9 @@ describe("mobile SQLite environment cache store", () => { const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID)); expect(shell.threads.map((thread) => thread.id)).toEqual([THREAD_ID, readable.id]); - expect([...(yield* shell.loadPullRequests!)]).toEqual([[readable.id, [link]]]); + const links = yield* Effect.forkChild(shell.loadPullRequests!); + yield* TestClock.adjust("1 millis"); + expect([...(yield* Fiber.join(links))]).toEqual([[readable.id, [link]]]); expect(messages).toHaveLength(1); expect(memory.removed).toEqual([]); }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))); diff --git a/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts new file mode 100644 index 0000000000..efe489b0fd --- /dev/null +++ b/apps/mobile/src/connection/environment-owned-data-cleanup.test.ts @@ -0,0 +1,74 @@ +import { Persistence } from "@t3tools/client-runtime/platform"; +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; +import { vi } from "vite-plus/test"; + +const harness = vi.hoisted(() => ({ + clearOutbox: vi.fn<(environmentId: string) => Promise>(), + clearDrafts: vi.fn<(environmentId: string) => Promise>(), + clearComposerErrors: vi.fn(), +})); + +vi.mock("../state/thread-outbox-removal", () => ({ + clearThreadOutboxEnvironment: harness.clearOutbox, +})); +vi.mock("../state/use-composer-drafts", () => ({ + clearComposerDraftsEnvironment: harness.clearDrafts, +})); +vi.mock("../state/thread-composer-error", () => ({ + clearThreadComposerErrorsForEnvironment: harness.clearComposerErrors, +})); + +import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup"; + +const ENVIRONMENT_ID = EnvironmentId.make("environment-1"); + +describe("EnvironmentOwnedDataCleanup", () => { + it.effect("waits for the other clears and logs a bounded warning when one rejects", () => { + const warnings: Array = []; + let releaseDrafts = () => {}; + let draftsCleared = false; + // The drafts clear finishes only after the outbox failure is logged. + const logger = Logger.make(({ message }) => { + warnings.push(message); + releaseDrafts(); + }); + return Effect.gen(function* () { + harness.clearOutbox.mockRejectedValue(new Error("Some queued messages could not be read.")); + harness.clearDrafts.mockImplementation(() => + new Promise((resolve) => { + releaseDrafts = resolve; + }).then(() => { + draftsCleared = true; + }), + ); + + const cleanup = yield* Persistence.EnvironmentOwnedDataCleanup; + yield* cleanup.clear(ENVIRONMENT_ID); + + expect(draftsCleared).toBe(true); + expect(warnings).toEqual([ + [ + "Could not clear mobile environment-owned data.", + { + environmentId: ENVIRONMENT_ID, + operation: "outbox", + errorType: "error", + errorName: "Error", + stack: expect.any(String), + }, + ], + ]); + }).pipe( + Effect.provide( + Layer.merge( + EnvironmentOwnedDataCleanup.layer, + Logger.layer([logger], { mergeWithExisting: false }), + ), + ), + ); + }); +}); diff --git a/apps/mobile/src/connection/environment-owned-data-cleanup.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.ts new file mode 100644 index 0000000000..28c6cda29a --- /dev/null +++ b/apps/mobile/src/connection/environment-owned-data-cleanup.ts @@ -0,0 +1,48 @@ +import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; +import { Persistence } from "@t3tools/client-runtime/platform"; +import type { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error"; +import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal"; +import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts"; + +class EnvironmentOwnedDataClearError extends Schema.TaggedError()( + "EnvironmentOwnedDataClearError", + { cause: Schema.Defect() }, +) {} + +export const layer = Layer.succeed( + Persistence.EnvironmentOwnedDataCleanup, + Persistence.EnvironmentOwnedDataCleanup.of({ + clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) { + // Each clear settles on its own: a failure must not interrupt a clear that is still running. + const settle = ( + operation: "outbox" | "drafts", + clear: (environmentId: EnvironmentId) => Promise, + ) => + Effect.tryPromise({ + try: () => clear(environmentId), + catch: (cause) => new EnvironmentOwnedDataClearError({ cause }), + }).pipe( + Effect.catch((error) => + Effect.logWarning("Could not clear mobile environment-owned data.", { + environmentId, + operation, + ...safeErrorLogAttributes(error.cause), + }), + ), + ); + return Effect.all( + [ + settle("outbox", clearThreadOutboxEnvironment), + settle("drafts", clearComposerDraftsEnvironment), + Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)), + ], + { concurrency: "unbounded", discard: true }, + ); + }), + }), +); diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts index 5d71ea46dd..edf9bde99a 100644 --- a/apps/mobile/src/connection/platform.ts +++ b/apps/mobile/src/connection/platform.ts @@ -1,10 +1,6 @@ // apps/mobile/src/connection/platform.ts // supplies native client connectivity and authentication capabilities -import { - ClientCapabilities, - PlatformConnectionSource, - Persistence, -} from "@t3tools/client-runtime/platform"; +import { ClientCapabilities, PlatformConnectionSource } from "@t3tools/client-runtime/platform"; import { Connectivity, Wakeups } from "@t3tools/client-runtime/connection"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; @@ -18,10 +14,8 @@ import { AppState } from "react-native"; import { authClientMetadata } from "../lib/authClientMetadata"; import * as Runtime from "../lib/runtime"; -import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal"; -import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts"; -import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error"; import { mobileApplicationActiveWakeup } from "./app-state-wakeups"; +import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup"; import * as ConnectionStorage from "./storage"; function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" { @@ -168,22 +162,6 @@ const layerPlatformConnectionSource = Layer.succeed( const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer)); const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer)); -const layerEnvironmentOwnedDataCleanup = Layer.succeed( - Persistence.EnvironmentOwnedDataCleanup, - Persistence.EnvironmentOwnedDataCleanup.of({ - clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")((environmentId) => - Effect.all( - [ - Effect.promise(() => clearThreadOutboxEnvironment(environmentId)), - Effect.promise(() => clearComposerDraftsEnvironment(environmentId)), - Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)), - ], - { concurrency: "unbounded", discard: true }, - ), - ), - }), -); - type ConnectionPlatformLayerSource = | typeof layerProvidedConnectionStorage | typeof Runtime.layer @@ -191,7 +169,7 @@ type ConnectionPlatformLayerSource = | typeof layerWakeups | typeof layerProvidedCapabilities | typeof layerPlatformConnectionSource - | typeof layerEnvironmentOwnedDataCleanup; + | typeof EnvironmentOwnedDataCleanup.layer; export const layer: Layer.Layer< Layer.Success, @@ -204,5 +182,5 @@ export const layer: Layer.Layer< layerWakeups, layerProvidedCapabilities, layerPlatformConnectionSource, - layerEnvironmentOwnedDataCleanup, + EnvironmentOwnedDataCleanup.layer, ); diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.ts index 3c01c6d371..6cdec81732 100644 --- a/apps/mobile/src/connection/runtime.ts +++ b/apps/mobile/src/connection/runtime.ts @@ -41,6 +41,8 @@ const layerProvidedClientConnection = layerSnapshotLoader.pipe( usageLimitsCommand: true, hostAppUpdate: true, providerCatalogsOnDemand: true, + providerCatalogDigests: true, + providerStatusDeltas: true, }), ), Layer.provideMerge( diff --git a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx index c499e12b64..b312eeb645 100644 --- a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx +++ b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx @@ -10,6 +10,7 @@ import { Platform, TextInput, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { ControlPill } from "../../components/ui/ControlPill"; +import { useContentTopInset } from "../../components/ui/useBarInset"; import { useAppForeground } from "../../lib/appState"; import { useThreadServerBrowserTabs } from "../../state/preview"; @@ -34,16 +35,33 @@ type BrowserPreviewRouteScreenProps = StaticScreenProps<{ export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenProps) { const navigation = useNavigation(); const onClose = () => navigation.goBack(); + const { environmentId, threadId } = route.params; + if (!environmentId?.trim() || !threadId?.trim()) { + return ; + } return ( ); } +function BrowserUnavailableScreen({ onClose }: { readonly onClose: () => void }) { + const insets = useSafeAreaInsets(); + const contentTopInset = useContentTopInset(); + return ( + + + + ); +} + function BrowserPreviewScreen({ environmentId, threadId, @@ -56,6 +74,7 @@ function BrowserPreviewScreen({ readonly onClose: () => void; }) { const insets = useSafeAreaInsets(); + const contentTopInset = useContentTopInset(); const { themeVariables } = useAppearancePreferences(); const prepared = usePreparedConnection(environmentId); const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null; @@ -90,7 +109,10 @@ function BrowserPreviewScreen({ const live = (focused && foreground) || pictureInPicture.active; return ( - + ({ + started: 0, + interrupted: 0, + gate: Promise.resolve(), + open: () => {}, +})); + +vi.mock("@react-navigation/native", async () => { + const { createRequire } = await import("node:module"); + const { realpathSync } = await import("node:fs"); + const require = createRequire(import.meta.url); + const nativeRequire = createRequire( + realpathSync(require.resolve("@react-navigation/native/package.json")), + ); + // Use the shipped focus hook without importing the React Native view layer. + const { NavigationContext, useFocusEffect }: typeof import("@react-navigation/native") = + nativeRequire("@react-navigation/core"); + return { NavigationContext, useFocusEffect }; +}); +const appState = vi.hoisted(() => ({ listeners: new Set<(state: string) => void>() })); + +vi.mock("react-native", () => ({ + AppState: { + addEventListener: (_event: "change", listener: (state: string) => void) => { + appState.listeners.add(listener); + return { remove: () => appState.listeners.delete(listener) }; + }, + }, + View: ({ children }: { children?: ReactNode }) => children, +})); +vi.mock("../../components/ui/AppText", () => ({ + AppText: ({ children }: { children?: ReactNode }) => children, +})); +vi.mock("../settings/components/SettingsSection", () => ({ + SettingsSection: ({ children }: { children?: ReactNode }) => children, +})); +vi.mock("../../state/entities", () => ({ + useEnvironmentServerConfig: () => ({ + environment: { capabilities: { peerLinks: true } }, + settings: { linkedEnvironmentsEnabled: true }, + }), +})); +vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true })); +vi.mock("../../state/peerLinks", async () => { + const { Atom } = await import("effect/reactivity"); + const EffectModule = await import("effect/Effect"); + // Waits for the gate, as a list waits on its slowest linked machine. + const list = Atom.make( + EffectModule.gen(function* () { + fetches.started += 1; + yield* EffectModule.promise(() => fetches.gate); + return { links: [] }; + }).pipe( + EffectModule.onInterrupt(() => + EffectModule.sync(() => { + fetches.interrupted += 1; + }), + ), + ), + ); + return { peerLinkEnvironment: { list: () => list } }; +}); + +import { LinkedEnvironmentsSection } from "./LinkedEnvironmentsSection"; + +function createNavigation() { + const listeners = { focus: new Set<() => void>(), blur: new Set<() => void>() }; + let focused = true; + return { + value: { + isFocused: () => focused, + addListener: (event: keyof typeof listeners, listener: () => void) => { + listeners[event].add(listener); + return () => listeners[event].delete(listener); + }, + } as unknown as NavigationProp, + focus(next: boolean) { + focused = next; + act(() => { + for (const listener of listeners[next ? "focus" : "blur"]) listener(); + }); + }, + }; +} + +function setup() { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + fetches.started = 0; + fetches.interrupted = 0; + fetches.gate = new Promise((resolve) => { + fetches.open = resolve; + }); + const registry = AtomRegistry.make(); + const root = createRoot(document.createElement("div")); + const navigation = createNavigation(); + act(() => + root.render( + + + + + , + ), + ); + return { + focus: navigation.focus, + moveApp: (state: "active" | "background") => + act(() => { + for (const listener of appState.listeners) listener(state); + }), + settle: () => + act(async () => { + fetches.open(); + await fetches.gate; + }), + [Symbol.dispose]() { + act(() => root.unmount()); + registry.dispose(); + }, + }; +} + +it("asks again on focus only once the list it is waiting for has answered", async () => { + using screen = setup(); + // The first focus comes while the first fetch runs, which must not be cut and restarted. + expect(fetches).toMatchObject({ started: 1, interrupted: 0 }); + screen.focus(false); + screen.focus(true); + expect(fetches).toMatchObject({ started: 1, interrupted: 0 }); + + await screen.settle(); + screen.focus(false); + screen.focus(true); + expect(fetches).toMatchObject({ started: 2, interrupted: 0 }); +}); + +it("asks again when the app comes back to the front on this screen", async () => { + using screen = setup(); + await screen.settle(); + expect(fetches).toMatchObject({ started: 1, interrupted: 0 }); + fetches.gate = new Promise((resolve) => { + fetches.open = resolve; + }); + + screen.moveApp("background"); + screen.moveApp("active"); + expect(fetches).toMatchObject({ started: 2, interrupted: 0 }); + + // Coming back while that answer is still out must not cut it and start again. + screen.moveApp("background"); + screen.moveApp("active"); + expect(fetches).toMatchObject({ started: 2, interrupted: 0 }); +}); diff --git a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx index 9153c9fa6a..f447e27602 100644 --- a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx +++ b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx @@ -1,9 +1,10 @@ +import { RegistryContext } from "@effect/atom-react"; import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request"; import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks"; import { useFocusEffect } from "@react-navigation/native"; import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { useCallback, useState } from "react"; +import { useCallback, useContext, useState } from "react"; import { AppState, View } from "react-native"; import { AppText as Text } from "../../components/ui/AppText"; @@ -20,8 +21,25 @@ export function LinkedEnvironmentsSection(props: { const config = useEnvironmentServerConfig(props.environmentId); const canRead = useEnvironmentScope(props.environmentId, AuthAccessReadScope); const supported = canRead && offersLinkedEnvironments(config); - const links = useEnvironmentQuery( - supported ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) : null, + const listAtom = supported + ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) + : null; + const links = useEnvironmentQuery(listAtom); + const registry = useContext(RegistryContext); + // Links change outside this client, and the shared list only revalidates when built, so + // showing the screen and bringing the app back ask again. + useFocusEffect( + useCallback(() => { + if (listAtom === null) return; + const askAgain = () => { + if (!registry.get(listAtom).waiting) registry.refresh(listAtom); + }; + askAgain(); + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") askAgain(); + }); + return () => subscription.remove(); + }, [listAtom, registry]), ); const [nowMs, setNowMs] = useState(Date.now); const hasLinks = supported && (links.data?.links.length ?? 0) > 0; diff --git a/apps/mobile/src/features/connection/useConnectionController.ts b/apps/mobile/src/features/connection/useConnectionController.ts index 6c0d891c0d..cd0ad72c3b 100644 --- a/apps/mobile/src/features/connection/useConnectionController.ts +++ b/apps/mobile/src/features/connection/useConnectionController.ts @@ -16,7 +16,6 @@ export function useConnectionController() { }); const updateBearer = useAtomCommand(updateBearerConnection, { reportFailure: false }); const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove"); - const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry"); const setEnvironmentEnabledMutation = useAtomCommand( environmentCatalog.setEnabled, "environment toggle", @@ -32,8 +31,6 @@ export function useConnectionController() { ); const removeEnvironment = (environmentId: EnvironmentId) => removeEnvironmentMutation(environmentId); - const retryEnvironment = (environmentId: EnvironmentId) => - retryEnvironmentMutation(environmentId); const setEnvironmentEnabled = (environmentId: EnvironmentId, enabled: boolean) => setEnvironmentEnabledMutation({ environmentId, enabled }); const updateEnvironment = ( @@ -50,7 +47,6 @@ export function useConnectionController() { connectedEnvironments, connectPairingUrl, removeEnvironment, - retryEnvironment, setEnvironmentEnabled, updateEnvironment, }; diff --git a/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx b/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx new file mode 100644 index 0000000000..da94dedf2e --- /dev/null +++ b/apps/mobile/src/features/connection/useRetryEnvironment.test.tsx @@ -0,0 +1,108 @@ +import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId } from "@t3tools/contracts"; +import { + EnvironmentRegistry, + PrimaryConnectionTarget, + type ConnectionCatalogEntry, +} from "@t3tools/client-runtime/connection"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import { AtomRegistry } from "effect/reactivity"; +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; + +const fixture = vi.hoisted(() => ({ + environment: undefined as + | Pick< + EnvironmentRegistry.EnvironmentRegistry["Service"], + "entries" | "retryNow" | "setEnabled" + > + | undefined, +})); + +vi.mock("../../connection/runtime", async () => { + const { Atom } = await import("effect/reactivity"); + const Layer = await import("effect/Layer"); + const { EnvironmentRegistry } = await import("@t3tools/client-runtime/connection"); + return { + connectionAtomRuntime: Atom.runtime( + Layer.suspend(() => + Layer.succeed( + EnvironmentRegistry.EnvironmentRegistry, + fixture.environment as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"], + ), + ), + ), + }; +}); + +import { useRetryEnvironment } from "./useRetryEnvironment"; + +const environmentId = EnvironmentId.make("retry-environment"); + +describe("useRetryEnvironment", () => { + it.effect.each([ + { enabled: false, retries: 0 }, + { enabled: true, retries: 1 }, + ])("Retry now with the environment enabled: $enabled", ({ enabled, retries }) => + Effect.gen(function* () { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const target = new PrimaryConnectionTarget({ + environmentId, + label: "Retry", + httpBaseUrl: "https://retry.test", + wsBaseUrl: "wss://retry.test", + }); + const entries = yield* SubscriptionRef.make< + ReadonlyMap + >(new Map([[environmentId, { target, profile: Option.none(), enabled }]])); + let retryCount = 0; + fixture.environment = { + entries, + retryNow: () => + Effect.sync(() => { + retryCount += 1; + }), + setEnabled: (id, next) => + SubscriptionRef.update(entries, (current) => + new Map(current).set(id, { ...current.get(id)!, enabled: next }), + ), + }; + + const registry = AtomRegistry.make(); + const root = createRoot(document.createElement("div")); + using _mounted = { + [Symbol.dispose]() { + act(() => root.unmount()); + registry.dispose(); + }, + }; + let retryEnvironment!: ReturnType; + function Probe() { + const value = useRetryEnvironment(); + useLayoutEffect(() => { + retryEnvironment = value; + }); + return null; + } + yield* Effect.promise(async () => { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => { + await retryEnvironment(environmentId); + }); + }); + + const entry = (yield* SubscriptionRef.get(entries)).get(environmentId); + expect({ enabled: entry?.enabled, retries: retryCount }).toEqual({ enabled: true, retries }); + }), + ); +}); diff --git a/apps/mobile/src/features/connection/useRetryEnvironment.ts b/apps/mobile/src/features/connection/useRetryEnvironment.ts new file mode 100644 index 0000000000..b5d8edc749 --- /dev/null +++ b/apps/mobile/src/features/connection/useRetryEnvironment.ts @@ -0,0 +1,17 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId } from "@t3tools/contracts"; + +import { environmentCatalog } from "../../connection/catalog"; +import { useAtomCommand } from "../../state/use-atom-command"; + +export function useRetryEnvironment() { + const catalog = useAtomValue(environmentCatalog.catalogValueAtom); + const retryNow = useAtomCommand(environmentCatalog.retryNow, "environment retry"); + const setEnabled = useAtomCommand(environmentCatalog.setEnabled, "environment toggle"); + + return (environmentId: EnvironmentId) => + // A retry does nothing while the environment is switched off. + catalog.entries.get(environmentId)?.enabled === false + ? setEnabled({ environmentId, enabled: true }) + : retryNow(environmentId); +} diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx index 6c41d30185..e69ac15c61 100644 --- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx +++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx @@ -92,10 +92,10 @@ export function SettingsDiagnosticsRouteScreen() { {state.status === "loading" ? ( diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts index 6c2cb8f0d3..4950bb5ee4 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts @@ -39,13 +39,6 @@ it("evicts source text by aggregate size and returns an over-budget response unc expect(fetch).toHaveBeenCalledTimes(5); }); -it("lets later viewport requests retry a failed source fetch", async () => { - const fetch = vi.fn().mockRejectedValueOnce(new Error("Offline")).mockResolvedValueOnce(SOURCE); - const load = createNativeReviewDiffSourceLoader(fetch); - await expect(load("retry.ts")).rejects.toThrow("Offline"); - expect(await load("retry.ts")).toBe(SOURCE); -}); - const failureKeys = [ ["string", () => "retry.ts"], ["number", () => 1], diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts index 7f503239c2..4d73a7cda5 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts @@ -19,6 +19,7 @@ function permanentSourceFailureReason(error: unknown): string | undefined { if (name === "GitHubDiffFileContentsUnavailableError") return "github-source-unavailable"; for (const permanent of [ "provider-unsupported", + "repository-without-project", "unsupported", "oversized", "binary", diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx index 2d29be6d8b..8957f95c8a 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx @@ -219,6 +219,7 @@ function setup(integrated = false) { const onDebug: NonNullable = (event) => handlePullRequestDiffDebugEvent(event, { rowCount: data.rows.length, + lastShownRowIndex: data.rows.length - 1, targetFileId, focusIndex: -1, isIos: true, diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts index bf8c6e8e31..2699bb9954 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts @@ -47,6 +47,12 @@ export interface NativeReviewDiffRow { readonly commentText?: string; readonly commentRangeLabel?: string; readonly commentSectionTitle?: string; + /** A notice drawn in the warning colors. */ + readonly tone?: "warning"; + /** A notice that reports taps through `onPressNotice`. */ + readonly actionable?: boolean; + /** Where a cut line's note starts in `content`. */ + readonly noteStart?: number; } export interface NativeReviewDiffWordDiffRange { @@ -74,6 +80,8 @@ export interface NativeReviewDiffTheme { readonly deleteBar: string; readonly addText: string; readonly deleteText: string; + readonly warningText: string; + readonly warningBackground: string; } export interface NativeReviewDiffStyle { @@ -151,6 +159,9 @@ export interface NativeReviewDiffViewProps extends ViewProps { }>, ) => void; readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void; + readonly onPressNotice?: ( + event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>, + ) => void; } export interface NativeReviewDiffViewHandle { diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx index 1b36debb31..e23a0795e1 100644 --- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx +++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx @@ -7,7 +7,8 @@ import { getBrowseDirectoryPath } from "@t3tools/client-runtime/state/projects"; import { maskMarkdownFrontmatter } from "@t3tools/shared/markdownFrontmatter"; import { useState } from "react"; import { StackActions, useNavigation } from "@react-navigation/native"; -import { RefreshControl, ScrollView, View } from "react-native"; +import { ScrollView, View } from "react-native"; +import { RefreshControl } from "../../components/ui/RefreshControl"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { FONT_FAMILIES } from "../../lib/fontFamilies"; diff --git a/apps/mobile/src/features/files/FileTreeBrowser.tsx b/apps/mobile/src/features/files/FileTreeBrowser.tsx index 1901cc70a7..ac43523da0 100644 --- a/apps/mobile/src/features/files/FileTreeBrowser.tsx +++ b/apps/mobile/src/features/files/FileTreeBrowser.tsx @@ -7,7 +7,8 @@ import type { ProjectEntry } from "@t3tools/contracts"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { SymbolView } from "../../components/ui/AppSymbol"; import { useEffect, useRef, useState } from "react"; -import { Pressable, RefreshControl, View } from "react-native"; +import { Pressable, View } from "react-native"; +import { RefreshControl } from "../../components/ui/RefreshControl"; import { AppText as Text } from "../../components/ui/AppText"; import { PierreEntryIcon } from "../../components/PierreEntryIcon"; diff --git a/apps/mobile/src/features/files/SourceFileSurface.tsx b/apps/mobile/src/features/files/SourceFileSurface.tsx index 9ee512d9a1..6c796848b6 100644 --- a/apps/mobile/src/features/files/SourceFileSurface.tsx +++ b/apps/mobile/src/features/files/SourceFileSurface.tsx @@ -1,18 +1,19 @@ +import { LegendList, type LegendListRef } from "@legendapp/list/react-native"; import { settlePromise } from "@t3tools/client-runtime/state/runtime"; import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import type { ComponentType } from "react"; import { useLayoutEffect, useRef, useState } from "react"; import { - FlatList, Platform, Pressable, - RefreshControl, ScrollView, Text as NativeText, useWindowDimensions, View, } from "react-native"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { RefreshControl } from "../../components/ui/RefreshControl"; import { WebView } from "react-native-webview"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; @@ -43,7 +44,6 @@ import { selectableSourceHtml, } from "./source-file-document"; import { sourceHighlightAtom } from "./sourceHighlightingState"; -import { createSourceLineScroll } from "./source-file-scroll"; interface SourceFileSurfaceProps { readonly contents: string; @@ -270,8 +270,7 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) { const { codeSurface, codeWordBreak } = useAppearanceCodeSurface(); const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props); const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null; - const listRef = useRef>(null); - const [lineScroll] = useState(createSourceLineScroll); + const listRef = useRef(null); const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh); const refreshControl = props.onRefresh ? ( void handlePullToRefresh()} /> @@ -283,15 +282,21 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) { const usesTextSelection = props.selectable === true && !usesWebSelection; // Layout effect so a pending jump is cancelled in the commit that swaps the file. - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the FlatList to the target line and cancels a pending jump when the file changes + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the list to the target line and cancels a pending jump when the file changes useLayoutEffect(() => { if (targetIndex === null || !usesLineList) { return; } - lineScroll.scrollToLine(listRef.current, targetIndex); - return lineScroll.cancel; + const frame = requestAnimationFrame(() => { + void listRef.current?.scrollToIndex({ + index: targetIndex, + animated: false, + viewPosition: 0.3, + }); + }); + return () => cancelAnimationFrame(frame); // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening another file at the same line index, or leaving selection mode, scrolls the remounted list to it. - }, [lineScroll, props.path, targetIndex, usesLineList]); + }, [props.path, targetIndex, usesLineList]); const { onLongPressLine } = props; const renderLine = ({ item, index }: { item: string; index: number }) => ( @@ -385,33 +390,26 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) { ) : null; const list = ( - String(index)} - initialNumToRender={80} - maxToRenderPerBatch={80} - windowSize={12} - {...(codeWordBreak - ? {} - : { - getItemLayout: (_data, index) => ({ - length: codeSurface.rowHeight, - offset: codeSurface.rowHeight * index, - index, - }), - })} + extraData={{ tokens, targetIndex, codeSurface, codeWordBreak, onLongPressLine }} + estimatedItemSize={codeSurface.rowHeight} + getFixedItemSize={codeWordBreak ? undefined : () => codeSurface.rowHeight} + drawDistance={codeSurface.rowHeight * 40} + recycleItems contentContainerStyle={{ minWidth: codeWordBreak ? undefined : "100%", paddingBottom: codeSurface.rowHeight, paddingTop: 8, }} renderItem={renderLine} - onScrollToIndexFailed={lineScroll.onScrollToIndexFailed} - onScrollBeginDrag={lineScroll.cancel} /> ); diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index 11fa0a0c7a..6de31137fb 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -226,7 +226,7 @@ function FileSourceSurface(props: ComponentProps) { setSelection({ line, active: true }) : undefined } @@ -250,6 +250,7 @@ function FileContent(props: { readonly threadId: ThreadId | null; readonly initialLine: number | null; readonly truncated: boolean; + readonly selectable: boolean; readonly onRefresh?: () => Promise | void; }) { // Reopening a mutable host file must not reuse a poster from an earlier visit. @@ -351,6 +352,7 @@ function FileContent(props: { path={props.relativePath} initialLine={props.initialLine} headerInsetTop={props.truncated ? 0 : undefined} + selectable={props.selectable} onRefresh={props.onRefresh} /> )} @@ -650,6 +652,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { readonly path: string; readonly mode: FileViewMode; } | null>(null); + const [textSelectionPath, setTextSelectionPath] = useState(null); const [previewRevision, setPreviewRevision] = useState(0); const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]); const [fullScreenPreview, setFullScreenPreview] = useState(null); @@ -749,6 +752,10 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { : null, ); const fileData = fileQuery.data as ProjectReadFileResult | null; + // iOS only: Android lays out a whole-file selectable TextView on the UI thread, which stalls. + const canSelectText = + Platform.OS === "ios" && resolvedActiveMode === "source" && fileData?.contents != null; + const selectingText = canSelectText && textSelectionPath === relativePath; const handleSelectFile = (path: string) => { const targetPath = @@ -837,6 +844,15 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { onPress: () => setCodeWordBreak(!appearance.codeWordBreak), } as const) : null, + canSelectText + ? ({ + id: "select-text", + title: selectingText ? "Done selecting" : "Select text", + icon: "character.cursor.ibeam", + inline: false, + onPress: () => setTextSelectionPath(selectingText ? null : relativePath), + } as const) + : null, ...(mediaSource ? mediaActions.actions .filter(({ id }) => id !== "open-file") @@ -1046,6 +1062,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { relativePath={relativePath} threadId={threadId} truncated={fileData?.truncated ?? false} + selectable={selectingText} onRefresh={() => fileQuery.refresh()} /> diff --git a/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx index 63c3e7be0c..eccac90d9a 100644 --- a/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx +++ b/apps/mobile/src/features/files/WorkspaceFilePreviewError.tsx @@ -2,11 +2,10 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { View } from "react-native"; import { EmptyState } from "../../components/ui/EmptyState"; -import { environmentCatalog } from "../../connection/catalog"; import type { AssetUrlFailureReason } from "../../state/asset-url-state"; -import { useAtomCommand } from "../../state/use-atom-command"; import { useEnvironmentPresentation } from "../../state/presentation"; import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice"; +import { useRetryEnvironment } from "../connection/useRetryEnvironment"; export function WorkspaceFilePreviewError(props: { readonly environmentId: EnvironmentId | null; @@ -15,7 +14,7 @@ export function WorkspaceFilePreviewError(props: { }) { const { environmentId, onRetry } = props; const environment = useEnvironmentPresentation(environmentId); - const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry"); + const retryEnvironment = useRetryEnvironment(); const retryConnection = () => { if (environmentId !== null) void retryEnvironment(environmentId); onRetry(); diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx index e105d20824..b962d716b9 100644 --- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx +++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx @@ -11,6 +11,7 @@ import { PdfPreview } from "../../components/PdfPreview"; import { ControlPill } from "../../components/ui/ControlPill"; import { useHardwareBack } from "../../lib/backHandler"; import { isPdfPreviewUri } from "../../lib/pdfPreview"; +import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; import { useContentTopInset } from "../../components/ui/useBarInset"; export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) { @@ -58,9 +59,11 @@ function DocumentWebPreview(props: { readonly uri: string }) { source={{ uri: props.uri }} // react-native-webview defaults to "never", which starts the page under the header. contentInsetAdjustmentBehavior="automatic" + decelerationRate={webViewDecelerationRate} originWhitelist={["*"]} allowsBackForwardNavigationGestures allowsFullscreenVideo + allowsInlineMediaPlayback setSupportMultipleWindows={false} onShouldStartLoadWithRequest={(request) => { if (request.isTopFrame !== false && isPdfPreviewUri(request.url)) { diff --git a/apps/mobile/src/features/files/ZipArchiveView.tsx b/apps/mobile/src/features/files/ZipArchiveView.tsx index 9f5dbbec07..6187a051e1 100644 --- a/apps/mobile/src/features/files/ZipArchiveView.tsx +++ b/apps/mobile/src/features/files/ZipArchiveView.tsx @@ -667,8 +667,6 @@ function ZipEntryView(props: { () => { if (controller.signal.aborted) return; setBusy(null); - if (kind === "attach") - Dialog.alert("Added to chat", `${entry.name} is attached to your message.`); }, (cause: unknown) => { if (controller.signal.aborted) return; diff --git a/apps/mobile/src/features/files/filePath.test.ts b/apps/mobile/src/features/files/filePath.test.ts index 46b26d7e3b..75f46e23f1 100644 --- a/apps/mobile/src/features/files/filePath.test.ts +++ b/apps/mobile/src/features/files/filePath.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from "vite-plus/test"; import { fileRoutePathSegments, + isAudioPreviewFile, + isMarkdownPreviewFile, needsWorkspaceFileContents, resolveFileLinkPath, resolveWorkspaceRelativeFilePath, @@ -58,3 +60,21 @@ describe("needsWorkspaceFileContents", () => { expect(needsWorkspaceFileContents({ ...input, metadataKind: "directory" })).toBe(false); }); }); + +describe("workspace preview classifiers", () => { + it("recognize preview extensions and treat # and ? as literal filename characters", () => { + for (const path of ["notes/clip#1.wav", "notes/clip?1.wav", "notes#old/clip.wav"]) { + expect(isAudioPreviewFile(path)).toBe(true); + } + for (const path of [ + "docs/draft#1.md", + "docs/draft?1.md", + "docs#old/draft.md", + "CHANGELOG.markdown", + "notes.MDOWN", + "todo.mkd", + ]) { + expect(isMarkdownPreviewFile(path)).toBe(true); + } + }); +}); diff --git a/apps/mobile/src/features/files/filePath.ts b/apps/mobile/src/features/files/filePath.ts index e38ff86fa6..8e659280fd 100644 --- a/apps/mobile/src/features/files/filePath.ts +++ b/apps/mobile/src/features/files/filePath.ts @@ -100,15 +100,15 @@ export function isVideoPreviewFile(path: string): boolean { } export function isAudioPreviewFile(path: string): boolean { - return isWorkspaceAudioPreviewPath(path.split(/[?#]/, 1)[0] ?? ""); + return isWorkspaceAudioPreviewPath(path); } export function isSvgImagePreviewFile(path: string): boolean { - return /\.svg$/i.test(path.split(/[?#]/, 1)[0] ?? ""); + return /\.svg$/i.test(path); } export function isMarkdownPreviewFile(path: string): boolean { - return /\.(?:md|mdx)$/i.test(path.split(/[?#]/, 1)[0] ?? ""); + return /\.(?:md|mdx|markdown|mdown|mkd)$/i.test(path); } export function needsWorkspaceFileContents(input: { diff --git a/apps/mobile/src/features/files/source-file-scroll.test.ts b/apps/mobile/src/features/files/source-file-scroll.test.ts deleted file mode 100644 index 98fc4b6a2a..0000000000 --- a/apps/mobile/src/features/files/source-file-scroll.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { expect, it, vi } from "vite-plus/test"; - -import { createSourceLineScroll } from "./source-file-scroll"; - -const ROW_HEIGHT = 24; - -// Mirrors VirtualizedList.scrollToIndex without getItemLayout: indices past the highest -// measured cell fail, and unmeasured indices below it scroll to an averaged estimate. -function setup({ - lineCount = 1_203, - measuredThrough = 79, - rowHeight = (_index: number): number => ROW_HEIGHT, -} = {}) { - vi.useFakeTimers(); - vi.stubGlobal("requestAnimationFrame", (callback: () => void) => setTimeout(callback, 16)); - vi.stubGlobal("cancelAnimationFrame", (frame: ReturnType) => - clearTimeout(frame), - ); - const measured = new Set(); - const state = { - lineCount, - offset: 0, - measure(from: number, to: number) { - for (let index = from; index <= to; index += 1) measured.add(index); - }, - }; - state.measure(0, measuredThrough); - const offsetOf = (index: number) => { - let offset = 0; - for (let row = 0; row < index; row += 1) offset += rowHeight(row); - return offset; - }; - const averageItemLength = () => { - let total = 0; - for (const index of measured) total += rowHeight(index); - return total / measured.size; - }; - const scrollToIndex = vi.fn((params: { index: number }) => { - if (params.index < 0 || params.index >= state.lineCount) { - throw new Error(`scrollToIndex out of range: requested index ${params.index}`); - } - const highestMeasuredFrameIndex = Math.max(...measured); - if (params.index > highestMeasuredFrameIndex) { - scroll.onScrollToIndexFailed({ - index: params.index, - averageItemLength: averageItemLength(), - highestMeasuredFrameIndex, - }); - return; - } - state.offset = measured.has(params.index) - ? offsetOf(params.index) - : averageItemLength() * params.index; - }); - const scrollToOffset = vi.fn((params: { offset: number }) => { - state.offset = params.offset; - }); - const list = { - get props() { - return { data: { length: state.lineCount } }; - }, - scrollToIndex, - scrollToOffset, - }; - const scroll = createSourceLineScroll(); - return { - scroll, - list, - state, - offsetOf, - scrollToIndex, - scrollToOffset, - [Symbol.dispose]: () => { - vi.unstubAllGlobals(); - vi.useRealTimers(); - }, - }; -} - -it("lands on an already measured line", () => { - using t = setup(); - - t.scroll.scrollToLine(t.list, 40); - vi.runAllTimers(); - - expect(t.state.offset).toBe(t.offsetOf(40)); - expect(t.scrollToOffset).not.toHaveBeenCalled(); - expect(vi.getTimerCount()).toBe(0); -}); - -it("jumps near an unmeasured wrapped line, then lands on it once rows measure", () => { - using t = setup({ rowHeight: (index) => (index >= 80 ? ROW_HEIGHT * 3 : ROW_HEIGHT) }); - - t.scroll.scrollToLine(t.list, 899); - expect(() => vi.advanceTimersToNextTimer()).not.toThrow(); - expect(t.state.offset).toBeGreaterThan(0); - - // The render batch after the estimated jump measures rows past the target first, so - // the next scrollToIndex is accepted against an averaged estimate. - t.state.measure(900, 979); - vi.advanceTimersToNextTimer(); - expect(t.state.offset).not.toBe(t.offsetOf(899)); - - t.state.measure(820, 899); - vi.runAllTimers(); - - expect(t.state.offset).toBe(t.offsetOf(899)); - expect(vi.getTimerCount()).toBe(0); -}); - -it("stops retrying when the target never measures", () => { - using t = setup({ rowHeight: (index) => (index === 899 ? ROW_HEIGHT * 400 : ROW_HEIGHT) }); - - t.scroll.scrollToLine(t.list, 899); - expect(() => vi.runAllTimers()).not.toThrow(); - - expect(t.scrollToIndex.mock.calls.length).toBeLessThanOrEqual(10); - expect(vi.getTimerCount()).toBe(0); -}); - -it("ignores a line outside the document", () => { - using t = setup({ lineCount: 12 }); - - expect(() => t.scroll.scrollToLine(t.list, 899)).not.toThrow(); - vi.runAllTimers(); - expect(t.scrollToIndex).not.toHaveBeenCalled(); - expect(t.scrollToOffset).not.toHaveBeenCalled(); -}); - -it("drops a pending jump when the document shrinks or the jump is cancelled", () => { - using t = setup(); - - t.scroll.scrollToLine(t.list, 899); - vi.advanceTimersToNextTimer(); - t.state.lineCount = 12; - expect(() => vi.runAllTimers()).not.toThrow(); - - t.state.lineCount = 1_203; - t.scroll.scrollToLine(t.list, 899); - vi.advanceTimersToNextTimer(); - const calls = t.scrollToIndex.mock.calls.length; - t.scroll.cancel(); - t.state.measure(80, 999); - vi.runAllTimers(); - expect(t.scrollToIndex).toHaveBeenCalledTimes(calls); -}); - -it("a drag before the first frame cancels the jump", () => { - using t = setup(); - - t.scroll.scrollToLine(t.list, 40); - t.scroll.cancel(); - vi.runAllTimers(); - - expect(t.scrollToIndex).not.toHaveBeenCalled(); -}); diff --git a/apps/mobile/src/features/files/source-file-scroll.ts b/apps/mobile/src/features/files/source-file-scroll.ts deleted file mode 100644 index eb0f3dbd63..0000000000 --- a/apps/mobile/src/features/files/source-file-scroll.ts +++ /dev/null @@ -1,66 +0,0 @@ -interface SourceLineList { - readonly props: { readonly data?: { readonly length: number } | null }; - scrollToIndex(params: { index: number; animated: boolean; viewPosition: number }): void; - scrollToOffset(params: { offset: number; animated: boolean }): void; -} - -const RETRY_DELAY_MS = 100; -const MAX_RETRIES = 5; - -// Wrapped rows have no getItemLayout. VirtualizedList fails a jump past its highest measured -// row and silently estimates an unmeasured row below it, so re-aim until the budget runs out. -export function createSourceLineScroll() { - let list: SourceLineList | null = null; - let target: number | null = null; - let retries = 0; - let cancelPending: (() => void) | null = null; - - const cancel = () => { - cancelPending?.(); - cancelPending = null; - target = null; - }; - - const retry = () => { - if (retries >= MAX_RETRIES) { - target = null; - return; - } - retries += 1; - const timer = setTimeout(attempt, RETRY_DELAY_MS); - cancelPending = () => clearTimeout(timer); - }; - - const attempt = () => { - cancelPending = null; - if (target === null || !list || target >= (list.props.data?.length ?? 0)) { - target = null; - return; - } - list.scrollToIndex({ index: target, animated: false, viewPosition: 0.3 }); - // A failed jump has already scheduled its retry. - if (cancelPending === null) retry(); - }; - - return { - scrollToLine(nextList: SourceLineList | null, index: number) { - cancel(); - list = nextList; - if (!Number.isInteger(index) || index < 0) return; - target = index; - retries = 0; - const frame = requestAnimationFrame(attempt); - cancelPending = () => cancelAnimationFrame(frame); - }, - onScrollToIndexFailed(info: { - index: number; - averageItemLength: number; - highestMeasuredFrameIndex: number; - }) { - if (info.index !== target || !list) return; - list.scrollToOffset({ offset: info.averageItemLength * info.index, animated: false }); - retry(); - }, - cancel, - }; -} diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.test.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.test.tsx new file mode 100644 index 0000000000..21f64998a3 --- /dev/null +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.test.tsx @@ -0,0 +1,79 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const queries = vi.hoisted(() => [] as { cwd: string | null; searchQuery: string }[]); + +vi.mock("@t3tools/client-runtime/state/filesystem", () => ({ + resolveFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false }), +})); +vi.mock("../../state/session", () => ({ environmentSession: { sessionStateAtom: () => null } })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null, error: null }) })); +vi.mock("../../state/presentation", () => ({ + useEnvironmentPresentation: () => ({ isReady: true, presentation: null }), +})); +vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({ themeAppearance: "dark" }), +})); +vi.mock("./preload-workspace-file", () => ({ preloadWorkspaceFileContents: () => {} })); +vi.mock("./FileTreeBrowser", () => ({ FileTreeBrowser: () => null })); +vi.mock("./useFileTreeEntries", () => ({ + useFileTreeEntries: (input: { cwd: string | null; searchQuery: string }) => { + queries.push({ cwd: input.cwd, searchQuery: input.searchQuery }); + return { refresh: () => {}, selectPath: () => {} }; + }, +})); +vi.mock("../../components/ui/SheetPane", () => ({ + SheetPane: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../components/ui/AppBar", () => ({ + AppBar: (props: { search: { value: string; onChangeText: (value: string) => void } }) => ( + props.search.onChangeText(event.target.value)} + /> + ), +})); + +import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane"; + +it("starts unfiltered when the mounted pane switches to another workspace", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const container = document.body.appendChild(document.createElement("div")); + const root = createRoot(container); + const render = (cwd: string) => + act(() => + root.render( + {}} + />, + ), + ); + try { + render("/first"); + const input = container.querySelector("input")!; + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + "alpha", + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(queries.at(-1)).toEqual({ cwd: "/first", searchQuery: "alpha" }); + + render("/second"); + expect(queries.at(-1)).toEqual({ cwd: "/second", searchQuery: "" }); + expect(container.querySelector("input")!.value).toBe(""); + } finally { + act(() => root.unmount()); + container.remove(); + } +}); diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx index dd95959b30..cc0c86e6d3 100644 --- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -4,7 +4,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { AppBar } from "../../components/ui/AppBar"; import { ScreenContent } from "../../components/ui/ScreenContent"; import { useState } from "react"; -import { View } from "react-native"; +import { SheetPane } from "../../components/ui/SheetPane"; import { useEnvironmentQuery } from "../../state/query"; import { useEnvironmentPresentation } from "../../state/presentation"; @@ -20,7 +20,11 @@ export function ThreadFileNavigatorPane(props: { readonly selectedPath: string | null; readonly onSelectFile: (path: string) => void; }) { - const [searchQuery, setSearchQuery] = useState(""); + const workspaceKey = JSON.stringify([props.environmentId, props.cwd]); + // The pane stays mounted across thread switches; a query only filters the workspace it was typed in. + const [search, setSearch] = useState({ workspaceKey, query: "" }); + const searchQuery = search.workspaceKey === workspaceKey ? search.query : ""; + const setSearchQuery = (query: string) => setSearch({ workspaceKey, query }); const { themeAppearance: highlightTheme } = useAppearancePreferences(); const fileAccessSession = useEnvironmentQuery( environmentSession.sessionStateAtom(props.environmentId), @@ -48,7 +52,7 @@ export function ThreadFileNavigatorPane(props: { }; const fileTree = ( - {fileTree} + - + {fileTree} + ); } diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index d093dce9c4..e6c9411fd1 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -2,20 +2,15 @@ import { uuidv4 } from "../../lib/uuid"; import { ThreadUndoNotice } from "./ThreadUndoNotice"; import { use } from "react"; import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; -import * as Arr from "effect/Array"; -import * as Order from "effect/Order"; import { useNavigation } from "@react-navigation/native"; import { useMemo, useState } from "react"; import { Platform } from "react-native"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { - pickableProjectGroups, - resolveScratchProjectScopeKey, -} from "@t3tools/client-runtime/state/project-grouping"; +import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { useProjects } from "../../state/entities"; -import { environmentThreadShells } from "../../state/threads"; +import { steadyNavigationThreadShellsAtom } from "../../state/threads"; import { useLaunchingThreads, usePendingNewTasks } from "../../state/use-pending-new-tasks"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; @@ -25,8 +20,16 @@ import { } from "../layout/AdaptiveWorkspaceLayout"; import { HomeScreen } from "./HomeScreen"; import { useHomeListOptions } from "./home-list-options"; -import { useAtomValueWhileVisible, useHomeRouteVisible } from "./home-route-visibility"; -import { buildHomeProjectScopes } from "./homeThreadList"; +import { + runWhenHomeCovered, + useAtomValueWhileVisible, + useHomeRouteVisible, +} from "./home-route-visibility"; +import { + buildHomeProjectScopes, + resolveHomeProjectFilterScope, + sortHomeProjectScopes, +} from "./homeThreadList"; import { usePendingTaskListActions } from "./usePendingTaskListActions"; import { useThreadListActions } from "./useThreadListActions"; import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; @@ -35,7 +38,7 @@ import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; import { WorkspaceListEmptyDetail } from "../layout/workspace/WorkspaceListEmptyDetail"; import { WorkspaceListHeader } from "../layout/workspace/WorkspaceListHeader"; -import { buildHomeListFilterMenuItems } from "./home-list-filter-menu"; +import { buildHomeListFilterMenuItems, homeListFilterEnvironments } from "./home-list-filter-menu"; export function HomeRouteScreen() { const nativePrimaryColumn = use(NativePrimaryColumnContext); @@ -46,7 +49,7 @@ export function HomeRouteScreen() { // Stop rebuilding the streaming thread list while Thread covers Home. const visible = useHomeRouteVisible(); const threads = useLaunchingThreads( - useAtomValueWhileVisible(environmentThreadShells.navigationThreadShellsAtom, visible), + useAtomValueWhileVisible(steadyNavigationThreadShellsAtom, visible), ); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); const { savedConnectionsById } = useSavedRemoteConnections(); @@ -63,13 +66,15 @@ export function HomeRouteScreen() { else if (workspace) workspace.dispatch({ type: "query", query, tab: "threads" }); else setLocalSearchQuery(query); }; - const handleSelectThread = (thread: EnvironmentThreadShell) => - selectDetail({ - name: "Thread", - params: { environmentId: String(thread.environmentId), threadId: String(thread.id) }, - }); - const selectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) => + // Split layouts keep the query; only the stacked layout opens the thread over the list. + const clearsSearchOnOpen = !layout.usesSplitView; + const selectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) => { + if (searchQuery !== "" && clearsSearchOnOpen && workspace) + runWhenHomeCovered(() => workspace.cancelSearch("threads")); selectDetail({ name: "Thread", params }); + }; + const handleSelectThread = (thread: EnvironmentThreadShell) => + selectThreadRoute({ environmentId: String(thread.environmentId), threadId: String(thread.id) }); const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => { selectThreadRoute({ draft: { @@ -99,19 +104,7 @@ export function HomeRouteScreen() { const pendingTasks = usePendingNewTasks(); const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions(selectThreadRoute); - const connectionStateByEnvironmentId = new Map( - workspaceEnvironments.map( - (environment) => [environment.environmentId, environment.connectionState] as const, - ), - ); - const environments = 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), - ); + const environments = homeListFilterEnvironments(workspaceEnvironments); const availableEnvironmentIds = useMemo( () => new Set(environments.map((environment) => environment.environmentId)), [environments], @@ -122,35 +115,32 @@ export function HomeRouteScreen() { setSelectedProjectKey, } = useHomeListOptions(availableEnvironmentIds); const selectedEnvironmentId = listOptions.selectedEnvironmentId; - // A legacy per-environment scratch key resolves here on every render; the stored - // value is only rewritten when the user picks a filter. - const resolvedProjectKey = resolveScratchProjectScopeKey( - listOptions.selectedProjectKey, - projects, - { - sidebarProjectGroupingMode: listOptions.projectGroupingMode, - sidebarProjectGroupingOverrides: {}, - }, + const projectScopes = useMemo( + () => + buildHomeProjectScopes({ + projects, + environmentId: selectedEnvironmentId, + projectGroupingMode: listOptions.projectGroupingMode, + }), + [listOptions.projectGroupingMode, projects, selectedEnvironmentId], ); const projectFilterOptions = useMemo( () => pickableProjectGroups( - buildHomeProjectScopes({ - projects, - environmentId: selectedEnvironmentId, - projectGroupingMode: listOptions.projectGroupingMode, + sortHomeProjectScopes({ + scopes: projectScopes, + threads, + pendingTasks: [], + projectSortOrder: "updated_at", }), ).map((scope) => ({ key: scope.key, label: scope.title, })), - [listOptions.projectGroupingMode, projects, selectedEnvironmentId], + [projectScopes, threads], ); - const selectedProjectKey = projectFilterOptions.some( - (project) => project.key === resolvedProjectKey, - ) - ? resolvedProjectKey - : null; + const selectedProjectKey = + resolveHomeProjectFilterScope(projectScopes, projects, listOptions)?.key ?? null; if (layout.usesSplitView && !nativePrimaryColumn) { return ( @@ -230,6 +220,7 @@ export function HomeRouteScreen() { selectedEnvironmentId={selectedEnvironmentId} selectedProjectKey={selectedProjectKey} threads={threads} + visible={visible} /> diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 8dc0def978..3eb18af132 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -7,7 +7,7 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import type { ThreadMoveDestination } from "../threads/threadOrder"; import type { LegendListRef } from "@legendapp/list/react-native"; import { AnimatedLegendList } from "@legendapp/list/reanimated"; -import { THREAD_SIDEBAR_ROW_LAYOUT } from "../threads/threadListAnimations"; +import { THREAD_LIST_ROW_LAYOUT } from "../threads/threadListAnimations"; import { FinckeListHeader, finckeWaveTail } from "../../fincke/FinckeListHeader"; import { buildProjectSidebarItems, @@ -31,7 +31,15 @@ import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-gro import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; -import { use, useEffect, useMemo, useRef, useState, type ComponentProps } from "react"; +import { + use, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + type ComponentProps, +} from "react"; import { Platform, ScrollView, @@ -69,6 +77,7 @@ import { useThreadSearch } from "../../state/queries"; import { requestThreadMessageJump } from "../threads/threadMessageJump"; import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches"; import { useThreadListV2 } from "../threads/useThreadListV2"; +import { useSidebarRowThreadKey } from "../threads/useSidebarRowThreadKey"; import { useThreadListNow } from "../threads/use-thread-list-now"; import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration"; import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts"; @@ -104,10 +113,14 @@ import { import { createSwipeRowActivation } from "./swipe-row-activation"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions"; import { useFabScroll } from "./FabScrollContext"; +import { holdLaunchSplashForHomeRows, settleLaunchSplashHomeRows } from "./home-launch-splash"; import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; import { ThreadListFilters } from "./ThreadListFilters"; +import { deriveHomeEmptyState } from "./home-empty-state"; interface HomeScreenProps { + /** Whether this list is the one on screen; see `useHomeRouteVisible`. */ + readonly visible: boolean; readonly projects: ReadonlyArray; readonly threads: ReadonlyArray; readonly pendingTasks: ReadonlyArray; @@ -161,73 +174,6 @@ const ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT = 72; // rows that are already built instead of rows still being rebuilt. const THREAD_LIST_V2_DRAW_DISTANCE = 1_000; -function deriveEmptyState(props: { - readonly catalogState: WorkspaceState; - readonly projectCount: number; -}): { readonly title: string; readonly detail: string; readonly loading: boolean } { - const { catalogState } = props; - if (catalogState.isLoadingConnections) { - return { - title: "Loading environments", - detail: "Checking saved environments on this device.", - loading: true, - }; - } - - if (!catalogState.hasConnections) { - return { - title: "No environments connected", - detail: "Add an environment to load projects and start coding sessions.", - loading: false, - }; - } - - if ( - (catalogState.connectionState === "available" || - catalogState.connectionState === "offline" || - catalogState.connectionState === "error" || - catalogState.connectionState === "unsupported") && - !catalogState.hasLoadedShellSnapshot - ) { - return { - title: - catalogState.connectionState === "unsupported" - ? "Client not supported" - : "Environment unavailable", - detail: - catalogState.connectionError ?? - "The saved environment is offline. Check the URL or start the environment, then retry.", - loading: false, - }; - } - - if ( - catalogState.hasConnectingEnvironment && - !catalogState.hasLoadedShellSnapshot && - catalogState.connectionError === null - ) { - return { - title: "Connecting to environment", - detail: "Loading projects and threads from the saved environment.", - loading: true, - }; - } - - if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) { - return { - title: "No projects found", - detail: "The connected environment did not report any projects.", - loading: false, - }; - } - - return { - title: "No threads yet", - detail: "Create a task to start a new coding runtime in one of your connected projects.", - loading: false, - }; -} - function HomeTopContentSpacer() { return ; } @@ -267,7 +213,7 @@ function HomeScrollView(props: ComponentProps) { } function renderHomeScrollView(props: ScrollViewProps) { - // FlatList clones this with cells and ref; keep the marker inside their actual ScrollView. + // The list passes its content and ref in these props; keep the marker inside the real ScrollView. return ; } @@ -285,7 +231,8 @@ export function HomeScreen(props: HomeScreenProps) { ); const columnMetrics = useNativeColumnLayoutMetrics(); const activeNewTask = useActiveNewTask(); - const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null); + const sidebarRowThreadKey = useSidebarRowThreadKey(primaryColumn?.selectedThreadKey ?? null); + const selectedThreadKey = activeNewTask ? null : sidebarRowThreadKey; const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined; const queuedThreadKeys = useQueuedThreadKeys(); const openSwipeableRef = useRef(null); @@ -599,7 +546,6 @@ export function HomeScreen(props: HomeScreenProps) { selectedThreadKey) } project={projectByKey.get(pendingScopeKey) ?? null} - projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)} environmentLabel={ Object.keys(props.savedConnectionsById).length > 1 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? @@ -757,15 +703,18 @@ export function HomeScreen(props: HomeScreenProps) { props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0 || threadListV2Layout.settledCount > 0; + // A hidden list gets no layout, so it never reports its rows as laid out. + const hasRowsToLayOut = props.visible && hasAnyThreads && threadListV2Items.length > 0; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- holds the native launch splash, which is outside React, until the rows are gone or this list unmounts; a layout effect runs before the splash hides in this commit + useLayoutEffect(() => { + return hasRowsToLayOut ? holdLaunchSplashForHomeRows() : undefined; + }, [hasRowsToLayOut]); const selectedEnvironmentLabel = props.selectedEnvironmentId === null ? null : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ?? "this environment"); - const emptyState = deriveEmptyState({ - catalogState: props.catalogState, - projectCount: props.projects.length, - }); + const emptyState = deriveHomeEmptyState(props.catalogState, props.projects.length); if (!hasAnyThreads) { return ( @@ -788,14 +737,10 @@ export function HomeScreen(props: HomeScreenProps) { ({ + projects={pickableProjectGroups( + sortHomeProjectScopes({ + scopes: projectScopes, + threads: props.threads, + pendingTasks: [], + projectSortOrder: "updated_at", + }), + ).map((scope) => ({ key: scope.key, label: scope.title, }))} @@ -870,7 +822,13 @@ export function HomeScreen(props: HomeScreenProps) { ); const v2ListEmpty = - hasSearchQuery && threadSearch.isPending ? undefined : hasSearchQuery ? ( + hasSearchQuery && threadSearch.isPending ? ( + + ) : hasSearchQuery ? ( activateVisibleRows(threadListV2Items)} + onLoad={() => { + settleLaunchSplashHomeRows(); + activateVisibleRows(threadListV2Items); + }} onTouchStart={(event) => trackListTouches(event, true)} onTouchEnd={(event) => trackListTouches(event, false)} onTouchCancel={(event) => trackListTouches(event, false)} diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx index d8d2480a83..c8415808ae 100644 --- a/apps/mobile/src/features/home/ThreadUndoNotice.tsx +++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx @@ -49,7 +49,11 @@ export function ThreadUndoNotice(props: { readonly visible: boolean }) { const bottom = Platform.OS === "ios" ? foldedResting - ? Math.max(rootMetrics.safeArea.bottom, keyboardHeight) + 8 + ? // Sit level with the rail's tab pill, which floats inside the bottom safe area. + Math.max( + rootMetrics.bottomBarInset ?? rootMetrics.safeArea.bottom + 8, + keyboardHeight + 8, + ) : rootMetrics?.hasHinge && rootMetrics.verticalBarEdge !== "none" ? // The column's safe area already includes UIKit's search toolbar in this posture. workspaceSearchBottomClearance({ diff --git a/apps/mobile/src/features/home/home-empty-state.test.ts b/apps/mobile/src/features/home/home-empty-state.test.ts new file mode 100644 index 0000000000..013bb32a36 --- /dev/null +++ b/apps/mobile/src/features/home/home-empty-state.test.ts @@ -0,0 +1,103 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel"; +import { deriveHomeEmptyState } from "./home-empty-state"; + +function connectingEnvironment( + connectionState: "connecting" | "reconnecting", + connectionError: string | null, +): WorkspaceEnvironment { + return { + environmentId: EnvironmentId.make("environment-1"), + environmentLabel: "corex", + displayUrl: "", + isEnabled: true, + connectionState, + connectionError, + connectionErrorTraceId: null, + }; +} + +function workspaceState(overrides: Partial = {}): WorkspaceState { + return { + isLoadingConnections: false, + hasConnections: true, + hasLoadedShellSnapshot: true, + hasPendingShellSnapshot: false, + hasSyncingConnectedEnvironment: false, + hasReadyEnvironment: true, + hasConnectingEnvironment: false, + connectingEnvironments: [], + connectionState: "connected", + connectionError: null, + shellSnapshotError: null, + networkStatus: "online", + ...overrides, + }; +} + +const RETAINED_FAILURE = "Environment did not respond before the connection timeout."; +const reconnecting = connectingEnvironment("reconnecting", RETAINED_FAILURE); + +describe("home empty state", () => { + it.each([ + [ + "waits while a saved environment retries after a retained failure", + workspaceState({ + hasLoadedShellSnapshot: false, + hasPendingShellSnapshot: true, + hasReadyEnvironment: false, + hasConnectingEnvironment: true, + connectingEnvironments: [reconnecting], + connectionState: "reconnecting", + connectionError: RETAINED_FAILURE, + }), + 1, + { title: "Connecting to environment", loading: true, showsAddEnvironment: false }, + ], + [ + "waits for a connected environment's first shell snapshot", + workspaceState({ + hasLoadedShellSnapshot: false, + hasPendingShellSnapshot: true, + hasSyncingConnectedEnvironment: true, + }), + 0, + { title: "Loading threads", loading: true, showsAddEnvironment: false }, + ], + [ + "waits while another environment is still connecting after one loaded empty", + workspaceState({ + hasPendingShellSnapshot: true, + hasConnectingEnvironment: true, + connectingEnvironments: [reconnecting], + connectionError: RETAINED_FAILURE, + }), + 0, + { title: "Loading threads", loading: true, showsAddEnvironment: false }, + ], + [ + "reports no threads once every environment has resolved", + workspaceState(), + 1, + { title: "No threads yet", loading: false, showsAddEnvironment: false }, + ], + [ + "does not wait on retries while the device is offline", + workspaceState({ + hasPendingShellSnapshot: true, + hasReadyEnvironment: false, + hasConnectingEnvironment: true, + connectingEnvironments: [reconnecting], + connectionState: "offline", + networkStatus: "offline", + }), + 1, + { title: "No threads yet", loading: false, showsAddEnvironment: true }, + ], + ] as const)("%s", (_name, state, projectCount, expected) => { + const { title, loading, showsAddEnvironment } = deriveHomeEmptyState(state, projectCount); + expect({ title, loading, showsAddEnvironment }).toEqual(expected); + }); +}); diff --git a/apps/mobile/src/features/home/home-empty-state.ts b/apps/mobile/src/features/home/home-empty-state.ts new file mode 100644 index 0000000000..66f231a546 --- /dev/null +++ b/apps/mobile/src/features/home/home-empty-state.ts @@ -0,0 +1,81 @@ +import { isWorkspaceCatalogPending, type WorkspaceState } from "../../state/workspaceModel"; + +export interface HomeEmptyState { + readonly title: string; + readonly detail: string; + readonly loading: boolean; + readonly showsAddEnvironment: boolean; +} + +export function deriveHomeEmptyState( + catalogState: WorkspaceState, + projectCount: number, +): HomeEmptyState { + const emptyState = deriveEmptyState(catalogState, projectCount); + return { + ...emptyState, + showsAddEnvironment: !emptyState.loading && !catalogState.hasReadyEnvironment, + }; +} + +function deriveEmptyState( + catalogState: WorkspaceState, + projectCount: number, +): Omit { + if (catalogState.isLoadingConnections) { + return { + title: "Loading environments", + detail: "Checking saved environments on this device.", + loading: true, + }; + } + + if (!catalogState.hasConnections) { + return { + title: "No environments connected", + detail: "Add an environment to load projects and start coding sessions.", + loading: false, + }; + } + + if ( + (catalogState.connectionState === "available" || + catalogState.connectionState === "offline" || + catalogState.connectionState === "error" || + catalogState.connectionState === "unsupported") && + !catalogState.hasLoadedShellSnapshot + ) { + return { + title: + catalogState.connectionState === "unsupported" + ? "Client not supported" + : "Environment unavailable", + detail: + catalogState.connectionError ?? + "The saved environment is offline. Check the URL or start the environment, then retry.", + loading: false, + }; + } + + if (isWorkspaceCatalogPending(catalogState)) { + return { + title: catalogState.hasReadyEnvironment ? "Loading threads" : "Connecting to environment", + detail: "Loading projects and threads from the saved environment.", + loading: true, + }; + } + + if (projectCount === 0 && catalogState.hasLoadedShellSnapshot) { + return { + title: "No projects found", + detail: "The connected environment did not report any projects.", + loading: false, + }; + } + + return { + title: "No threads yet", + detail: "Create a task to start a new coding runtime in one of your connected projects.", + loading: false, + }; +} diff --git a/apps/mobile/src/features/home/home-launch-splash.test.ts b/apps/mobile/src/features/home/home-launch-splash.test.ts new file mode 100644 index 0000000000..d571811b33 --- /dev/null +++ b/apps/mobile/src/features/home/home-launch-splash.test.ts @@ -0,0 +1,70 @@ +import { expect, it, vi } from "vite-plus/test"; + +import { createLaunchSplashHomeRows, splashCanHide } from "./home-launch-splash"; + +const launched = { + preferencesReady: true, + shellCachesRead: true, + homeRowsPending: false, + waitEnded: false, +}; + +it.each([ + { + name: "hides when the cached shells are read and no rows wait for layout", + input: launched, + hides: true, + }, + { + name: "waits while Home still lays out the cached rows", + input: { ...launched, homeRowsPending: true }, + hides: false, + }, + { + name: "waits for the cached shells when Home has no rows yet", + input: { ...launched, shellCachesRead: false }, + hides: false, + }, + { + name: "stops waiting for rows at the limit", + input: { ...launched, homeRowsPending: true, waitEnded: true }, + hides: true, + }, + { + name: "stops waiting for a cache read that fails at the limit", + input: { ...launched, shellCachesRead: false, homeRowsPending: true, waitEnded: true }, + hides: true, + }, + { + name: "waits for preferences even after the limit", + input: { ...launched, preferencesReady: false, waitEnded: true }, + hides: false, + }, +])("the launch splash $name", ({ input, hides }) => { + expect(splashCanHide(input)).toBe(hides); +}); + +it("the launch splash is held only while a Home list has rows to lay out", () => { + const rows = createLaunchSplashHomeRows(); + const onChange = vi.fn(); + rows.subscribe(onChange); + + const release = rows.hold(); + expect(rows.pending()).toBe(true); + // The server answered with no rows, or the list unmounted, before its first layout. + release(); + expect(rows.pending(), "a list that lost its rows releases the splash").toBe(false); + expect(onChange).toHaveBeenCalledTimes(2); + + const releaseLater = rows.hold(); + const releaseOther = rows.hold(); + releaseLater(); + release(); + expect(rows.pending(), "another list still has rows to lay out").toBe(true); + + rows.settle(); + expect(rows.pending()).toBe(false); + releaseOther(); + rows.hold(); + expect(rows.pending(), "a list that mounts after the launch holds nothing").toBe(false); +}); diff --git a/apps/mobile/src/features/home/home-launch-splash.ts b/apps/mobile/src/features/home/home-launch-splash.ts new file mode 100644 index 0000000000..16069f051d --- /dev/null +++ b/apps/mobile/src/features/home/home-launch-splash.ts @@ -0,0 +1,75 @@ +import { useSyncExternalStore } from "react"; + +/** + * Whether the launch splash still waits for Home's list. A list holds the splash while it + * has cached rows to lay out, so the first frame after the splash shows them. + */ +export function createLaunchSplashHomeRows() { + let holds = 0; + let settled = false; + const listeners = new Set<() => void>(); + const pending = () => !settled && holds > 0; + const change = (apply: () => void) => { + const before = pending(); + apply(); + if (pending() !== before) for (const listener of listeners) listener(); + }; + return { + pending, + /** + * A Home list has rows that are not laid out yet. Call the returned release when it no + * longer has them or unmounts; rows that come later can hold again. + */ + hold: () => { + let held = true; + change(() => { + holds += 1; + }); + return () => { + if (!held) return; + held = false; + change(() => { + holds -= 1; + }); + }; + }, + /** + * The rows are laid out, the launch opened another route, or the splash is gone. It is + * final: lists that mount after the launch must not hold anything. + */ + settle: () => + change(() => { + settled = true; + }), + subscribe: (onChange: () => void) => { + listeners.add(onChange); + return () => { + listeners.delete(onChange); + }; + }, + }; +} + +const homeRows = createLaunchSplashHomeRows(); + +export const holdLaunchSplashForHomeRows = homeRows.hold; +export const settleLaunchSplashHomeRows = homeRows.settle; +export const launchSplashHomeRowsPending = homeRows.pending; + +export function useLaunchSplashHomeRowsPending(): boolean { + return useSyncExternalStore(homeRows.subscribe, homeRows.pending); +} + +/** + * Whether the native splash can hide: after the cached shells are read and Home's list has + * laid out their rows. One limit ends both waits. + */ +export function splashCanHide(input: { + readonly preferencesReady: boolean; + readonly shellCachesRead: boolean; + readonly homeRowsPending: boolean; + readonly waitEnded: boolean; +}): boolean { + if (!input.preferencesReady) return false; + return input.waitEnded || (input.shellCachesRead && !input.homeRowsPending); +} diff --git a/apps/mobile/src/features/home/home-list-filter-menu.test.ts b/apps/mobile/src/features/home/home-list-filter-menu.test.ts new file mode 100644 index 0000000000..050fbc1c83 --- /dev/null +++ b/apps/mobile/src/features/home/home-list-filter-menu.test.ts @@ -0,0 +1,34 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import type { WorkspaceEnvironment } from "../../state/workspaceModel"; +import { homeListFilterEnvironments } from "./home-list-filter-menu"; + +function environment( + environmentId: string, + environmentLabel: string, + isEnabled: boolean, +): WorkspaceEnvironment { + return { + environmentId: environmentId as EnvironmentId, + environmentLabel, + displayUrl: "", + isEnabled, + connectionState: isEnabled ? "connected" : "available", + connectionError: null, + connectionErrorTraceId: null, + }; +} + +it("offers only switched-on environments, sorted by label", () => { + expect( + homeListFilterEnvironments([ + environment("env-studio", "Studio", true), + environment("env-laptop", "Laptop", false), + environment("env-desk", "Desk", true), + ]), + ).toEqual([ + { environmentId: "env-desk", label: "Desk", connectionState: "connected" }, + { environmentId: "env-studio", label: "Studio", connectionState: "connected" }, + ]); +}); diff --git a/apps/mobile/src/features/home/home-list-filter-menu.ts b/apps/mobile/src/features/home/home-list-filter-menu.ts index 617c3fa098..1d6da0e8d7 100644 --- a/apps/mobile/src/features/home/home-list-filter-menu.ts +++ b/apps/mobile/src/features/home/home-list-filter-menu.ts @@ -1,12 +1,28 @@ import type { EnvironmentId } from "@t3tools/contracts"; +import * as Arr from "effect/Array"; +import * as Order from "effect/Order"; import type { AppBarMenuItem } from "../../components/ui/AppBar.types"; +import type { WorkspaceEnvironment } from "../../state/workspaceModel"; export interface HomeListFilterMenuEnvironment { readonly environmentId: EnvironmentId; readonly label: string; } +export function homeListFilterEnvironments(environments: ReadonlyArray) { + return Arr.sort( + environments + .filter((environment) => environment.isEnabled) + .map((environment) => ({ + environmentId: environment.environmentId, + label: environment.environmentLabel, + connectionState: environment.connectionState, + })), + Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label), + ); +} + export interface HomeListFilterMenuProject { readonly key: string; readonly label: string; diff --git a/apps/mobile/src/features/home/home-route-visibility.test.ts b/apps/mobile/src/features/home/home-route-visibility.test.ts new file mode 100644 index 0000000000..2ab23be17a --- /dev/null +++ b/apps/mobile/src/features/home/home-route-visibility.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { + recordHomeTransitionEnd, + recordHomeTransitionStart, + runWhenHomeCovered, +} from "./home-route-visibility"; + +vi.mock("@react-navigation/native", () => ({ useNavigation: vi.fn() })); + +describe("runWhenHomeCovered", () => { + it("waits for the page opening over Home to finish covering it, then runs once", () => { + const clearSearch = vi.fn(); + runWhenHomeCovered(clearSearch); + recordHomeTransitionStart(true); + expect(clearSearch).not.toHaveBeenCalled(); + recordHomeTransitionEnd(true, true); + expect(clearSearch).not.toHaveBeenCalled(); + recordHomeTransitionEnd(true, false); + expect(clearSearch).toHaveBeenCalledTimes(1); + recordHomeTransitionStart(false); + recordHomeTransitionEnd(true, false); + expect(clearSearch).toHaveBeenCalledTimes(1); + }); + + it("drops the action when Home reappears before it is covered", () => { + const clearSearch = vi.fn(); + runWhenHomeCovered(clearSearch); + recordHomeTransitionStart(true); + recordHomeTransitionStart(false); + recordHomeTransitionEnd(false, false); + recordHomeTransitionEnd(true, false); + expect(clearSearch).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/mobile/src/features/home/home-route-visibility.test.tsx b/apps/mobile/src/features/home/home-route-visibility.test.tsx new file mode 100644 index 0000000000..dae3994209 --- /dev/null +++ b/apps/mobile/src/features/home/home-route-visibility.test.tsx @@ -0,0 +1,137 @@ +import { RegistryContext } from "@effect/atom-react"; +import { Atom, AtomRegistry } from "effect/reactivity"; +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +import { + NativePrimaryColumnContext, + NativeWorkspaceTabActivityContext, +} from "../../native/v5-workspace-context"; + +// The Thread in the detail column is the focused route on iPad split view. +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ isFocused: () => false }), +})); + +import { + recordHomeFocus, + recordHomeTransitionEnd, + recordHomeTransitionStart, + useAtomValueWhileVisible, + useHomeRouteVisible, +} from "./home-route-visibility"; + +const shellsAtom = Atom.make(0).pipe(Atom.keepAlive); + +function setup() { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const registry = AtomRegistry.make(); + let latest: number | undefined; + function Probe() { + const visible = useHomeRouteVisible(); + const value = useAtomValueWhileVisible(shellsAtom, visible); + useLayoutEffect(() => { + latest = value; + }); + return null; + } + const root = createRoot(document.createElement("div")); + const sidebar = { + presented: true, + selectedThreadKey: "env-1:thread-1", + selectedPullRequestKey: null, + }; + return { + registry, + get latest() { + return latest; + }, + showHome() { + act(() => + root.render( + + + + + , + ), + ); + }, + /** A phone has no primary column: Home is the root page of its tab's slot. */ + showHomeInTabSlot(active: boolean) { + act(() => + root.render( + + active }}> + + + , + ), + ); + }, + [Symbol.dispose]() { + act(() => root.unmount()); + registry.dispose(); + }, + }; +} + +it("keeps the sidebar thread list live after switching tabs beside a focused Thread", () => { + using home = setup(); + // The primary column appearing is the only navigation event Home gets on iPad. + recordHomeTransitionStart(false); + home.showHome(); + act(() => home.registry.set(shellsAtom, 1)); + expect(home.latest).toBe(1); + + // Chats → PRs → Chats: Chats' column will-appear, then the PRs column's did-disappear. + act(() => { + recordHomeTransitionEnd(true, false); + recordHomeTransitionStart(false); + recordHomeTransitionEnd(true, false); + }); + act(() => home.registry.set(shellsAtom, 2)); + + expect(home.latest, "new thread shells reach the sidebar list").toBe(2); +}); + +// Each phone tab slot shows its own copy of the Home route. PRs keeps Home focused; Settings +// is a route of its own. +it.each([ + { tab: "PRs", homeFocusedUnderTab: true }, + { tab: "Settings", homeFocusedUnderTab: false }, +])( + "keeps the phone thread list live after a round trip through $tab", + ({ homeFocusedUnderTab }) => { + using home = setup(); + recordHomeFocus(); + home.showHomeInTabSlot(true); + act(() => home.registry.set(shellsAtom, 1)); + expect(home.latest).toBe(1); + + // To the other tab: its slot will-appear, then the Chats slot's did-disappear. + act(() => { + recordHomeTransitionStart(false); + recordHomeTransitionEnd(true, homeFocusedUnderTab); + }); + home.showHomeInTabSlot(false); + act(() => home.registry.set(shellsAtom, 2)); + expect(home.latest, "the list under another tab holds its rows").toBe(1); + + // Back to Chats: its slot will-appear, then the other slot's did-disappear comes last. + act(() => { + recordHomeFocus(); + recordHomeTransitionStart(false); + recordHomeTransitionEnd(true, true); + }); + home.showHomeInTabSlot(true); + act(() => home.registry.set(shellsAtom, 3)); + expect(home.latest, "a server rename reaches the list").toBe(3); + + // A pushed Thread takes the focus and still stops the list. + act(() => recordHomeTransitionEnd(true, false)); + act(() => home.registry.set(shellsAtom, 4)); + expect(home.latest, "the list under a Thread holds its rows").toBe(3); + }, +); diff --git a/apps/mobile/src/features/home/home-route-visibility.ts b/apps/mobile/src/features/home/home-route-visibility.ts index 5413ea1b1b..51bd292347 100644 --- a/apps/mobile/src/features/home/home-route-visibility.ts +++ b/apps/mobile/src/features/home/home-route-visibility.ts @@ -3,6 +3,11 @@ import { useNavigation } from "@react-navigation/native"; import { useContext, useRef, useSyncExternalStore } from "react"; import type { Atom } from "effect/reactivity"; +import { + NativePrimaryColumnContext, + NativeWorkspaceTabActivityContext, +} from "../../native/v5-workspace-context"; + /** * Home stays mounted under a pushed Thread, and native-stack never freezes the * route directly below the focused one on Fabric, so Home has to stop its own @@ -28,12 +33,29 @@ function subscribeHomeVisibility(onChange: () => void) { }; } +let onHomeCovered: (() => void) | null = null; + +/** Runs `action` once the page opening over Home covers it; Home starting to reappear first drops it. */ +export function runWhenHomeCovered(action: () => void): void { + onHomeCovered = action; +} + export function recordHomeTransitionStart(closing: boolean): void { - if (!closing) setHomeVisible(true); + if (closing) return; + onHomeCovered = null; + setHomeVisible(true); } -export function recordHomeTransitionEnd(closing: boolean): void { - if (closing) setHomeVisible(false); +/** + * Each iOS tab slot shows its own copy of the Home route, and the slot a tab switch leaves + * disappears last. So a disappear hides Home only when another route has the focus. + */ +export function recordHomeTransitionEnd(closing: boolean, homeFocused: boolean): void { + if (!closing || homeFocused) return; + setHomeVisible(false); + const action = onHomeCovered; + onHomeCovered = null; + action?.(); } /** Popping a sheet or a deep-linked route above Home has no appear event. */ @@ -43,7 +65,14 @@ export function recordHomeFocus(): void { export function useHomeRouteVisible(): boolean { const navigation = useNavigation(); + const primaryColumn = useContext(NativePrimaryColumnContext); + const tabActive = useContext(NativeWorkspaceTabActivityContext)?.active ?? true; const visible = useSyncExternalStore(subscribeHomeVisibility, () => homeVisible); + // Every tab slot's primary column reports to the one Home route, so a tab + // switch can end on the leaving slot's disappear. Trust this column instead. + if (primaryColumn) return primaryColumn.presented; + // The store is true for the Home route of every tab; this list shows in one of them. + if (!tabActive) return false; // Before Home's first navigation event: a cold deep link mounts Home under // its Thread without ever showing it. return visible ?? navigation.isFocused(); diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts index 1b2e1a8c54..7c03924976 100644 --- a/apps/mobile/src/features/home/homeThreadList.ts +++ b/apps/mobile/src/features/home/homeThreadList.ts @@ -1,4 +1,8 @@ -import { buildProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; +import { + buildProjectGroups, + pickableProjectGroups, + resolveScratchProjectScopeKey, +} from "@t3tools/client-runtime/state/project-grouping"; import type { EnvironmentProject, EnvironmentThreadShell, @@ -70,6 +74,24 @@ export function buildHomeProjectScopes(input: { }); } +/** The scope the thread list's project filter shows; an archived or unknown key shows all projects. */ +export function resolveHomeProjectFilterScope( + scopes: ReadonlyArray, + projects: ReadonlyArray, + options: { + readonly selectedProjectKey: string | null; + readonly projectGroupingMode: SidebarProjectGroupingMode; + }, +): HomeProjectScope | null { + // A legacy per-environment scratch key resolves here; the stored value is only + // rewritten when the user picks a filter. + const key = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { + sidebarProjectGroupingMode: options.projectGroupingMode, + sidebarProjectGroupingOverrides: {}, + }); + return pickableProjectGroups(scopes).find((scope) => scope.key === key) ?? null; +} + export function findHomeProjectScope( scopes: ReadonlyArray, key: string | null, diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx index 26db413b6e..e62f3c2cf2 100644 --- a/apps/mobile/src/features/home/thread-swipe-actions.tsx +++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx @@ -21,7 +21,7 @@ import type { StyleProp, ViewStyle, } from "react-native"; -import { Pressable, View } from "react-native"; +import { Pressable, View, useWindowDimensions } from "react-native"; import ReanimatedSwipeable, { type SwipeableMethods, } from "react-native-gesture-handler/ReanimatedSwipeable"; @@ -41,6 +41,7 @@ import Animated, { } from "react-native-reanimated"; import { AppText as Text } from "../../components/ui/AppText"; +import { useScaledTextRole } from "../settings/appearance/useScaledTextRole"; import { SwipeRowActivationContext, type SwipeRowActivation } from "./swipe-row-activation"; import { registerThreadDismissal } from "./thread-dismissal"; @@ -49,6 +50,10 @@ const ACTION_CIRCLE_SIZE = 36; const ACTION_ICON_SIZE = 15; const COMPACT_ACTION_CIRCLE_SIZE = 28; const COMPACT_ACTION_ICON_SIZE = 13; +// At the default app text size, "Unarchive", the longest label, fills its slot at about 1.12x. +const ACTION_LABEL_MAX_FONT_SCALE = 1.1; +const ACTION_LABEL_MIN_HEIGHT = 14; +const ACTION_LABEL_OFFSET = 2; const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2; const THREAD_SWIPE_SPRING = { @@ -79,6 +84,14 @@ function swipeActionsWidth(hasSecondaryAction: boolean) { return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH; } +function fullActionStackHeight(labelLineHeight: number, fontScale: number) { + const labelHeight = labelLineHeight * Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE); + // The offset shifts the label after centering, so it needs room on both sides. + return ( + ACTION_CIRCLE_SIZE + ACTION_LABEL_OFFSET * 2 + Math.max(ACTION_LABEL_MIN_HEIGHT, labelHeight) + ); +} + function resolveSecondaryAction(input: { readonly close: () => void; readonly onDelete: () => void; @@ -225,6 +238,8 @@ interface ThreadSwipeableProps { readonly fullSwipeWidth: number; /** One action behind the leading edge, committed by a full swipe right. */ readonly leadingAction?: ThreadSwipeAction; + /** The list animates item layout; collapse in one step so its transition moves siblings once. */ + readonly listAnimatesLayout?: boolean; readonly onDelete: () => void; readonly onSwipeableClose?: (methods: SwipeableMethods) => void; readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void; @@ -238,6 +253,8 @@ interface ThreadSwipeableProps { readonly threadTitle: string; } +const COLLAPSED_ROW_STYLE = { height: 0, overflow: "hidden" } as const; + export function ThreadSwipeable(props: ThreadSwipeableProps) { const swipeableRef = useRef(null); const hasSecondaryAction = props.secondaryAction !== null; @@ -259,6 +276,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { ); const contentRef = useRef(content); const [isDismissing, setIsDismissing] = useState(false); + const [collapsedInList, setCollapsedInList] = useState(false); const dismissing = useSharedValue(false); const rowHeight = useSharedValue(0); const rowWidth = useSharedValue(props.fullSwipeWidth); @@ -269,6 +287,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { const leadingAction = props.leadingAction; const onDelete = props.onDelete; const onSwipeableClose = props.onSwipeableClose; + const listAnimatesLayout = props.listAnimatesLayout === true; const restoreRow = useCallback(() => { if (!mountedRef.current) return; @@ -285,6 +304,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { dismissing.set(false); })(swipeableRef.current); setIsDismissing(false); + setCollapsedInList(false); }, [actionOpacity, collapse, dismissing, fallbackTranslation]); const finishDismiss = useCallback((id?: number) => { @@ -293,6 +313,14 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { pendingDismissRef.current = null; pending.resolve(); }, []); + const collapseInList = useCallback( + (id: number) => { + if (!mountedRef.current || pendingDismissRef.current?.id !== id) return; + setCollapsedInList(true); + finishDismiss(id); + }, + [finishDismiss], + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the row's Reanimated animations and settles a pending dismissal on unmount useLayoutEffect(() => { @@ -337,6 +365,12 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { translation.set( withTiming(Math.min(translation.value, -rowWidth.value), timing, (finished) => { if (!finished) return; + // LegendList re-measures rows only on React commits, so a UI-thread height animation + // reaches it in late jumps. Collapse through React and let its transition move rows. + if (listAnimatesLayout) { + runOnJS(collapseInList)(id); + return; + } collapse.set( withTiming(1, { ...timing, duration: 180 }, (collapsed) => { if (collapsed) runOnJS(finishDismiss)(id); @@ -345,7 +379,15 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { }), ); }, - [actionOpacity, collapse, dismissing, finishDismiss, rowWidth], + [ + actionOpacity, + collapse, + collapseInList, + dismissing, + finishDismiss, + listAnimatesLayout, + rowWidth, + ], ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this row's animated dismissal in the module-level thread dismissal registry useLayoutEffect( @@ -440,7 +482,12 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { const handleSwipeableClose = useCallback(() => { if (swipeableRef.current) onSwipeableClose?.(swipeableRef.current); }, [onSwipeableClose]); - const compactActions = props.compactActions === true; + const { fontScale } = useWindowDimensions(); + const fullActionsHeight = fullActionStackHeight(useScaledTextRole("micro").lineHeight, fontScale); + const [measuredRowHeight, setMeasuredRowHeight] = useState(0); + const compactActions = + props.compactActions === true || + (measuredRowHeight > 0 && measuredRowHeight < fullActionsHeight); const { secondaryAction, threadTitle } = props; // Swipeable calls this on every render; returning the previous element while nothing it shows // changed keeps a selection change from re-rendering the hidden actions. @@ -457,6 +504,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { actionStyle, backgroundColor, compactActions, + measuredRowHeight, fullSwipeAction, fullSwipeThreshold, handleFullSwipeArmedChange, @@ -480,6 +528,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { @@ -519,45 +569,48 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { ); return ( - - { - rowHeight.set(layout.height); - rowWidth.set(layout.width); - }} - > - + + { + rowHeight.set(layout.height); + setMeasuredRowHeight(layout.height); + rowWidth.set(layout.width); + }} > - { - /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */ - props.children(close) - /* oxlint-enable react/refs */ - } - - - + + { + /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */ + props.children(close) + /* oxlint-enable react/refs */ + } + + + + ); } @@ -572,6 +625,7 @@ function SwipeActionButton(props: { readonly label: string; readonly menu?: ThreadSwipeAction["menu"]; readonly onPress: () => void; + readonly rowHeight: number; /** Leading actions sit at the left edge, so they reveal and stretch in the mirrored direction. */ readonly side?: "leading" | "trailing"; readonly stretchesOnFullSwipe: boolean; @@ -587,6 +641,15 @@ function SwipeActionButton(props: { } = props; const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE; const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE; + const { fontScale } = useWindowDimensions(); + // Even compact actions can outgrow a short row at large app text sizes; shrink the label's + // leading to the room left under the circle. + const labelRoom = + props.compact && props.rowHeight > 0 + ? (props.rowHeight - circleSize) / Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE) + : Infinity; + const labelLineHeight = Math.min(useScaledTextRole("micro").lineHeight, labelRoom); + const labelTextStyle = { lineHeight: labelLineHeight }; const actionStyle = useAnimatedStyle(() => { const reveal = Math.max(-translation.value * direction, 0); const entryProgress = interpolate( @@ -718,13 +781,23 @@ function SwipeActionButton(props: { /> + {/* An offset, not padding: padding would grow the box and move the circle at 1x. */} - + {props.label} @@ -766,6 +839,7 @@ function ThreadLeadingSwipeAction(props: { readonly compact: boolean; readonly fullSwipeThreshold: number; readonly onFullSwipeArmedChange: (armed: boolean) => void; + readonly rowHeight: number; readonly translation: SharedValue; }) { const { fullSwipeThreshold, onFullSwipeArmedChange, translation } = props; @@ -797,6 +871,7 @@ function ThreadLeadingSwipeAction(props: { icon={props.action.icon} label={props.action.label} onPress={props.action.onPress} + rowHeight={props.rowHeight} side="leading" stretchesOnFullSwipe translation={translation} @@ -812,6 +887,7 @@ export function ThreadSwipeActions(props: { readonly fullSwipeThreshold: number; readonly onFullSwipeArmedChange: (armed: boolean) => void; readonly primaryAction: ThreadSwipeAction; + readonly rowHeight: number; readonly secondaryAction: ThreadSwipeSecondaryAction | null; readonly translation: SharedValue; }) { @@ -851,6 +927,7 @@ export function ThreadSwipeActions(props: { icon={props.primaryAction.icon} label={props.primaryAction.label} onPress={props.primaryAction.onPress} + rowHeight={props.rowHeight} stretchesOnFullSwipe={fullSwipeIsPrimary} translation={props.translation} /> @@ -866,6 +943,7 @@ export function ThreadSwipeActions(props: { label={secondaryAction.label} menu={secondaryAction.menu} onPress={secondaryAction.onPress} + rowHeight={props.rowHeight} stretchesOnFullSwipe={!fullSwipeIsPrimary} translation={props.translation} /> diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 26e93af335..45e5b7271d 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -7,6 +7,7 @@ import { ProviderInstanceId, RunId, ThreadId, + type ThreadTitleRegenerationOutcome, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; @@ -16,8 +17,11 @@ const state = vi.hoisted(() => ({ connectedEnvironmentIds: [] as EnvironmentId[], pendingOrder: null as object | null, dropBusy: false, + holdingRows: false, failedAction: null as string | null, + titleOutcome: null as ThreadTitleRegenerationOutcome | null, archivedRefreshes: [] as string[], + onArchivedRefresh: undefined as (() => void) | undefined, scopes: new Map>(), shells: [] as EnvironmentThreadShell[], requests: [] as { @@ -31,6 +35,7 @@ const state = vi.hoisted(() => ({ buttons?: { text: string; onPress?: () => void }[]; }[], afterRequest: undefined as (() => void) | undefined, + heldActions: new Map>(), })); vi.mock("react", () => ({ @@ -55,6 +60,7 @@ vi.mock("../../components/ui/Dialog", () => ({ vi.mock("../archive/useArchivedThreadSnapshots", () => ({ refreshArchivedThreadsForEnvironment: (environmentId: string) => { state.archivedRefreshes.push(environmentId); + state.onArchivedRefresh?.(); }, })); vi.mock("../../state/session", () => ({ @@ -67,8 +73,9 @@ vi.mock("../../state/presentation", () => ({ vi.mock("../../state/server", () => ({ environmentServerConfigsAtom: "server-configs", })); -vi.mock("../../state/atom-registry", () => ({ - appAtomRegistry: { +vi.mock("../../state/atom-registry", async () => { + const registry = (await import("effect/reactivity")).AtomRegistry.make(); + const stub = { set: (_atom: string, value: boolean) => { state.dropBusy = value; }, @@ -77,28 +84,43 @@ vi.mock("../../state/atom-registry", () => ({ ? state.connectedEnvironmentIds : atom === "thread-drop-busy" ? state.dropBusy - : atom === "thread-shells" - ? state.shells - : atom === "queued-thread-keys" - ? new Set() - : new Map( - [...state.scopes.keys()].map((environmentId) => [ - environmentId, - { - environment: { - capabilities: { - threadSettlement: true, - threadSnooze: true, - threadPinning: true, - threadPinReorder: true, - threadTitleRegeneration: true, + : atom === "steady-shells-holding" + ? state.holdingRows + : atom === "thread-shells" + ? state.shells + : atom === "queued-thread-keys" + ? new Set() + : new Map( + [...state.scopes.keys()].map((environmentId) => [ + environmentId, + { + environment: { + capabilities: { + threadSettlement: true, + threadSnooze: true, + threadPinning: true, + threadPinReorder: true, + threadTitleRegeneration: true, + }, }, }, - }, - ]), - ), - }, -})); + ]), + ), + }; + // Real atoms such as composerDraftsAtom go to a real registry; strings are stubbed state. + return { + appAtomRegistry: { + get: (atom: unknown) => + typeof atom === "string" + ? stub.get(atom) + : registry.get(atom as Parameters[0]), + set: (atom: unknown, value: unknown) => + typeof atom === "string" + ? stub.set(atom, value as boolean) + : registry.set(atom as Parameters[0], value), + }, + }; +}); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command, })); @@ -120,10 +142,9 @@ vi.mock("../../state/thread-order", () => ({ }, })); vi.mock("../../state/threads", () => ({ - environmentThreadShells: { - threadShellsAtom: "thread-shells", - navigationThreadShellsAtom: "thread-shells", - }, + environmentThreadShells: { threadShellsAtom: "thread-shells" }, + steadyNavigationThreadShellsAtom: "thread-shells", + steadyShellsHoldingAtom: "steady-shells-holding", threadEnvironment: Object.fromEntries( [ "archive", @@ -138,6 +159,7 @@ vi.mock("../../state/threads", () => ({ "reorderPin", "reorderActive", "updateMetadata", + "regenerateTitle", ].map((action) => [ action, async (request: { @@ -145,18 +167,21 @@ vi.mock("../../state/threads", () => ({ input: { threadId: string; orderKey?: string }; }) => { state.requests.push({ action, ...request }); + await state.heldActions.get(action); if (!state.scopes.get(request.environmentId)?.has(AuthOrchestrationOperateScope)) { return AsyncResult.failure(Cause.fail(new Error("Thread operation denied"))); } if (action === state.failedAction) return AsyncResult.failure(Cause.fail(new Error("Server rejected action"))); state.afterRequest?.(); - return AsyncResult.success(undefined); + return AsyncResult.success(action === "regenerateTitle" ? state.titleOutcome : undefined); }, ]), ), })); +import { appAtomRegistry } from "../../state/atom-registry"; +import { composerDraftsAtom } from "../../state/use-composer-drafts"; import { dismissThreadUndoNotice, readThreadUndoNotice } from "./thread-undo-notice"; import { useThreadListActions } from "./useThreadListActions"; @@ -182,15 +207,18 @@ const mutationCases = [ ["unsnoozeThread", "unsnooze"], ["pinThread", "pin"], ["unpinThread", "unpin"], - ["regenerateThreadTitle", "updateMetadata"], + ["regenerateThreadTitle", "regenerateTitle"], ] as const; beforeEach(() => { state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId]; state.failedAction = null; + state.titleOutcome = null; state.archivedRefreshes = []; + state.onArchivedRefresh = undefined; state.pendingOrder = null; state.dropBusy = false; + state.holdingRows = false; state.scopes = new Map([ [primaryEnvironmentId, new Set([AuthOrchestrationOperateScope])], [otherEnvironmentId, new Set()], @@ -200,6 +228,7 @@ beforeEach(() => { state.dialogs = []; state.alerts = []; state.afterRequest = undefined; + state.heldActions = new Map(); }); afterEach(() => { @@ -208,6 +237,16 @@ afterEach(() => { vi.unstubAllEnvs(); }); +it("reports a failed title generation as unsuccessful and allows another request", async () => { + const actions = useThreadListActions(); + const thread = makeThread(); + state.titleOutcome = { status: "failed", message: "Model unavailable" }; + expect(await actions.regenerateThreadTitle(thread)).toBe(false); + + state.titleOutcome = { status: "renamed" }; + expect(await actions.regenerateThreadTitle(thread)).toBe(true); +}); + describe("thread list operation permissions", () => { it.each(mutationCases)( "%s rejects a retained callback after its environment loses permission", @@ -230,7 +269,9 @@ describe("thread list operation permissions", () => { expect(state.requests).toEqual([]); }); - it("rechecks permission after a retained delete confirmation", async () => { + it("rechecks permission after a retained delete confirmation, then clears the draft", async () => { + const draft = { text: "unsent", attachments: [] }; + appAtomRegistry.set(composerDraftsAtom, { "primary:thread": draft, "primary:other": draft }); useThreadListActions().confirmDeleteThread(makeThread()); const confirm = state.dialogs[0]?.onConfirm; expect(confirm).toBeTypeOf("function"); @@ -239,6 +280,15 @@ describe("thread list operation permissions", () => { await confirm!(); expect(state.requests).toEqual([]); + expect(Object.keys(appAtomRegistry.get(composerDraftsAtom))).toContain("primary:thread"); + + state.scopes.get(primaryEnvironmentId)!.add(AuthOrchestrationOperateScope); + const deleted = new Promise((resolve) => (state.onArchivedRefresh = resolve)); + confirm!(); + await deleted; + + expect(state.requests).toEqual([expect.objectContaining({ action: "delete" })]); + expect(Object.keys(appAtomRegistry.get(composerDraftsAtom))).toEqual(["primary:other"]); }); }); @@ -271,6 +321,12 @@ describe("pinned thread operation permissions", () => { }), ]; + // Rows that wait to show can hold order keys the server has replaced. + state.holdingRows = true; + expect(await useThreadListActions().moveThread(moved, "up")).toBe(false); + expect(state.requests).toEqual([]); + state.holdingRows = false; + expect(await useThreadListActions().moveThread(moved, "up")).toBe(true); expect(state.requests).toEqual([ expect.objectContaining({ action: "reorderPin", environmentId: primaryEnvironmentId }), @@ -406,6 +462,23 @@ describe("thread action undo", () => { expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]); }); + it("sends a different action while one is pending for the same thread", async () => { + const actions = useThreadListActions(); + const thread = makeThread(); + const settleResponse = Promise.withResolvers(); + state.heldActions.set("settle", settleResponse.promise); + + const pending = [ + actions.settleThread(thread), + actions.unsettleThread(thread), + actions.settleThread(thread), + ]; + settleResponse.resolve(); + + expect(await Promise.all(pending)).toEqual([true, true, true]); + expect(state.requests.map(({ action }) => action)).toEqual(["settle", "unsettle", "settle"]); + }); + it("restores pin placement and snooze after settling, only once", async () => { const thread = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z", @@ -474,6 +547,25 @@ describe("thread action undo", () => { }, ); + it.each(["settleThread", "unpinThread"] as const)( + "%s plans its undo from the live row when the list holds an older one", + async (handler) => { + const held = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z", pinOrderKey: "m" }); + const live = makeThread({ + pinnedAt: "2026-09-02T00:00:00.000Z", + pinOrderKey: "t", + snoozedUntil: "2099-01-01T09:00:00.000Z", + }); + state.shells = [live]; + await useThreadListActions()[handler](held); + await readThreadUndoNotice()!.undo(); + expect(state.requests.slice(-2)).toMatchObject([ + { action: "pin", input: { threadId: live.id, orderKey: "t" } }, + { action: "snooze", input: { threadId: live.id, snoozedUntil: live.snoozedUntil } }, + ]); + }, + ); + // regression: #21401 restore archive and thread action undo it("does not restore snooze if undoing an unpin fails", async () => { const thread = makeThread({ @@ -533,11 +625,17 @@ describe("thread action undo", () => { expect(state.requests.map(({ action }) => action)).toEqual(["unpin"]); }); - // regression: #21401 restore archive and thread action undo - it("refreshes the archive after archiving on a settlement-capable server", async () => { - await useThreadListActions().archiveThread(makeThread()); - expect(state.requests.map(({ action }) => action)).toEqual(["archive"]); - expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]); + it("keeps the earlier Undo until archiving succeeds", async () => { + const actions = useThreadListActions(); + const thread = makeThread(); + await actions.settleThread(thread); + state.failedAction = "archive"; + expect(await actions.archiveThread(thread)).toBe(false); + expect(readThreadUndoNotice()?.action).toBe("Archived"); + + state.failedAction = null; + expect(await actions.archiveThread(thread)).toBe(true); + expect(readThreadUndoNotice()).toBeNull(); }); }); @@ -557,5 +655,10 @@ describe("thread archive guard", () => { expect(state.requests).toEqual([]); expect(state.archivedRefreshes).toEqual([]); expect(state.alerts.at(-1)?.title).toBe("Could not archive thread"); + + // A list can hold a row from before the run started. + state.shells = [thread]; + expect(await useThreadListActions().archiveThread(makeThread())).toBe(false); + expect(state.requests).toEqual([]); }); }); diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 9f16cd7fa8..54be9f87aa 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -17,7 +17,13 @@ import { appAtomRegistry } from "../../state/atom-registry"; import { environmentServerConfigsAtom } from "../../state/server"; import { connectedEnvironmentIdsAtom } from "../../state/presentation"; import { readEnvironmentScope } from "../../state/session"; -import { environmentThreadShells, threadEnvironment } from "../../state/threads"; +import { clearComposerDraft } from "../../state/use-composer-drafts"; +import { + environmentThreadShells, + steadyNavigationThreadShellsAtom, + steadyShellsHoldingAtom, + threadEnvironment, +} from "../../state/threads"; import { queuedThreadKeysAtom } from "../../state/use-thread-outbox"; import { useAtomCommand } from "../../state/use-atom-command"; import { @@ -83,6 +89,19 @@ function checkThreadOperationPermission(thread: EnvironmentThreadShell, title: s return false; } +/** + * The live row of a thread that a list passes to an action. A list holds its rows while an + * environment synchronizes (`steadyNavigationThreadShellsAtom`), so its row can be older than + * the client's data: an undo plan or a guard read from it would use replaced state. + */ +function liveThread(thread: EnvironmentThreadShell): EnvironmentThreadShell { + return ( + appAtomRegistry + .get(environmentThreadShells.threadShellsAtom) + .find((row) => row.id === thread.id && row.environmentId === thread.environmentId) ?? thread + ); +} + function useThreadActionExecutor( onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void, ) { @@ -91,20 +110,23 @@ function useThreadActionExecutor( const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false }); const settleMutation = useAtomCommand(threadEnvironment.settle, { reportFailure: false }); const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false }); - const inFlightThreadKeys = useRef(new Set()); + const latestPendingActions = useRef(new Map()); const executeAction = async ( action: ThreadListAction, thread: EnvironmentThreadShell, onStarted?: () => void, + restoreUnsettledAt?: string | null, ) => { if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false; const key = scopedThreadKey(thread.environmentId, thread.id); - if (inFlightThreadKeys.current.has(key)) { + // Drop only a repeat of the latest pending action; Settle → Un-settle → Settle must all send. + if (latestPendingActions.current.get(key)?.action === action) { return false; } - inFlightThreadKeys.current.add(key); + const pending = { action }; + latestPendingActions.current.set(key, pending); selectionHaptic(); const succeeded = await (async () => { if ( @@ -125,9 +147,6 @@ function useThreadActionExecutor( return false; } if (action === "unsettle") ThreadUndo.invalidate("settle", key); - if (action === "archive" || action === "delete") { - for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key); - } onStarted?.(); const result = await withThreadDismissal( key, @@ -137,7 +156,11 @@ function useThreadActionExecutor( // suppressed until real activity clears the pin server-side. await unsettleMutation({ environmentId: thread.environmentId, - input: { threadId: thread.id, reason: "user" }, + input: { + threadId: thread.id, + reason: "user", + ...(restoreUnsettledAt === undefined ? {} : { restoreUnsettledAt }), + }, }) : await ( action === "settle" @@ -157,13 +180,17 @@ function useThreadActionExecutor( Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause)); return false; } + if (action === "archive" || action === "delete") { + for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key); + } if (action === "archive" || action === "unarchive" || action === "delete") { refreshArchivedThreadsForEnvironment(thread.environmentId); } + if (action === "delete") clearComposerDraft(key); onCompleted?.(action, thread); return true; })(); - inFlightThreadKeys.current.delete(key); + if (latestPendingActions.current.get(key) === pending) latestPendingActions.current.delete(key); return succeeded; }; @@ -220,6 +247,9 @@ export function useThreadListActions(): { const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); + const regenerateTitle = useAtomCommand(threadEnvironment.regenerateTitle, { + reportFailure: false, + }); const snoozeInFlightThreadKeys = useRef(new Set()); const titleRegenerationInFlightThreadKeys = useRef(new Set()); @@ -240,11 +270,19 @@ export function useThreadListActions(): { async (step) => { switch (step.action) { case "unsettle": - return unsettleThread(thread); + return unsettleThread(thread, step.restoreUnsettledAt); case "unsnooze": return unsnoozeThread(thread); case "pin": return pinThread(thread, step.orderKey); + case "reorderActive": { + const result = await reorderActiveMutation({ + environmentId: thread.environmentId, + input: { threadId: thread.id, orderKey: step.orderKey }, + }); + if (result._tag === "Failure") throw Cause.squash(result.cause); + return true; + } case "snooze": { const failureTitle = action === "Unpinned" ? "Could not undo unpin" : "Could not undo archive"; @@ -388,8 +426,10 @@ export function useThreadListActions(): { snoozeInFlightThreadKeys.current.delete(key); return succeeded; }; - const unsettleThread = async (thread: EnvironmentThreadShell) => - (await executeAction("unsettle", thread)) === true; + const unsettleThread = async ( + thread: EnvironmentThreadShell, + restoreUnsettledAt?: string | null, + ) => (await executeAction("unsettle", thread, undefined, restoreUnsettledAt)) === true; const pinThread = async (thread: EnvironmentThreadShell, restoreOrderKey?: string) => { if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false; if (!environmentConfigLoaded(thread.environmentId)) { @@ -509,9 +549,9 @@ export function useThreadListActions(): { titleRegenerationInFlightThreadKeys.current.add(key); selectionHaptic(); const succeeded = await (async () => { - const result = await updateThreadMetadata({ + const result = await regenerateTitle({ environmentId: thread.environmentId, - input: { threadId: thread.id, regenerateTitle: true }, + input: { threadId: thread.id }, }); if (result._tag === "Failure") { const error = Cause.squash(result.cause); @@ -523,6 +563,13 @@ export function useThreadListActions(): { ); return false; } + if (result.value?.status === "failed") { + Dialog.alert( + "Could not regenerate title", + result.value.message ?? "The thread title could not be regenerated.", + ); + return false; + } return true; })(); titleRegenerationInFlightThreadKeys.current.delete(key); @@ -570,7 +617,10 @@ export function useThreadListActions(): { const moveThread = async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => { if (!checkThreadOperationPermission(thread, "Could not move thread")) return false; if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false; - const shells = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom); + // The rows on screen can be older than the server's while they wait to show. A move + // planned from them could act on a pin or an order key that the server has replaced. + if (appAtomRegistry.get(steadyShellsHoldingAtom)) return false; + const shells = appAtomRegistry.get(steadyNavigationThreadShellsAtom); const current = shells.find( (row) => row.id === thread.id && row.environmentId === thread.environmentId, ); @@ -706,18 +756,19 @@ export function useThreadListActions(): { const confirmDeleteThread = (thread: EnvironmentThreadShell) => confirmThreadDeletion(executeAction, thread); + // `moveThread` looks up its own row, and refuses while a list holds older rows. return { - archiveThread, - confirmDeleteThread, - settleThread, - snoozeThread, - unsnoozeThread, - unsettleThread, - pinThread, - unpinThread, - setThreadAutoSettle, + archiveThread: (thread) => archiveThread(liveThread(thread)), + confirmDeleteThread: (thread) => confirmDeleteThread(liveThread(thread)), + settleThread: (thread) => settleThread(liveThread(thread)), + snoozeThread: (thread, snoozedUntil) => snoozeThread(liveThread(thread), snoozedUntil), + unsnoozeThread: (thread) => unsnoozeThread(liveThread(thread)), + unsettleThread: (thread) => unsettleThread(liveThread(thread)), + pinThread: (thread) => pinThread(liveThread(thread)), + unpinThread: (thread) => unpinThread(liveThread(thread)), + setThreadAutoSettle: (thread, enabled) => setThreadAutoSettle(liveThread(thread), enabled), moveThread, - renameThread, - regenerateThreadTitle, + renameThread: (thread) => renameThread(liveThread(thread)), + regenerateThreadTitle: (thread) => regenerateThreadTitle(liveThread(thread)), }; } diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx index 2eae47e6a1..9cfb0e424f 100644 --- a/apps/mobile/src/features/keyboard/CommandPalette.tsx +++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx @@ -1,3 +1,4 @@ +import { LegendList, type LegendListRef } from "@legendapp/list/react-native"; import { uuidv4 } from "../../lib/uuid"; import { useNavigation } from "@react-navigation/native"; import { @@ -7,7 +8,8 @@ import { type EnvironmentThreadSearchMatch, type ShownOrder, } from "@t3tools/client-runtime/state/thread-search"; -import { isListedThreadLineage, THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts"; +import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; +import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts"; import { foldSearchQuery, PALETTE_MESSAGE_LIMIT, @@ -18,7 +20,6 @@ import { } from "@t3tools/shared/paletteSearch"; import { useEffect, useMemo, useRef, useState } from "react"; import { - FlatList, KeyboardAvoidingView, Modal, Pressable, @@ -41,7 +42,12 @@ import { deriveBottomControlInsets } from "../../lib/reserved-regions"; import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; import { useNativeLayoutMetrics } from "../../native/native-layout-metrics"; import { T3KeyboardCommands } from "../../native/T3KeyboardCommands"; -import { useProjects, useThreadShell, useVisibleThreadShells } from "../../state/entities"; +import { + useDelegatedUnderParent, + useProjects, + useThreadShell, + useVisibleThreadShells, +} from "../../state/entities"; import { useThreadSearch } from "../../state/queries"; import { requestThreadMessageJump } from "../threads/threadMessageJump"; import { threadEnvironment } from "../../state/threads"; @@ -216,6 +222,7 @@ export function CommandPalette(props: { const runCommand = props.onCommand; const projects = useProjects(); const threads = useVisibleThreadShells(); + const delegatedUnderParent = useDelegatedUnderParent(); const activeThreadRef = parseActiveThreadPath(props.pathname); const activeThread = useThreadShell(activeThreadRef); const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); @@ -229,7 +236,7 @@ export function CommandPalette(props: { const pendingAction = useRef<(() => void) | null>(null); const closing = useRef(false); const inputRef = useRef(null); - const listRef = useRef>(null); + const listRef = useRef(null); const { width, height } = useWindowDimensions(); // The palette floats above every column, so it keeps itself inside the window's side insets // and to one side of a book fold. @@ -381,7 +388,15 @@ export function CommandPalette(props: { }), })); const threadItems: CommandPaletteItem[] = threads - .filter((thread) => thread.archivedAt === null && isListedThreadLineage(thread.lineage)) + .filter( + (thread) => + thread.archivedAt === null && + !isShownUnderParent( + { environmentId: thread.environmentId, threadId: thread.id }, + thread.lineage, + delegatedUnderParent, + ), + ) .map((thread) => { const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)); const environment = @@ -426,6 +441,7 @@ export function CommandPalette(props: { savedConnectionsById, selectDetail, threads, + delegatedUnderParent, ]); const rankedMessageKeys = useMemo(() => { const subjectByKey = new Map( @@ -615,22 +631,23 @@ export function CommandPalette(props: { /> - item.key} - getItemLayout={(_, index) => ({ - length: ROW_HEIGHT + (index === firstMessageIndex ? SECTION_LABEL_HEIGHT : 0), - offset: - ROW_HEIGHT * index + - (firstMessageIndex !== -1 && index > firstMessageIndex - ? SECTION_LABEL_HEIGHT - : 0), - index, - })} - contentContainerClassName="pb-2" + getFixedItemSize={(_, index) => + ROW_HEIGHT + (index === firstMessageIndex ? SECTION_LABEL_HEIGHT : 0) + } + recycleItems + contentContainerStyle={{ paddingBottom: 8 }} ListEmptyComponent={ {search.isPending ? "Searching…" : "No results"} diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index d424e646ae..4083220a80 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -55,6 +55,8 @@ import { useProjects } from "../../state/entities"; import { environmentThreadShells } from "../../state/threads"; import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; import { mobilePreferencesAtom } from "../../state/preferences"; +import { savedConnectionsByIdAtom } from "../../state/use-remote-environment-registry"; +import { workspaceConnections } from "../../state/workspace"; import { DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS, resolveMobileProjectGroupingSettings, @@ -71,7 +73,8 @@ import { import { startOpeningDetail } from "./workspace/useSelectWorkspaceDetail"; import { useWorkspaceTabs } from "./workspace/WorkspaceTabsContext"; import { HomeListOptionsProvider } from "../home/home-list-options"; -import { newTaskDestination } from "../threads/new-task-project-selection"; +import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "../home/homeThreadList"; +import { newTaskDestination, newTaskFilteredProject } from "../threads/new-task-project-selection"; import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary"; import { PaneContext } from "../../components/ui/Pane"; import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation"; @@ -97,7 +100,7 @@ import { workspaceTabColumns, workspaceTabNavigationState, } from "./workspace/workspace-tab-navigation"; -import type { WorkspaceTab } from "./workspace/workspace-tabs-state"; +import { workspaceTabOf, type WorkspaceTab } from "./workspace/workspace-tabs-state"; import { workspaceRoutesOf } from "./workspace-overlay-routes"; import { SettingsWorkspaceLayout } from "../settings/SettingsWorkspaceLayout"; import { WorkspaceThreadSidebar } from "./workspace/WorkspaceThreadSidebar"; @@ -512,10 +515,7 @@ function AdaptiveWorkspaceLayoutContent( setFileInspectorPreferredVisible(false); setInspectorSheetRoute(null); if (layout.variant === "medium") setPrimarySidebarVisible(false); - workspace?.dispatch({ - type: "select", - tab: detail.name === "Thread" ? "threads" : "pullRequests", - }); + workspace?.dispatch({ type: "select", tab: workspaceTabOf(detail.name) }); startOpeningDetail(detail); navigation.dispatch(selectWorkspaceDetail(detail, sheet)); }); @@ -549,12 +549,38 @@ function AdaptiveWorkspaceLayoutContent( : undefined; const preferences = appAtomRegistry.get(mobilePreferencesAtom); const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined; + // Resolve the thread list's filter as useHomeListOptions does: a removed connection's filter reads as all. + const listFilters = saved?.threadListFilters; + const listEnvironmentId = + listFilters?.environmentId != null && + appAtomRegistry.get(savedConnectionsByIdAtom)[listFilters.environmentId] !== undefined + ? listFilters.environmentId + : null; + const filteredScope = resolveHomeProjectFilterScope( + buildHomeProjectScopes({ projects, environmentId: listEnvironmentId, projectGroupingMode }), + projects, + { selectedProjectKey: listFilters?.projectKey ?? null, projectGroupingMode }, + ); + const connectedEnvironmentIds = new Set( + appAtomRegistry + .get(workspaceConnections.environmentsAtom) + .filter((environment) => environment.connectionState === "connected") + .map((environment) => environment.environmentId), + ); handleSelectThreadRoute( newTaskDestination({ projects, requestId: uuidv4(), useLastProject: saved?.useLastProjectForNewThreads, currentProject: environmentId && projectId ? { environmentId, projectId } : undefined, + filteredProject: filteredScope + ? newTaskFilteredProject( + filteredScope, + listEnvironmentId, + connectedEnvironmentIds, + saved?.lastThreadProject, + ) + : undefined, lastProject: saved?.lastThreadProject, }), ); diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx index d26d90e725..8e3920cbb0 100644 --- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx +++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx @@ -28,7 +28,13 @@ import { type ComponentProps, type ReactNode, } from "react"; -import { StyleSheet, View } from "react-native"; +import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; +import { + currentWorkspaceSelections, + workspaceSelectionCheck, +} from "./workspace/workspace-selection-store"; +import { workspaceTabColumns, workspaceTabPage } from "./workspace/workspace-tab-navigation"; +import { Platform, StyleSheet, View } from "react-native"; import { Split, type SplitHostCommands } from "react-native-screens"; import { SafeAreaView } from "react-native-safe-area-context"; import { GestureHandlerRootView } from "react-native-gesture-handler"; @@ -79,6 +85,7 @@ import { NativePrimaryColumnContext, NativeWorkspaceInspectorContext, NativeWorkspaceModeContext, + NativeWorkspaceTabActivityContext, WorkspaceSlotOptionsContext, slotScreenOptions, } from "../../native/v5-workspace-context"; @@ -106,10 +113,14 @@ function ColumnScreen(props: { readonly screenKey?: string; readonly primary?: boolean; readonly attached?: boolean; + readonly animatesPush?: boolean; readonly selectedThreadKey?: string | null; readonly selectedPullRequestKey?: string | null; readonly onDismiss: (routeKey: string, native: boolean) => void; - readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void; + readonly onAppearance: ( + type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear", + key: string, + ) => void; readonly onCompose?: () => void; readonly onToggleSidebar?: () => void; readonly onSearch?: () => void; @@ -139,6 +150,7 @@ function ColumnScreen(props: { { props.onDismiss(key, event.nativeEvent.isNativeDismiss); }} @@ -156,9 +168,10 @@ function ColumnScreen(props: { props.onAppearance("willDisappear", key); props.navigation.emit({ type: "transitionStart", target: key, data: { closing: true } }); }} - onDidDisappear={() => - props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } }) - } + onDidDisappear={() => { + props.onAppearance("didDisappear", key); + props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } }); + }} > @@ -173,6 +186,7 @@ function ColumnScreen(props: { /> dispatchHardwareKeyboardCommand("commandPalette") : undefined; + // Pages a hidden tab opens as it's shown belong to the tab, so they appear in place. + const headerOnly = use(NativeWorkspaceTabActivityContext)?.headerOnly === true; + const [shownPages, setShownPages] = useState({ headerOnly, keys: new Set() }); + if (shownPages.headerOnly !== headerOnly) + setShownPages({ + headerOnly, + keys: headerOnly ? new Set() : new Set(props.detail.map((route) => route.key)), + }); const inspector = use(NativeWorkspaceInspectorContext); const hideInspector = () => { if (inspector.visible) toggleAuxiliaryPane(); @@ -324,7 +346,7 @@ function WorkspaceColumns( } }; const followCollapsedSplit = ( - type: "willAppear" | "didAppear" | "willDisappear", + type: "willAppear" | "didAppear" | "willDisappear" | "didDisappear", key: string, ) => { if (!collapsed.current || layout.usesSplitView) return; @@ -348,6 +370,7 @@ function WorkspaceColumns( const primary = props.descriptors[props.primary.key]; if (!primary) return null; + const primaryColumnWidth = (layout.listPaneWidth ?? 320) + (layout.listPaneGap ?? 0) / 2; return ( - + current.key === route.key)} + animatesPush={!shownPages.keys.has(route.key)} onDismiss={handleNativeDismiss} onAppearance={followCollapsedSplit} onCompose={isPullRequestRoute(route) ? undefined : detailCompose} @@ -556,34 +580,51 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean ), }; diff --git a/apps/mobile/src/features/layout/workspace-inspector-sheet.tsx b/apps/mobile/src/features/layout/workspace-inspector-sheet.tsx index 9fec5e64df..f2f9c02425 100644 --- a/apps/mobile/src/features/layout/workspace-inspector-sheet.tsx +++ b/apps/mobile/src/features/layout/workspace-inspector-sheet.tsx @@ -1,10 +1,8 @@ import { createContext, useRef, useState } from "react"; -import { Platform, View } from "react-native"; import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; -import { FormSheet } from "react-native-screens"; -import { useResolveClassNames } from "uniwind"; import { PaneContext } from "../../components/ui/Pane"; +import { PaneSheet } from "../../components/ui/PaneSheet"; import { RoutedFormSheetContext } from "../../components/ui/RoutedFormSheetContext"; import { formSheetDetents } from "../../native/sheet-surface"; import { InspectorPanes } from "./inspector-host"; @@ -22,7 +20,6 @@ export function WorkspaceInspectorSheet(props: { readonly onClose: () => void; readonly content: InspectorContent | undefined; }) { - const containerStyle = useResolveClassNames(Platform.OS === "android" ? "bg-header" : "bg-sheet"); const insets = useSafeAreaInsets(); // Stays mounted until the sheet has finished closing, so it doesn't empty as it slides away. // Each opening gets a fresh native sheet, even one that starts while the last is closing. @@ -51,15 +48,12 @@ export function WorkspaceInspectorSheet(props: { }; if (!presented.mounted) return null; return ( - { props.onClose(); @@ -71,25 +65,11 @@ export function WorkspaceInspectorSheet(props: { {/* The sheet starts below the status bar. */} - {/* Android FormSheet does not bound flex children. */} - - close()} /> - {Platform.OS === "android" ? ( - - ) : null} - + close()} /> - + ); } diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx index c99de46ebe..01d9cf709c 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx @@ -6,21 +6,31 @@ import { NAVIGATION_TAB_ICONS, useEnabledNavigationTabs, } from "./navigation-tabs"; -import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { + useEffect, + useLayoutEffect, + useRef, + useState, + type Dispatch, + type ReactNode, + type SetStateAction, +} from "react"; import { View, useWindowDimensions, type NativeSyntheticEvent } from "react-native"; import { Tabs, type TabSelectedEvent, type TabSelectionRejectedEvent } from "react-native-screens"; import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext"; +import type { NavigationTab } from "./navigation-tab-order"; import { NATIVE_WORKSPACE_TAB_SLOTS, workspaceTabForNativeSlot, workspaceUsesColumns, - type WorkspaceTab, } from "./workspace-tabs-state"; import { NativeWorkspaceTabActivityContext, + WorkspaceColumnMetricsContext, WorkspaceSlotOptionsContext, } from "../../../native/v5-workspace-context"; +import type { NativeLayoutMetrics } from "../../../lib/reserved-regions"; import { useCompactWorkspaceTabs, useFloatingWorkspaceTabs, @@ -36,9 +46,14 @@ const PULL_REQUEST_ICON = require("../../../../assets/icons/pull-request.png"); /** Retain each native controller tree; removing its root can leave RNS's stack empty. */ function RetainedWorkspaceTab(props: { - readonly tab: WorkspaceTab; + readonly slot: string; + readonly tab: NavigationTab; readonly active: boolean; - readonly children: ReactNode; + /** Render a slot that hasn't been shown yet: its header, and the page it opens with. */ + readonly prewarm: boolean; + readonly setMountedSlots: Dispatch>>; + readonly setPrewarmRequests: Dispatch>>; + readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode; }) { const workspace = useWorkspaceTabs()!; // Whether this slot is the visible one, read by cleanups after the switch has committed. @@ -48,9 +63,30 @@ function RetainedWorkspaceTab(props: { activeRef.current = props.active; }, [props.active]); const isActive = () => activeRef.current; + const [content, setContent] = useState( + props.active + ? { source: workspace, workspace, children: props.children, headerOnly: false } + : null, + ); + const stale = content?.source !== workspace || content?.children !== props.children; + if (props.active && (content?.headerOnly !== false || stale)) + setContent({ source: workspace, workspace, children: props.children, headerOnly: false }); + // A slot not shown yet follows the workspace, so the page it opens with stays current. + else if (!props.active && props.prewarm && (content === null || (content.headerOnly && stale))) + setContent({ + source: workspace, + workspace: { + ...workspace, + settingsOpen: props.slot === "settings", + state: { ...workspace.state, selectedTab: props.tab }, + }, + children: props.children, + headerOnly: true, + }); const activity = { active: props.active, isActive, + headerOnly: content?.headerOnly === true, }; const [optionsByRoute, setOptionsByRoute] = useState>(new Map()); // Stable, so writers and the cleanups that depend on them don't re-run on every write. @@ -59,22 +95,55 @@ function RetainedWorkspaceTab(props: { new Map(current).set(routeKey, { ...current.get(routeKey), ...options }), ); const slotOptions = { byRoute: optionsByRoute, set: setRouteOptions }; - const [content, setContent] = useState( - props.active ? { workspace, children: props.children } : null, + const mounted = content !== null && !content.headerOnly; + const headerOnly = content?.headerOnly === true; + const { slot, setMountedSlots, setPrewarmRequests } = props; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the slot's mount to the host, which uncovers the tab then + useEffect(() => { + if (!mounted) return; + // Each header write commits in the render after it; the slot is ready once a frame passes + // without one, which is when its native header and content are in place. + const frame = requestAnimationFrame(() => + setMountedSlots((current) => (current.has(slot) ? current : new Set(current).add(slot))), + ); + return () => cancelAnimationFrame(frame); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each header write re-arms the frame + }, [mounted, optionsByRoute, slot, setMountedSlots]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a replacement slot (e.g. a re-enabled fourth tab) must report its own mount + useEffect( + () => () => + setMountedSlots((current) => { + if (!current.has(slot)) return current; + const next = new Set(current); + next.delete(slot); + return next; + }), + [slot, setMountedSlots], ); - if (props.active && (content?.workspace !== workspace || content?.children !== props.children)) - setContent({ workspace, children: props.children }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks UIKit to prewarm a hidden header after each write, since bar items it rebuilds fade in on their own first entry + useEffect(() => { + if (!headerOnly || optionsByRoute.size === 0) return; + const frame = requestAnimationFrame(() => + setPrewarmRequests((current) => new Map(current).set(slot, (current.get(slot) ?? 0) + 1)), + ); + return () => cancelAnimationFrame(frame); + }, [headerOnly, optionsByRoute, slot, setPrewarmRequests]); return content ? ( - {content.children} + + {content.children(content.workspace, content.headerOnly)} + ) : null; } +type SlotWorkspace = NonNullable>; + export function WorkspaceNativeTabs(props: { - readonly children: ReactNode; + /** Renders a slot's tree for its own tab, which can lay out differently from the shown one. */ + readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode; readonly hidden: boolean; /** The sidebar column draws the tabs itself, so they leave with it. */ readonly tabsInSidebarColumn?: boolean; @@ -101,66 +170,101 @@ export function WorkspaceNativeTabs(props: { const { colors } = useControlTheme(); const selectedTab = workspace.state.selectedTab; const selectedSlot = workspace.settingsOpen ? -1 : primaryTabs.indexOf(selectedTab); - const request = { - selectedScreenKey: selectedSlot === -1 ? "settings" : NATIVE_WORKSPACE_TAB_SLOTS[selectedSlot]!, - baseProvenance: provenance, + const selectedScreenKey = + selectedSlot === -1 ? "settings" : NATIVE_WORKSPACE_TAB_SLOTS[selectedSlot]!; + // A slot renders its body the first time it's selected. Until it has, UIKit keeps the last + // tab's snapshot over it, so the switch never shows a half-built tab. + const [mountedSlots, setMountedSlots] = useState>(() => new Set()); + // Once the first tab is up, the others mount their headers for UIKit to put in the window + // once: iOS 26 fades bar items in the first time they enter it, which a first visit would show. + const [prewarm, setPrewarm] = useState(false); + const [columnMetrics, setColumnMetrics] = useState>( + () => new Map(), + ); + const sharedColumnMetrics = { + byColumn: columnMetrics, + publish: (column: string, metrics: NativeLayoutMetrics) => + setColumnMetrics((current) => + JSON.stringify(current.get(column)) === JSON.stringify(metrics) + ? current + : new Map(current).set(column, metrics), + ), }; + const [prewarmRequests, setPrewarmRequests] = useState>( + () => new Map(), + ); + const prewarmReady = mountedSlots.size > 0; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- waits for the JS thread to go idle after the first tab mounts + useEffect(() => { + if (!prewarmReady || prewarm) return; + const handle = requestIdleCallback(() => setPrewarm(true), { timeout: 2_000 }); + return () => cancelIdleCallback(handle); + }, [prewarmReady, prewarm]); + const request = { selectedScreenKey, baseProvenance: provenance }; return ( - ) => - setProvenance(nativeEvent.provenance) - } - onTabSelected={({ nativeEvent }: NativeSyntheticEvent) => { - setProvenance(nativeEvent.provenance); - if (nativeEvent.actionOrigin === "programmatic-js") return; - const tab = workspaceTabForNativeSlot(primaryTabs, nativeEvent.selectedScreenKey); - if (tab) selectTab(tab); - }} - > - {NATIVE_WORKSPACE_TAB_SLOTS.map((slot, index) => { - const settings = slot === "settings"; - const tab = settings ? (overflow ?? selectedTab) : primaryTabs[index]; - if (!tab) return null; - return ( - - + ) => + setProvenance(nativeEvent.provenance) + } + onTabSelected={({ nativeEvent }: NativeSyntheticEvent) => { + setProvenance(nativeEvent.provenance); + if (nativeEvent.actionOrigin === "programmatic-js") return; + const tab = workspaceTabForNativeSlot(primaryTabs, nativeEvent.selectedScreenKey); + if (tab) selectTab(tab); + }} + > + {NATIVE_WORKSPACE_TAB_SLOTS.map((slot, index) => { + const settings = slot === "settings"; + const tab = settings ? (overflow ?? selectedTab) : primaryTabs[index]; + if (!tab) return null; + return ( + - {props.children} - - - ); - })} - + + {props.children} + + + ); + })} + + {(deviceType === "pad" || compactTabs || (layout.variant === "medium" && diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx index 44bb869b14..1043eea401 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx @@ -12,7 +12,10 @@ import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area import { CompactBrandTitle } from "../../../components/CompactBrandTitle"; import { HeaderItemsWidthContext } from "../../../native/header-items-width"; import { NativeStackScreenOptions } from "../../../native/StackHeader"; -import { NativePrimaryColumnContext } from "../../../native/v5-workspace-context"; +import { + NativePrimaryColumnContext, + NativeWorkspaceTabActivityContext, +} from "../../../native/v5-workspace-context"; import { isDuoDevice } from "../../../lib/device-type"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../../native/native-glass"; import { @@ -89,6 +92,7 @@ function WorkspaceRootContent() { const { state } = workspace; // Settings is a workspace tab too; its list takes the place of the selected tab's. const settingsOpen = workspace.settingsOpen; + const headerOnly = use(NativeWorkspaceTabActivityContext)?.headerOnly === true; const renderHeaderTitle = () => ( - {settingsOpen ? ( + {/* Usage draws its own header, and skips its body itself. */} + {headerOnly && (settingsOpen || state.selectedTab !== "usage") ? null : settingsOpen ? ( ) : enabled.length === 0 ? ( diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx index 9ecb6fa933..81344be55e 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx @@ -26,6 +26,8 @@ export const WorkspaceTabsContext = createContext<{ readonly settingsOpen: boolean; readonly getScrollOffset: (tab: WorkspaceSearchTab) => number; readonly recordScrollOffset: (tab: WorkspaceSearchTab, offset: number) => void; + /** Leaves search and returns the list to where it was when search began. */ + readonly cancelSearch: (tab: WorkspaceSearchTab) => void; } | null>(null); export function useWorkspaceTabs() { @@ -52,8 +54,8 @@ function resolveWorkspaceTabsSelection( // One model per provider. Handlers on frozen screens keep stale closures, so // they read the current selection from the registry at call time. -function createWorkspaceTabsModel() { - const stored = Atom.make(initialWorkspaceTabsState()); +function createWorkspaceTabsModel(selectedTab?: WorkspaceTab) { + const stored = Atom.make(initialWorkspaceTabsState(selectedTab)); const scrollOffsets: Record = { threads: 0, pullRequests: 0, @@ -75,19 +77,25 @@ function createWorkspaceTabsModel() { export function WorkspaceTabsProvider(props: { readonly children: ReactNode; readonly settingsOpen?: boolean; + readonly initialTab?: WorkspaceTab; }) { const registry = use(RegistryContext); - const [model] = useState(createWorkspaceTabsModel); + const [model] = useState(() => createWorkspaceTabsModel(props.initialTab)); const state = useAtomValue(model.resolved); + const dispatch = (action: WorkspaceTabsAction) => + registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action)); const context = { state, - dispatch: (action: WorkspaceTabsAction) => - registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action)), + dispatch, isTabActive: (tab: WorkspaceTab) => registry.get(model.resolved).selectedTab === tab, bottomClearance: 0, settingsOpen: props.settingsOpen ?? false, getScrollOffset: model.getScrollOffset, recordScrollOffset: model.recordScrollOffset, + cancelSearch: (tab: WorkspaceSearchTab) => { + model.recordScrollOffset(tab, registry.get(model.resolved).tabs[tab].searchEntryOffset); + dispatch({ type: "cancel", tab }); + }, }; return {props.children}; } diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceToolbar.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceToolbar.tsx index 3d27b096c1..f07076a8fb 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceToolbar.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceToolbar.tsx @@ -1,6 +1,6 @@ import { useActiveNewTask } from "../../../state/active-new-task"; import { Toolbar } from "../../../components/ui/Toolbar"; -import { useFocusEffect, useIsFocused } from "@react-navigation/native"; +import { useFocusEffect, useIsFocused, useNavigationState } from "@react-navigation/native"; import { use, useCallback, useEffect, useRef } from "react"; import { isDuoDevice } from "../../../lib/device-type"; import { useDeviceType } from "../../../native/native-layout-metrics"; @@ -80,18 +80,21 @@ export function WorkspaceToolbar(props: { searchRef.current?.focus(); return true; }; - const cancelSearch = () => { - workspace.recordScrollOffset(selectedTab, tab.searchEntryOffset); - workspace.dispatch({ type: "cancel", tab: selectedTab }); - }; + const cancelSearch = () => workspace.cancelSearch(selectedTab); const searchFocused = () => tab.searchMode === "resting" ? enterSearch() : workspace.dispatch({ type: "search", tab: selectedTab }); useHardwareKeyboardCommand("focusSearch", focusSearch); + // Home draws the Settings list under the `Settings` route, which holds navigation focus. + const settingsListOnTop = useNavigationState( + (state) => state.routes[state.index]?.name === "Settings", + ); // The sidebar remains visible while its detail owns navigation focus. - const searchHostVisible = focused || primaryColumn?.presented === true; + const searchHostVisible = focused || settingsListOnTop || primaryColumn?.presented === true; const restoreSearch = () => { + // A search cancelled while its screen was covered leaves its text in the native field. + if (tab.searchMode === "resting") searchRef.current?.setText(""); if ( searchHostVisible && searchVisible && diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts index 69ffd96aa4..7b32ad7f95 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts @@ -1,10 +1,12 @@ +import * as NodeModule from "node:module"; import { describe, expect, it } from "vite-plus/test"; -import { restoreSettingsLinkState } from "../../settings/settings-navigation"; +import { restoreSettingsLinkState, settingsLinkAction } from "../../settings/settings-navigation"; import { workspaceSelectionsIn, workspaceTabColumns, workspaceTabNavigationState, + workspaceTabPage, } from "./workspace-tab-navigation"; const home = { key: "home", name: "Home" }; @@ -19,6 +21,17 @@ const pullRequest = { params: { environmentId: "env", projectId: "project", repository: "o/r", number: 7 }, }; const settings = { key: "settings", name: "Settings" }; +const requireFromNative = NodeModule.createRequire( + NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"), +); +const { getStateFromPath } = requireFromNative("@react-navigation/core") as { + readonly getStateFromPath: typeof import("@react-navigation/native").getStateFromPath; +}; +const { StackRouter } = NodeModule.createRequire( + requireFromNative.resolve("@react-navigation/core/package.json"), +)("@react-navigation/routers") as { + readonly StackRouter: typeof import("@react-navigation/native").StackRouter; +}; const available = { thread: () => true, pullRequest: () => true }; const names = (state: { routes: readonly { name: string }[] }) => state.routes.map((route) => route.name); @@ -106,6 +119,12 @@ describe("opening a workspace tab", () => { workspaceTabNavigationState(state, "settings", { settings: "SettingsMicrophone" }, columns), ), ).toEqual(["Home", "Settings", "SettingsVoice"]); + // A hidden tab renders its page under the key that opening the tab later uses. + for (const tab of ["pullRequests", "settings"] as const) { + expect(workspaceTabNavigationState(state, tab, selections, columns).routes.at(-1)?.key).toBe( + workspaceTabPage(state, tab, selections, columns)?.key, + ); + } }); it("keeps the route that is already open, so re-selecting a tab doesn't rebuild it", () => { @@ -217,4 +236,29 @@ describe("Settings links", () => { ]); expect(restoreSettingsLinkState(bare, undefined)).toBe(bare); }); + + it("opens a link sent to the running app on the Settings tab, as its button does", () => { + const screens = { + Home: "", + Settings: "settings", + SettingsAbout: "settings/about", + SettingsAppearance: "settings/appearance", + }; + const router = StackRouter({}); + const options = { routeNames: Object.keys(screens), routeParamList: {}, routeGetIdList: {} }; + const open = router.getRehydratedState( + { index: 2, routes: [{ name: "Home" }, { name: "Settings" }, { name: "SettingsAbout" }] }, + options, + ); + const follow = (path: string) => { + const link = getStateFromPath(path, { initialRouteName: "Home", screens })!; + const action = settingsLinkAction(link, open)!; + return router.getStateForAction(open, action, options)!; + }; + + expect(names(follow("settings"))).toEqual(["Home", "Settings"]); + const appearance = follow("settings/appearance"); + expect(names(appearance)).toEqual(["Home", "Settings", "SettingsAppearance"]); + expect(appearance.routes[1]!.key).toBe(open.routes[1]!.key); + }); }); diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts index 6a44e617e5..704e47d2b9 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts @@ -146,6 +146,13 @@ function keyed(route: Route): Route & { readonly key: s return { ...route, key: `${route.name}-workspace-${routeKeys}` }; } +// A hidden tab renders the page it would open under this key, so opening it reuses that screen. +function keyedPage(route: Route): Route & { readonly key: string } { + return route.key === undefined + ? { ...route, key: `${route.name}-workspace-page` } + : (route as Route & { readonly key: string }); +} + function detailRoute( state: { readonly routes: readonly RouteLike[] }, tab: "threads" | "pullRequests", @@ -222,7 +229,12 @@ export function workspaceTabNavigationState< undefined, page === selections.settings ? selections.settingsKey : undefined, ); - const routes = [...settings.routes.map(keyed), ...overlays]; + const [home, list, current] = settings.routes; + const routes = [ + ...[home!, list!].map(keyed), + ...(current ? [keyedPage(current)] : []), + ...overlays, + ]; return { ...settings, index: routes.length - 1, routes }; } const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" }; @@ -230,6 +242,23 @@ export function workspaceTabNavigationState< options.columns && tab !== "usage" ? detailRoute(state, tab, selections, options.check, options.seedPullRequest) : undefined; - const routes = [...[home, ...(detail ? [detail] : [])].map(keyed), ...overlays]; + const routes = [keyed(home), ...(detail ? [keyedPage(detail)] : []), ...overlays]; return { ...state, index: routes.length - 1, routes }; } + +/** The page opening `tab` would show beside its list, which the hidden tab renders ahead. */ +export function workspaceTabPage( + state: { readonly routes: readonly RouteLike[] }, + tab: WorkspaceTab | "settings", + selections: WorkspaceSelections, + options: { + readonly columns: boolean; + readonly check: WorkspaceSelectionCheck; + readonly seedPullRequest?: (identity: Omit) => object; + }, +) { + const page = workspaceTabNavigationState(state, tab, selections, options).routes.find( + (route) => route.name !== "Home" && route.name !== "Settings", + ); + return page?.key === undefined ? undefined : { ...page, key: page.key }; +} diff --git a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts index 3598894115..3f6754c679 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts @@ -38,9 +38,16 @@ function emptyTab(): WorkspaceTabState { return { query: "", searchMode: "resting", scrollOffset: 0, searchEntryOffset: 0 }; } -export function initialWorkspaceTabsState(): WorkspaceTabsState { +/** The list a workspace page belongs to. */ +export function workspaceTabOf(routeName: string | undefined): WorkspaceTab { + return routeName === "PullRequest" ? "pullRequests" : "threads"; +} + +export function initialWorkspaceTabsState( + selectedTab: WorkspaceTab = "threads", +): WorkspaceTabsState { return { - selectedTab: "threads", + selectedTab, selectionRevision: 0, tabs: { threads: emptyTab(), diff --git a/apps/mobile/src/features/projects/AddProjectScreen.test.ts b/apps/mobile/src/features/projects/AddProjectScreen.test.ts index ab331d0149..4718133f7a 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.test.ts +++ b/apps/mobile/src/features/projects/AddProjectScreen.test.ts @@ -6,7 +6,11 @@ import * as NodeModule from "node:module"; import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { workspaceDetailRouter } from "../layout/workspace/workspace-detail-selection"; import type { NavigationState } from "@react-navigation/native"; -import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts"; +import { + AuthFilesystemReadScope, + AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, +} from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { act, createElement, isValidElement, type ReactNode } from "react"; @@ -22,7 +26,9 @@ const state = vi.hoisted(() => ({ id: string; title: string; workspaceRoot: string; + repositoryIdentity?: { canonicalKey: string }; }[], + cloneDestinations: [] as string[], createResult: null as Promise | null, createNewResult: null as Promise | null, startCloneResult: null as Promise | null, @@ -134,7 +140,15 @@ vi.mock("../../state/use-remote-environment-registry", () => ({ }), })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); -vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => () => {} })); +// Only filesystem.browse of `~` answers, with the host's home as its parentPath. +vi.mock("../../state/use-atom-query-runner", () => ({ + useAtomQueryRunner: + () => + async ({ input }: { input?: { partialPath?: string } }) => + input?.partialPath === "~" + ? AsyncResult.success({ parentPath: "/home/tester", entries: [] }) + : undefined, +})); vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) })); vi.mock("../../state/presentation", () => ({ useEnvironmentPresentation: () => ({ isReady: true, presentation: null }), @@ -144,6 +158,7 @@ vi.mock("../../state/sourceControl", () => ({ sourceControlEnvironment: { discovery: (input: unknown) => input, startProjectClone: async ({ input }: { input: { destinationPath: string } }) => { + state.cloneDestinations.push(input.destinationPath); if (state.startCloneResult) return state.startCloneResult; NodeFS.mkdirSync(input.destinationPath); return AsyncResult.success(undefined); @@ -230,7 +245,7 @@ function cloneAction() { renderScreen(() => AddProjectDestinationScreen({ environmentId: "environment", - remoteUrl: "https://example.com/repo.git", + remoteUrl: "https://example.com/owner/repo.git", repositoryName: "repo", }), ), @@ -274,6 +289,38 @@ describe("clone project permissions", () => { expect(state.projects).toEqual([]); }, ); + + it.each([ + [ + "opens the existing project of that repository instead of cloning into its folder", + "example.com/owner/repo", + false, + ], + ["leaves a folder holding another repository to the clone", "example.com/owner/other", true], + ])("%s", async (_name, canonicalKey, clones) => { + state.scopes.add(AuthOrchestrationOperateScope); + state.cloneDestinations = []; + state.startCloneResult = Promise.resolve( + AsyncResult.failure(Cause.fail(new Error("Destination is not empty"))), + ); + state.existingProjects = [ + { + environmentId: "environment", + id: "existing", + title: "repo", + workspaceRoot: NodePath.join(state.baseDirectory, "repo"), + repositoryIdentity: { canonicalKey }, + }, + ]; + try { + await cloneAction()(); + + expect(state.cloneDestinations.length > 0).toBe(clones); + } finally { + state.existingProjects = []; + state.startCloneResult = null; + } + }); }); function mountProjectFlow( @@ -488,10 +535,10 @@ describe("add project source environment", () => { }); describe("local project navigation", () => { - function setup() { + function setup(baseDirectory = "/tmp/t3-mobile-audit-fixture") { state.navigationState = undefined; state.scopes = new Set([AuthOrchestrationOperateScope]); - state.baseDirectory = "/tmp/t3-mobile-audit-fixture"; + state.baseDirectory = baseDirectory; state.projects = []; state.dispatch.mockReset(); state.alert.mockReset(); @@ -523,6 +570,28 @@ describe("local project navigation", () => { ); }); + it("opens an existing project typed as a home-relative path instead of creating it", async () => { + state.existingProjects = [ + { + environmentId: "environment", + id: "existing", + title: "bike-documents", + workspaceRoot: "/home/tester/projects/bike-documents", + }, + ]; + try { + const { created, projected, submit } = setup("~/projects/bike-documents/"); + state.scopes.add(AuthFilesystemReadScope); + created.resolve(AsyncResult.success(undefined)); + projected.resolve(null); + await submit(); + + expect(state.projects).toEqual([]); + } finally { + state.existingProjects = []; + } + }); + it("does not replace a reopened flow when the previous submission finishes", async () => { const { created, projected, submit } = setup(); const navigation = mountProjectFlow(false); diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index e4bf2f529e..e91a2c3d0c 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -30,6 +30,7 @@ import { parseAddProjectRemoteSource, resolveAddProjectPath, sortAddProjectProviderSources, + type OfferedSourceControlProviders, type AddProjectRemoteSource, } from "@t3tools/client-runtime/operations/projects"; import { @@ -117,6 +118,7 @@ interface EnvironmentOption { readonly connectionError: string | null; readonly connectionErrorTraceId: string | null; readonly ghqCloneLayout: boolean; + readonly offeredSourceControlProviders: OfferedSourceControlProviders | undefined; } const environmentOptionOrder = Order.mapInput( @@ -384,7 +386,26 @@ function useBrowsePathInput( [browseNavigation], ); - return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath }; + // Registered roots are absolute and `~` expands on the host, so ask the host for its home. + const resolveHomePath = async (path: string): Promise => { + if ( + !/^~(?:[\\/]|$)/.test(path) || + !environment || + !readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) || + !canPreloadBrowsePath(environmentRuntime?.connectionState) + ) { + return path; + } + const home = await loadBrowsePath({ + environmentId: environment.environmentId, + input: { partialPath: "~" }, + }); + return AsyncResult.isSuccess(home) && home.value + ? `${home.value.parentPath.replace(/[\\/]+$/, "")}${path.slice(1)}` + : path; + }; + + return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath, resolveHomePath }; } function useEnvironmentOptions( @@ -412,6 +433,7 @@ function useEnvironmentOptions( connectionError: runtime?.connectionError ?? null, connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null, ghqCloneLayout: config?.settings.ghqCloneLayout === true, + offeredSourceControlProviders: config?.settings.offeredSourceControlProviders, }; }); return Arr.sort( @@ -648,24 +670,30 @@ export function AddProjectSourceScreen(props: { readonly environmentId?: string ) } /> - {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map( - (candidate) => ( - - ), - )} + {( + [ + "url", + ...sortAddProjectProviderSources( + readiness, + selectedEnvironment.offeredSourceControlProviders, + ), + ] as AddProjectRemoteSource[] + ).map((candidate) => ( + + ))} {discoveryState.isPending ? ( @@ -720,16 +748,76 @@ async function draftWithPrompt( return draftId; } -function useCreateProject(environment: EnvironmentOption | null) { +function useOpenExistingProject(environment: EnvironmentOption | null) { const openNewTaskDraft = useOpenNewTaskDraft(); - const navigation = useNavigation(); - const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const updateProject = useAtomCommand(projectEnvironment.update, { label: "project unarchive", }); const projects = useProjects(); - return async (workspaceRoot: string, originRoute = getActiveRoute(navigation)) => { + return async ( + path: string, + originRoute: ReturnType, + clone?: { readonly remoteUrl: string; readonly prompt: string | null }, + ): Promise => { + if (!environment) return false; + const existing = findExistingAddProject({ + projects, + environmentId: environment.environmentId, + path, + }); + if (!existing) return false; + // A folder holding another repository is not this clone; let the clone report it occupied. + if ( + clone && + existing.repositoryIdentity?.canonicalKey !== + sourceControlClients.repositoryKeyFromRemote(clone.remoteUrl) + ) { + return false; + } + const prompt = clone?.prompt; + // Adding an archived project's folder again brings the project back. + const unarchived = + existing.archivedAt == null || + ( + await updateProject({ + environmentId: existing.environmentId, + input: { projectId: existing.id, archived: false }, + }) + )._tag === "Success"; + Dialog.alert( + "Project already exists", + unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, + ); + openNewTaskDraft( + { + environmentId: existing.environmentId, + projectId: existing.id, + title: existing.title, + ...(prompt + ? await draftWithPrompt(existing.environmentId, existing.id, prompt).then( + (draftId) => ({ draftId }), + () => ({}), + ) + : {}), + }, + originRoute, + ); + return true; + }; +} + +function useCreateProject(environment: EnvironmentOption | null) { + const openNewTaskDraft = useOpenNewTaskDraft(); + const navigation = useNavigation(); + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + const openExistingProject = useOpenExistingProject(environment); + + return async ( + workspaceRoot: string, + originRoute = getActiveRoute(navigation), + lookupPath = workspaceRoot, + ) => { if ( !environment || !canCreateProjectInEnvironment(environment.connectionState) || @@ -742,33 +830,7 @@ function useCreateProject(environment: EnvironmentOption | null) { return; } - const existing = findExistingAddProject({ - projects, - environmentId: environment.environmentId, - path: workspaceRoot, - }); - if (existing) { - // Adding an archived project's folder again brings the project back. - const unarchived = - existing.archivedAt == null || - ( - await updateProject({ - environmentId: existing.environmentId, - input: { projectId: existing.id, archived: false }, - }) - )._tag === "Success"; - Dialog.alert( - "Project already exists", - unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, - ); - openNewTaskDraft( - { - environmentId: existing.environmentId, - projectId: existing.id, - title: existing.title, - }, - originRoute, - ); + if (await openExistingProject(lookupPath, originRoute)) { return; } @@ -1050,7 +1112,10 @@ export function AddProjectNewScreen(props: { readonly environmentId?: string | s input: {}, }), ); - const publishTargets = getNewProjectPublishTargets(discoveryState.data); + const publishTargets = getNewProjectPublishTargets( + discoveryState.data, + environment?.offeredSourceControlProviders, + ); const [name, setName] = useState(""); const [publishes, setPublishes] = useState(false); const [publishKind, setPublishKind] = useState(null); @@ -1290,8 +1355,9 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st environment?.environmentId ?? null, AuthOrchestrationOperateScope, ); + const navigation = useNavigation(); const createProject = useCreateProject(environment); - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = + const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } = useBrowsePathInput(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1310,7 +1376,11 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st } setIsSubmitting(true); - const result = await createProject(resolved.path); + const originRoute = getActiveRoute(navigation); + const lookupPath = resolved.path.startsWith("~") + ? await resolveHomePath(resolved.path) + : resolved.path; + const result = await createProject(resolved.path, originRoute, lookupPath); if (result && AsyncResult.isFailure(result)) { setError(errorMessage(Cause.squash(result.cause))); } @@ -1377,11 +1447,9 @@ export function AddProjectDestinationScreen(props: { ? getCloneDirectoryPath(remoteUrl, true, repositoryName) : null; const cloneDirectoryName = ghqDirectoryPath?.split("/").at(-1) ?? repositoryName; - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput( - environment, - cloneDirectoryName, - ghqDirectoryPath ?? repositoryName, - ); + const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } = + useBrowsePathInput(environment, cloneDirectoryName, ghqDirectoryPath ?? repositoryName); + const openExistingProject = useOpenExistingProject(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1409,6 +1477,15 @@ export function AddProjectDestinationScreen(props: { const originRoute = getActiveRoute(navigation); setIsSubmitting(true); + if ( + await openExistingProject(await resolveHomePath(resolved.path), originRoute, { + remoteUrl, + prompt: prompt ?? null, + }) + ) { + setIsSubmitting(false); + return; + } const title = inferProjectTitleFromPath(resolved.path); const startResult = await startProjectClone({ environmentId: environment.environmentId, diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx index 40a7d0b675..9d59324c1e 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx @@ -11,7 +11,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { AsyncResult } from "effect/reactivity"; -import type { PullRequestThreadComment } from "@t3tools/contracts"; +import { pullRequestConversationThreads, type PullRequestThreadComment } from "@t3tools/contracts"; import { useRef, useState } from "react"; import { ScrollView, View, type ScrollViewInstance } from "react-native"; import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller"; @@ -21,7 +21,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/ import { AppBar } from "../../components/ui/AppBar"; import { Button } from "../../components/ui/Button"; import { GlassSurface } from "../../components/ui/GlassSurface"; -import { relativeTime } from "../../lib/time"; +import { compareTimestamps, relativeTime } from "../../lib/time"; import { composerPullRequests } from "../../state/pull-requests"; import { useAtomCommand } from "../../state/use-atom-command"; import { useEnvironmentQuery } from "../../state/query"; @@ -60,7 +60,12 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss reportFailure: false, }); const loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false }); - const thread = activity.data?.reviewThreads.find((thread) => thread.id === params.discussionId); + const thread = + activity.data && + pullRequestConversationThreads(activity.data).find( + (thread) => thread.id === params.discussionId, + ); + const filePath = thread?.path ?? null; const [body, setBody] = useState(""); const completions = usePullRequestCompletions({ environmentId: params.environmentId, @@ -142,7 +147,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss ...new Map( [...extra, ...(thread?.comments ?? [])].map((comment) => [comment.id, comment]), ).values(), - ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)); + ].sort((left, right) => compareTimestamps(left.createdAt, right.createdAt)); const scrollRef = useRef(null); const pendingTop = useRef(null); const positionedComment = useRef(null); @@ -200,20 +205,24 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss {activity.isPending && !thread ? : null} {thread ? ( - - {thread.path} - {thread.line ? `:${thread.line}` : ""} - + {thread.path === null ? null : ( + + {thread.path} + {thread.line ? `:${thread.line}` : ""} + + )} {thread.isResolved ? "Resolved" : "Unresolved"} {thread.isOutdated ? " · Outdated" : ""} -
+ ), +})); +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ isFocused: () => false }), + usePreventRemove: () => {}, +})); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) })); +vi.mock("@expo/ui/community/datetime-picker", () => ({ DateTimePicker: () => null })); +vi.mock("../../components/ui/Dialog", () => ({ alert: mocks.alert })); +vi.mock("../../components/ui/AppText", () => ({ AppText: Children })); +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); +vi.mock("../../components/EnvironmentMachineSymbol", () => ({ + EnvironmentMachineSymbol: () => null, + ENVIRONMENT_MACHINE_SYMBOLS: {}, +})); +vi.mock("../../components/ui/Menu", () => ({ + Menu: ({ + actions, + onPressAction, + }: { + actions: readonly { id: string; title: string }[]; + onPressAction: (event: { nativeEvent: { event: string } }) => void; + }) => + actions.map(({ id, title }) => ( + + )), +})); +vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children })); +vi.mock("./components/SettingsScreen", () => ({ SettingsScreen: Children })); +vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children })); +vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({ + useSettingsEnvironmentMenu: () => null, +})); +vi.mock("./components/ScheduledTaskPromptField", () => ({ ScheduledTaskPromptField: () => null })); +vi.mock("../layout/workspace/useSelectWorkspaceDetail", () => ({ + useSelectWorkspaceDetail: () => vi.fn(), +})); +vi.mock("../../state/threads", () => ({ threadFamilies: {} })); +vi.mock("../../lib/copyTextWithHaptic", () => ({ tryCopyTextWithHaptic: vi.fn() })); +vi.mock("../voice-input/useVoiceInputController", () => ({ + useVoiceInputController: () => ({ blocksSubmission: false }), +})); +vi.mock("../../components/ui/Button", () => ({ + Button: ({ label, onPress }: { label: string; onPress: () => void }) => ( + + ), +})); +vi.mock("../../components/ui/SegmentedControl", () => ({ + SegmentedControl: ({ + options, + onSelect, + }: { + options: readonly { value: string; label: string }[]; + onSelect: (value: string) => void; + }) => + options.map(({ value, label }) => ( + + )), +})); +vi.mock("../../components/ui/ThemedSwitch", () => ({ + ThemedSwitch: ({ + value, + onValueChange, + }: { + value: boolean; + onValueChange: (value: boolean) => void; + }) => , +})); +vi.mock("../../state/entities", () => ({ + useProjects: () => [ + { environmentId: "environment", id: "project", title: "Project" }, + { environmentId: "target", id: "target-project", title: "Target project" }, + ], + useServerConfigs: () => new Map(), + useEnvironmentServerConfig: () => null, + useThreadShell: () => null, +})); +vi.mock("./settings-environment-filter", () => ({ + useSettingsEnvironmentFilter: () => ({ + selectedTargets: [{ environmentId: "environment", label: "Environment" }], + availableTargets: [ + { environmentId: "environment", label: "Environment" }, + { environmentId: "target", label: "Target" }, + ], + selectedProjectKey: null, + projectGroups: [], + }), +})); +vi.mock("../../lib/modelOptions", () => ({ + buildModelOptions: () => [], + resolveDefaultableModelSelection: () => null, + resolveNewTaskModelSelection: () => null, +})); +vi.mock("../../state/session", () => ({ + readEnvironmentScope: () => true, + usePreparedConnection: () => ({ _tag: "None" }), +})); +vi.mock("../../state/server", () => ({ + serverEnvironment: { + scheduledTasksLive: () => ({}), + upsertScheduledTask: { permissionAtom: () => Atom.make(true) }, + }, +})); +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: () => ({ data: { tasks: mocks.tasks, threads: [] } }), +})); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.upsert })); + +import { appAtomRegistry } from "../../state/atom-registry"; +import { editDraft } from "./scheduledTaskDraft"; +import { + scheduledTaskEditorSessionAtom, + startScheduledTaskEditor, +} from "./scheduled-task-editor-state"; +import { SettingsScheduledTaskEditRouteScreen } from "./SettingsScheduledTasksRouteScreen"; + +let root: Root; +let container: HTMLDivElement; +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement("div"); + root = createRoot(container); + mocks.alert.mockReset(); + mocks.upsert.mockReset(); + mocks.upsert.mockResolvedValue({ _tag: "Success" }); + const task: ScheduledTask = { + id: ScheduledTaskId.make("task"), + title: "Task", + prompt: "Prompt", + enabled: true, + schedule: { type: "fixed_time", timeOfDay: "05:00" }, + projectId: ProjectId.make("project"), + threadId: null, + workspaceStrategy: { type: "root" }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "model", + }, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "mobile", + createdAt: "2026-10-22T00:00:00.000Z", + updatedAt: "2026-10-22T00:00:00.000Z", + nextRunAt: null, + lastRunAt: null, + lastRunStatus: "never", + lastRunError: null, + runCount: 0, + }; + mocks.tasks = [task]; + const draft = editDraft(task); + startScheduledTaskEditor({ + environmentId: EnvironmentId.make("environment"), + environmentLabel: "Environment", + draft: { ...draft, schedule: { ...draft.schedule, intervalMinutes: "60" } }, + }); + act(() => + root.render( + + + , + ), + ); +}); +afterEach(() => { + act(() => root.unmount()); + appAtomRegistry.set(scheduledTaskEditorSessionAtom, null); +}); +function button(label: string) { + const element = Array.from(container.querySelectorAll("button")).find( + (button) => button.textContent === label, + ); + if (!element) throw new Error(`Missing button: ${label}`); + return element; +} +describe("scheduled task batched edits", () => { + it("submits the selected interval when saved before React commits", async () => { + await act(async () => { + button("Interval").click(); + button("Save changes").click(); + }); + expect(mocks.alert).not.toHaveBeenCalled(); + expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({ + environmentId: "environment", + input: expect.objectContaining({ + id: "task", + requireExisting: true, + schedule: { type: "interval", everyMs: 3_600_000 }, + }), + }); + }); + it("retains the interval when enabled changes before React commits", async () => { + act(() => { + button("Interval").click(); + button("Toggle enabled").click(); + }); + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current?.draft.schedule.mode).toBe( + "interval", + ); + await act(async () => button("Save changes").click()); + expect(mocks.alert).not.toHaveBeenCalled(); + expect(mocks.upsert).toHaveBeenCalledExactlyOnceWith({ + environmentId: "environment", + input: expect.objectContaining({ + id: "task", + requireExisting: true, + enabled: false, + schedule: { type: "interval", everyMs: 3_600_000 }, + }), + }); + }); + it("keeps every webhook filter added before React commits", () => { + act(() => button("On webhook").click()); + act(() => { + button("Add filter").click(); + button("Add filter").click(); + }); + expect( + appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current?.draft.schedule.filters, + ).toHaveLength(2); + }); + it("keeps the target project when an old picker fires after changing environments", () => { + const editor = appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current; + if (!editor) throw new Error("Missing editor"); + act(() => startScheduledTaskEditor({ ...editor, draft: { ...editor.draft, task: null } })); + act(() => { + button("Select Target").click(); + button("Interval").click(); + button("Select Project").click(); + }); + expect(appAtomRegistry.get(scheduledTaskEditorSessionAtom)?.current).toMatchObject({ + environmentId: "target", + draft: { projectId: "target-project", schedule: { mode: "interval" } }, + }); + }); +}); diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index b3592d38a7..07111fd537 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -36,6 +36,7 @@ import { WEBHOOK_FILTER_OPS, type WebhookFilterDraft, } from "@t3tools/client-runtime/scheduled-task-webhook"; +import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; import { useRef, useState, type ReactNode } from "react"; import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native"; import type { NativeStackNavigationProp } from "@react-navigation/native-stack"; @@ -58,6 +59,7 @@ import { webhookAddress } from "@t3tools/client-runtime/webhook-address"; import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { usePreparedConnection } from "../../state/session"; import { buildModelOptions } from "../../lib/modelOptions"; +import { withImplicitFastModeSelection } from "../../lib/providerOptions"; import { useProjects, useEnvironmentServerConfig } from "../../state/entities"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; @@ -79,13 +81,15 @@ import { type ScheduledTaskDraft as Draft, } from "./scheduledTaskDraft"; import { settingsTargetsForProject } from "./settings-environment-filter.logic"; -import { useScheduledTaskDestinationLabel, useScheduledTaskEditor } from "./scheduled-task-editor"; +import { + useScheduledTaskDestinationLabel, + useScheduledTaskEditor, + useScheduledTaskThread, +} from "./scheduled-task-editor"; import { discardScheduledTaskEditor, markScheduledTaskEditorSaved, - scheduledTaskEditorSessionAtom, } from "./scheduled-task-editor-state"; -import { appAtomRegistry } from "../../state/atom-registry"; import { formatNextScheduledTaskRun, formatScheduledTaskInterval, @@ -115,7 +119,7 @@ const THREAD_MODE_LABELS: Record = { fresh_session: "One thread, fresh session", }; -function describeSchedule(task: ScheduledTask): string { +function describeSchedule(task: ScheduledTask, timeZone?: string): string { if (task.schedule.type === "webhook") return "On webhook"; if (task.schedule.type === "once") { const runAt = new Date(task.schedule.runAt); @@ -123,7 +127,8 @@ function describeSchedule(task: ScheduledTask): string { } if (task.schedule.type === "interval") return formatScheduledTaskInterval(task.schedule.everyMs); const days = task.schedule.weekdays?.length ? repeatLabel(task.schedule.weekdays) : "Every day"; - return `${days} at ${formatTime(task.schedule.timeOfDay)}`; + const zone = scheduleTimeZoneLabel(timeZone, task.nextRunAt); + return `${days} at ${formatTime(task.schedule.timeOfDay)}${zone === undefined ? "" : ` ${zone}`}`; } function formatTime(value: string): string { @@ -264,11 +269,13 @@ function SelectRow(props: { function WebhookFilterRows(props: { readonly filters: ReadonlyArray; readonly disabled: boolean; - readonly onChange: (filters: ReadonlyArray) => void; + readonly onChange: ( + update: (filters: ReadonlyArray) => ReadonlyArray, + ) => void; }) { - const update = (index: number, patch: Partial) => - props.onChange( - props.filters.map((filter, at) => (at === index ? { ...filter, ...patch } : filter)), + const update = (id: WebhookFilterDraft["id"], patch: Partial) => + props.onChange((filters) => + filters.map((filter) => (filter.id === id ? { ...filter, ...patch } : filter)), ); return ( <> @@ -281,7 +288,9 @@ function WebhookFilterRows(props: { accessibilityLabel={`Remove filter ${index + 1}`} disabled={props.disabled} hitSlop={8} - onPress={() => props.onChange(removeWebhookFilterDraft(props.filters, filter.id))} + onPress={() => + props.onChange((filters) => removeWebhookFilterDraft(filters, filter.id)) + } className="active:opacity-70" > @@ -292,7 +301,7 @@ function WebhookFilterRows(props: { value={filter.path} placeholder="body.action" disabled={props.disabled} - onChange={(path) => update(index, { path })} + onChange={(path) => update(filter.id, { path })} /> { const known = WEBHOOK_FILTER_OPS.find((option) => option.op === id); - if (known) update(index, { op: known.op }); + if (known) update(filter.id, { op: known.op }); }} /> {filter.op === "exists" ? null : ( @@ -313,7 +322,7 @@ function WebhookFilterRows(props: { value={filter.value} placeholder={filter.op === "in" ? "opened, reopened" : "opened"} disabled={props.disabled} - onChange={(value) => update(index, { value })} + onChange={(value) => update(filter.id, { value })} /> )} @@ -322,7 +331,13 @@ function WebhookFilterRows(props: { props.onChange([...props.filters, emptyWebhookFilterDraft()])} + onPress={() => + props.onChange((filters) => + filters.length < MAX_WEBHOOK_FILTERS + ? [...filters, emptyWebhookFilterDraft()] + : filters, + ) + } className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70" > @@ -514,8 +529,6 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string } const voiceInput = useVoiceInputController({ ownerKey, label: editor?.draft.title.trim() || title, - subscribeToDraftChanges: (onChange) => - appAtomRegistry.subscribe(scheduledTaskEditorSessionAtom, onChange), selection, readDraftMessage: () => { const current = readEditor(); @@ -589,8 +602,19 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string } voiceInput={voiceInput} /> } - setDraft={(draft) => { - if (!saving) setEditor({ ...editor, draft }); + setDraft={(update) => { + if (!saving) + setEditor((current) => + current ? { ...current, draft: update(current.draft) } : current, + ); + }} + setEnvironmentDraft={(update) => { + if (!saving) + setEditor((current) => + current && current.environmentId === editor.environmentId + ? { ...current, draft: update(current.draft) } + : current, + ); }} onSaved={() => { saved.current = true; @@ -598,18 +622,21 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string } if (navigation.isFocused()) navigation.goBack(); }} onChangeEnvironment={(target) => { - if (target.environmentId === editor.environmentId) return; - setEditor({ - environmentId: target.environmentId, - environmentLabel: target.label, - draft: { - ...draftForEnvironment(target.environmentId), - title: editor.draft.title, - prompt: editor.draft.prompt, - schedule: editor.draft.schedule, - enabled: editor.draft.enabled, - }, - }); + setEditor((current) => + !current || target.environmentId === current.environmentId + ? current + : { + environmentId: target.environmentId, + environmentLabel: target.label, + draft: { + ...draftForEnvironment(target.environmentId), + title: current.draft.title, + prompt: current.draft.prompt, + schedule: current.draft.schedule, + enabled: current.draft.enabled, + }, + }, + ); }} /> ) : ( @@ -634,6 +661,7 @@ function TaskForm({ dictationPending, promptField, setDraft, + setEnvironmentDraft, onSaved, onChangeEnvironment, }: { @@ -645,10 +673,12 @@ function TaskForm({ readonly setSaving: (saving: boolean) => void; readonly dictationPending: boolean; readonly promptField: ReactNode; - readonly setDraft: (draft: Draft) => void; + readonly setDraft: (update: (current: Draft) => Draft) => void; + readonly setEnvironmentDraft: (update: (current: Draft) => Draft) => void; readonly onSaved: () => void; readonly onChangeEnvironment: (target: SettingsTarget) => void; }) { + const { readEditor } = useScheduledTaskEditor(); const navigation = useNavigation>(); const tasks = useEnvironmentQuery( serverEnvironment.scheduledTasksLive({ environmentId, input: {} }), @@ -665,6 +695,10 @@ function TaskForm({ .sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null)); const config = useEnvironmentServerConfig(environmentId); const destinationLabel = useScheduledTaskDestinationLabel(environmentId, draft.threadId); + const boundThread = useScheduledTaskThread(environmentId, draft.threadId); + // Bound runs use the thread's current model, so the locked row shows that one. + const shownSelection = + draft.threadId === null ? draft.modelSelection : (boundThread?.modelSelection ?? null); const modelOptions = buildModelOptions(config, null, undefined, draft.projectId); // Existing webhook tasks keep the option so they can still switch to a timer. const webhookDenial = managedCapabilityDenial(config?.managedPolicy, "webhookTasks"); @@ -682,6 +716,7 @@ function TaskForm({ draft.task !== null && tasks.data !== null && !tasks.data.tasks.some((task) => task.id === draft.task?.id); + const runAtZone = scheduleTimeZoneLabel(tasks.data?.timeZone); const environmentUnavailable = !availableTargets.some( (target) => target.environmentId === environmentId, ); @@ -697,6 +732,9 @@ function TaskForm({ draft.task?.schedule.type === "once"; const offersThreadModes = config?.environment.capabilities.scheduledTaskThreadModes === true; const save = async () => { + const current = readEditor(); + if (!current || current.environmentId !== environmentId) return; + const draft = current.draft; if ( !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || submissionPending.current || @@ -755,7 +793,7 @@ function TaskForm({ title: draft.title.trim(), prompt: draft.prompt.trim(), projectId: draft.projectId, - modelSelection: draft.modelSelection, + modelSelection: withImplicitFastModeSelection(draft.modelSelection, config?.providers ?? []), schedule, enabled: draft.enabled, threadId: draft.threadId, @@ -841,7 +879,7 @@ function TaskForm({ disabled={saving} value={draft.title} placeholder="Check for issues" - onChange={(title) => setDraft({ ...draft, title })} + onChange={(title) => setDraft((current) => ({ ...current, title }))} /> {promptField} @@ -861,21 +899,23 @@ function TaskForm({ onSelect={(id) => { const project = projects.find((item) => item.id === id); if (!project) return; - const keepsExplicitModel = - draft.modelSelectionIsExplicit && - (draft.modelSelection === null || - !config?.settings || - resolveProjectProviderInstanceEnabled( - config.settings, - project.id, - draft.modelSelection.instanceId, - )); - setDraft({ - ...changeDraftProject(draft, project.id), - modelSelection: keepsExplicitModel - ? draft.modelSelection - : scheduledTaskDefaultModel(config, project), - modelSelectionIsExplicit: keepsExplicitModel, + setEnvironmentDraft((current) => { + const keepsExplicitModel = + current.modelSelectionIsExplicit && + (current.modelSelection === null || + !config?.settings || + resolveProjectProviderInstanceEnabled( + config.settings, + project.id, + current.modelSelection.instanceId, + )); + return { + ...changeDraftProject(current, project.id), + modelSelection: keepsExplicitModel + ? current.modelSelection + : scheduledTaskDefaultModel(config, project), + modelSelectionIsExplicit: keepsExplicitModel, + }; }); }} /> @@ -885,14 +925,17 @@ function TaskForm({ value={ modelOptions.find( (option) => - option.selection.instanceId === draft.modelSelection?.instanceId && - option.selection.model === draft.modelSelection?.model, + option.selection.instanceId === shownSelection?.instanceId && + option.selection.model === shownSelection?.model, )?.label ?? - draft.modelSelection?.model ?? + shownSelection?.model ?? (modelOptions.length ? "Choose model" : "No models available") } onPress={() => navigation.navigate("SettingsScheduledTaskModel")} - disabled={saving || dictationPending || environmentUnavailable} + // The saved selection only seeds new threads; bound runs ignore it. + disabled={ + saving || dictationPending || environmentUnavailable || draft.threadId !== null + } /> @@ -923,9 +966,9 @@ function TaskForm({ )} onSelect={(id) => { if (id === "new_thread") - setDraft({ ...unbindDraftFromThread(draft), threadMode: id }); + setDraft((current) => ({ ...unbindDraftFromThread(current), threadMode: id })); else if (id === "continue" || id === "fresh_session") - setDraft({ ...draft, threadMode: id }); + setDraft((current) => ({ ...current, threadMode: id })); }} /> ) : null} @@ -973,7 +1016,7 @@ function TaskForm({ ]} onSelect={(id) => { if (id === "worktree" || id === "root" || id === "existing_worktree") - setDraft({ ...draft, workspace: id }); + setDraft((current) => ({ ...current, workspace: id })); }} /> {draft.workspace === "worktree" ? ( @@ -996,10 +1039,10 @@ function TaskForm({ value={draft.checkoutPath} borderTop onChange={(checkoutPath) => - setDraft({ - ...draft, - checkoutPath: resolvePastedPath(draft.checkoutPath, checkoutPath), - }) + setEnvironmentDraft((current) => ({ + ...current, + checkoutPath: resolvePastedPath(current.checkoutPath, checkoutPath), + })) } /> ) : null} @@ -1024,21 +1067,21 @@ function TaskForm({ onSelect={(mode) => { setTimePickerOpen(false); setRunAtPicker(null); - setDraft({ - ...draft, + setDraft((current) => ({ + ...current, prompt: - mode === "webhook" && !draft.prompt.trim() + mode === "webhook" && !current.prompt.trim() ? DEFAULT_WEBHOOK_PROMPT - : draft.prompt, + : current.prompt, schedule: { - ...draft.schedule, + ...current.schedule, mode, runAt: - mode === "once" && !draft.schedule.runAt + mode === "once" && !current.schedule.runAt ? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000).toISOString() - : draft.schedule.runAt, + : current.schedule.runAt, }, - }); + })); }} /> @@ -1046,7 +1089,9 @@ function TaskForm({ <> setTimePickerOpen((open) => !open)} className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70" > @@ -1058,6 +1103,7 @@ function TaskForm({ className="min-w-0 flex-1 text-right text-foreground-muted" > {formatTime(draft.schedule.timeOfDay)} + {runAtZone ? ` ${runAtZone}` : ""} setTimePickerOpen(false)} onValueChange={(_, selected) => { const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`; - setDraft({ ...draft, schedule: { ...draft.schedule, timeOfDay } }); + setDraft((current) => ({ + ...current, + schedule: { ...current.schedule, timeOfDay }, + })); }} /> ) : null} @@ -1103,19 +1152,21 @@ function TaskForm({ })), ]} onSelect={(id) => { - const weekdays = - id === "every_day" - ? DAYS.map((day) => day.index) - : id === "weekdays" - ? [1, 2, 3, 4, 5] - : (() => { - const day = DAYS.find((item) => String(item.index) === id); - if (!day) return draft.schedule.weekdays; - return draft.schedule.weekdays.includes(day.index) - ? draft.schedule.weekdays.filter((index) => index !== day.index) - : [...draft.schedule.weekdays, day.index]; - })(); - setDraft({ ...draft, schedule: { ...draft.schedule, weekdays } }); + setDraft((current) => { + const weekdays = + id === "every_day" + ? DAYS.map((day) => day.index) + : id === "weekdays" + ? [1, 2, 3, 4, 5] + : (() => { + const day = DAYS.find((item) => String(item.index) === id); + if (!day) return current.schedule.weekdays; + return current.schedule.weekdays.includes(day.index) + ? current.schedule.weekdays.filter((index) => index !== day.index) + : [...current.schedule.weekdays, day.index]; + })(); + return { ...current, schedule: { ...current.schedule, weekdays } }; + }); }} /> @@ -1160,10 +1211,10 @@ function TaskForm({ onValueChange={(_, selected) => { // Android shows a dialog that closes on pick; iOS stays inline. if (Platform.OS === "android") setRunAtPicker(null); - setDraft({ - ...draft, - schedule: { ...draft.schedule, runAt: selected.toISOString() }, - }); + setDraft((current) => ({ + ...current, + schedule: { ...current.schedule, runAt: selected.toISOString() }, + })); }} /> ) : null} @@ -1186,8 +1237,11 @@ function TaskForm({ - setDraft({ ...draft, schedule: { ...draft.schedule, filters } }) + onChange={(update) => + setDraft((current) => ({ + ...current, + schedule: { ...current.schedule, filters: update(current.schedule.filters) }, + })) } /> - setDraft({ ...draft, schedule: { ...draft.schedule, replayKey } }) + setDraft((current) => ({ + ...current, + schedule: { ...current.schedule, replayKey }, + })) } /> @@ -1210,7 +1267,10 @@ function TaskForm({ disabled={saving} borderTop onChange={(coalesceKey) => - setDraft({ ...draft, schedule: { ...draft.schedule, coalesceKey } }) + setDraft((current) => ({ + ...current, + schedule: { ...current.schedule, coalesceKey }, + })) } /> - setDraft({ ...draft, schedule: { ...draft.schedule, coalesceWindowSeconds } }) + setDraft((current) => ({ + ...current, + schedule: { ...current.schedule, coalesceWindowSeconds }, + })) } /> @@ -1238,7 +1301,10 @@ function TaskForm({ disabled={saving} borderTop onChange={(intervalMinutes) => - setDraft({ ...draft, schedule: { ...draft.schedule, intervalMinutes } }) + setDraft((current) => ({ + ...current, + schedule: { ...current.schedule, intervalMinutes }, + })) } /> {!(parseIntervalMinutes(draft.schedule.intervalMinutes) >= 1) ? ( @@ -1261,7 +1327,7 @@ function TaskForm({ setDraft({ ...draft, enabled })} + onValueChange={(enabled) => setDraft((current) => ({ ...current, enabled }))} /> @@ -1472,7 +1538,7 @@ function EnvironmentTasks({ {task.title} - {describeSchedule(task)} + {describeSchedule(task, tasks.data?.timeZone)} {!task.enabled ? " · Paused" : task.nextRunAt diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 1207ccf1ef..0da0f334c7 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -42,6 +42,8 @@ import { import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs"; import { AutoSettleSettingsRows } from "./ThreadSettingsSections"; import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings"; +import { isSourceControlProviderOffered } from "@t3tools/client-runtime/operations/projects"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; type SettingsPage = "threads" | "source-control" | "worktrees" | "maintenance"; @@ -399,6 +401,31 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { {props.page === "source-control" ? ( <> + {projectSelected ? null : ( + + {sourceControlClients.definitions.map((definition) => { + const offered = displayTargets.map((target) => + isSourceControlProviderOffered( + target.settings.offeredSourceControlProviders, + definition.kind, + ), + ); + return ( + value === offered[0]) ? offered[0]! : null + } + disabled={disabledFor("offeredSourceControlProviders")} + onValueChange={(value) => + write({ offeredSourceControlProviders: { [definition.kind]: value } }) + } + /> + ); + })} + + )} write({ continueThreadsAfterServerUpdate: value })} /> + + write({ keepAwakeWhileAgentsWork: value })} + /> + ) : null} diff --git a/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx index 56493a60a5..476199a7db 100644 --- a/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx @@ -1,9 +1,11 @@ +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { LegendList } from "@legendapp/list/react-native"; import { useAtomValue } from "@effect/atom-react"; import type { StaticScreenProps } from "@react-navigation/native"; import type { EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { useState } from "react"; -import { FlatList, Platform, View } from "react-native"; +import { Platform, View } from "react-native"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { AppText as Text } from "../../components/ui/AppText"; @@ -54,9 +56,13 @@ export function SettingsVoiceModelsRouteScreen({ onQueryChange={setQuery} > {({ paddingBottom }) => ( - model.id} + extraData={{ voice, language, count: models.length }} + estimatedItemSize={72} + recycleItems className="flex-1" contentInsetAdjustmentBehavior="automatic" automaticallyAdjustKeyboardInsets={Platform.OS === "ios"} diff --git a/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts index ffeb6114c1..c71298a898 100644 --- a/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts +++ b/apps/mobile/src/features/settings/appearance/useScaledTextRole.ts @@ -1,4 +1,6 @@ -import { resolveScaledTextRole } from "../../../lib/appearancePreferences"; +import { Platform, useWindowDimensions } from "react-native"; + +import { resolveComposerTextRole, resolveScaledTextRole } from "../../../lib/appearancePreferences"; import { MOBILE_TYPOGRAPHY } from "../../../lib/typography"; import { useAppearancePreferences } from "./AppearancePreferencesProvider"; @@ -12,3 +14,9 @@ export function useScaledTextRole(role: keyof typeof MOBILE_TYPOGRAPHY): ScaledT const { appearance } = useAppearancePreferences(); return resolveScaledTextRole(role, appearance.baseFontSize); } + +export function useComposerTextRole(): ScaledTextRole { + const body = useScaledTextRole("body"); + const { fontScale } = useWindowDimensions(); + return resolveComposerTextRole(body, fontScale, Platform.OS); +} diff --git a/apps/mobile/src/features/settings/components/settings-page-targets.ts b/apps/mobile/src/features/settings/components/settings-page-targets.ts index 70281c01e6..d55dbc83b8 100644 --- a/apps/mobile/src/features/settings/components/settings-page-targets.ts +++ b/apps/mobile/src/features/settings/components/settings-page-targets.ts @@ -4,6 +4,7 @@ export const SETTINGS_PAGE_TARGETS = [ "SettingsThreads", "SettingsAbout", "SettingsAppearance", + "SettingsLanguage", "SettingsNavigation", "SettingsOrganization", "SettingsProjectOverview", diff --git a/apps/mobile/src/features/settings/scheduled-task-editor.tsx b/apps/mobile/src/features/settings/scheduled-task-editor.tsx index e99600ae53..d79ef40896 100644 --- a/apps/mobile/src/features/settings/scheduled-task-editor.tsx +++ b/apps/mobile/src/features/settings/scheduled-task-editor.tsx @@ -21,22 +21,29 @@ import { export const NEW_THREAD_DESTINATION_LABEL = "New thread each run"; -export function useScheduledTaskDestinationLabel( +export function useScheduledTaskThread( environmentId: EnvironmentId | null, threadId: ThreadId | null, -): string { +) { const ref = environmentId === null || threadId === null ? null : scopeThreadRef(environmentId, threadId); const shell = useThreadShell(ref); - // The shell can omit older settled threads; their family read still carries the title. + // The shell can omit older settled threads; their family read still carries the row. const family = useEnvironmentQuery( ref !== null && shell === null ? threadFamilies.familyAtom(ref.environmentId, ref.threadId) : null, ); - const thread = shell ?? family.data?.threads.find((row) => row.id === threadId); - if (ref === null) return NEW_THREAD_DESTINATION_LABEL; - return thread?.title.trim() || `Thread ${ref.threadId}`; + return shell ?? family.data?.threads.find((row) => row.id === threadId) ?? null; +} + +export function useScheduledTaskDestinationLabel( + environmentId: EnvironmentId | null, + threadId: ThreadId | null, +): string { + const thread = useScheduledTaskThread(environmentId, threadId); + if (environmentId === null || threadId === null) return NEW_THREAD_DESTINATION_LABEL; + return thread?.title.trim() || `Thread ${threadId}`; } /** The form draft lives in an atom, so it survives while its native picker routes are on top. */ diff --git a/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts b/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts new file mode 100644 index 0000000000..02ca0a2d11 --- /dev/null +++ b/apps/mobile/src/features/settings/scheduledTaskPresentation.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { formatNextScheduledTaskRun } from "./scheduledTaskPresentation"; + +describe("formatNextScheduledTaskRun", () => { + it("names the rounded unit for a run later today", () => { + const now = new Date(2026, 10, 3, 10, 0, 0).getTime(); + const at = (minutes: number) => new Date(now + minutes * 60_000).toISOString(); + expect(formatNextScheduledTaskRun(at(59), now)).toBe("Next run in 59 minutes"); + expect(formatNextScheduledTaskRun(at(59.5), now)).toBe("Next run in 1 hour"); + expect(formatNextScheduledTaskRun(at(150), now)).toBe("Next run in 3 hours"); + }); +}); diff --git a/apps/mobile/src/features/settings/scheduledTaskPresentation.ts b/apps/mobile/src/features/settings/scheduledTaskPresentation.ts index 0fbc2626f1..7ebdcfc2d3 100644 --- a/apps/mobile/src/features/settings/scheduledTaskPresentation.ts +++ b/apps/mobile/src/features/settings/scheduledTaskPresentation.ts @@ -38,8 +38,9 @@ export function formatNextScheduledTaskRun(nextRunAt: string, now: number): stri const days = localCalendarDay(next) - localCalendarDay(current); if (days === 0) { if (remaining < MINUTE) return "Next run in less than a minute"; - const unit = remaining < HOUR ? "minute" : "hour"; - const count = Math.round(remaining / (remaining < HOUR ? MINUTE : HOUR)); + const minutes = Math.round(remaining / MINUTE); + const unit = minutes < 60 ? "minute" : "hour"; + const count = minutes < 60 ? minutes : Math.round(remaining / HOUR); return `Next run in ${count} ${unit}${count === 1 ? "" : "s"}`; } diff --git a/apps/mobile/src/features/settings/settings-navigation.ts b/apps/mobile/src/features/settings/settings-navigation.ts index a5cc562961..c1fc8e4d87 100644 --- a/apps/mobile/src/features/settings/settings-navigation.ts +++ b/apps/mobile/src/features/settings/settings-navigation.ts @@ -85,6 +85,24 @@ export function settingsNavigationState, + current: NavigationState | undefined, +) { + const top = link.routes.at(-1); + if (!current || !top || top.state || !isSettingsRoute(top.name)) return undefined; + const page = top.name === "Settings" ? undefined : (top.name as SettingsPageName); + return { + type: "RESET" as const, + payload: settingsNavigationState(current, page, top.params), + target: current.key, + }; +} + /** Opens one Settings page in the Settings tab, from anywhere outside it. */ export function openSettings( navigation: RootStackNavigation, diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 3e798975d7..1dea547de5 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -54,7 +54,7 @@ describe("incoming native shares", () => { text: "Please explain this error\n\nhttps://example.com/issue/1", attachments: [ { - id: "share-1:image:3", + id: "share-1-image-3", type: "image", name: "Screenshot.png", mimeType: "image/png", @@ -131,7 +131,7 @@ describe("incoming native shares", () => { expect(result.attachments).toEqual([ { - id: "share-report:file:0", + id: "share-report-file-0", type: "file", name: "report.pdf", mimeType: "application/pdf", @@ -165,7 +165,7 @@ describe("incoming native shares", () => { expect(result.warnings).toEqual([]); expect(result.attachments).toEqual([ { - id: "share-video:file:0", + id: "share-video-file-0", type: "file", name: video.originalName, mimeType: video.mimeType, @@ -239,7 +239,7 @@ describe("incoming native shares", () => { expect(result.attachments).toEqual([ { - id: "share-android-report:file:0", + id: "share-android-report-file-0", type: "file", name: "report", mimeType: "application/pdf", diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index aa09771392..aa97294e15 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -332,7 +332,7 @@ export async function buildIncomingShareDraft(input: { } } attachments.push({ - id: `${input.id}:file:${index}`, + id: `${input.id}-file-${index}`, type: "file", name, mimeType, @@ -397,7 +397,7 @@ export async function buildIncomingShareDraft(input: { } const dataUrl = `data:${mimeType};base64,${base64}`; attachments.push({ - id: `${input.id}:image:${index}`, + id: `${input.id}-image-${index}`, type: "image", name: resolved?.originalName ?? fallbackName(uri, index, mimeType), mimeType, diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts index c985506480..961c0f42fa 100644 --- a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts +++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; vi.mock("expo-quick-actions", () => ({})); vi.mock("react-native", () => ({ Platform: { OS: "android" } })); +vi.mock("../../connection/catalog", () => ({})); vi.mock("../../persistence/imperative", () => ({})); vi.mock("../../state/atom-registry", () => ({})); vi.mock("../../state/threads", () => ({ environmentThreadShells: {} })); @@ -54,6 +55,23 @@ describe("createRecentThreadShortcuts", () => { expect(save).toHaveBeenLastCalledWith([thread("a")]); }); + it("drops threads of environments that are no longer saved", async () => { + const gone = { environmentId: "gone", threadId: "b", title: "b" }; + const kept = { environmentId: "kept", threadId: "c", title: "c" }; + const { save, publish, recents } = setup(() => Promise.resolve([thread("a"), gone, kept])); + recents.retainEnvironments(new Set(["env", "kept"])); + await recents.loaded; + expect(publish).toHaveBeenLastCalledWith([thread("a"), kept]); + + recents.retainEnvironments(new Set(["kept"])); + await recents.saved(); + expect(publish).toHaveBeenLastCalledWith([kept]); + expect(save).toHaveBeenLastCalledWith([kept]); + + recents.recordActiveThread(thread("a")); + expect(publish).toHaveBeenLastCalledWith([kept]); + }); + it("records title changes of the open thread and ignores repeats", async () => { const { publish, recents } = setup(() => Promise.resolve([])); await recents.loaded; diff --git a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts index b182c33b07..a8c3d7b964 100644 --- a/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts +++ b/apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts @@ -4,6 +4,7 @@ import type { NavigationState } from "@react-navigation/native"; import type { ScopedThreadRef } from "@t3tools/contracts"; import { Atom } from "effect/reactivity"; +import { environmentCatalog } from "../../connection/catalog"; import { loadRecentThreadShortcuts, saveRecentThreadShortcuts, @@ -34,6 +35,7 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD let recents: ReadonlyArray | null = null; let persistable = false; let active: RecentThreadShortcut | null = null; + let savedEnvironmentIds: ReadonlySet | null = null; // Serialize saves so older lists cannot overwrite newer ones. let saveQueue: Promise = Promise.resolve(); @@ -53,8 +55,11 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD }); }; + const isSaved = (thread: RecentThreadShortcut) => + savedEnvironmentIds?.has(thread.environmentId) ?? true; + const withActive = (list: ReadonlyArray) => { - if (active === null) return list; + if (active === null || !isSaved(active)) return list; const next = withRecentThreadShortcut(list, active); if (next !== list) persistable = true; return next; @@ -63,7 +68,7 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD const loaded = dependencies.load().then( (threads) => { persistable = true; - commit(withActive(threads)); + commit(withActive(threads.filter(isSaved))); }, (error: unknown) => { console.warn("[app-shortcuts] failed to load recent threads", error); @@ -81,6 +86,12 @@ export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsD const updated = withActive(recents); if (updated !== recents) commit(updated); }, + retainEnvironments(next: ReadonlySet): void { + savedEnvironmentIds = next; + if (recents === null) return; + const kept = recents.filter(isSaved); + if (kept.length !== recents.length) commit(kept); + }, }; } @@ -142,8 +153,16 @@ export function installAppShortcuts(navigate: (href: string) => void): () => voi (active) => recents.recordActiveThread(active), { immediate: true }, ); + const unsubscribeCatalog = appAtomRegistry.subscribe( + environmentCatalog.catalogValueAtom, + (catalog) => { + if (catalog.isReady) recents.retainEnvironments(new Set(catalog.entries.keys())); + }, + { immediate: true }, + ); return () => { subscription.remove(); unsubscribe(); + unsubscribeCatalog(); }; } diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx index 5202257e3b..ab0ba504ac 100644 --- a/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx +++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx @@ -1,7 +1,7 @@ import { applyTerminalAttachStreamEvent, EMPTY_TERMINAL_BUFFER_STATE, - terminalOutputText, + terminalOutputReplay, } from "@t3tools/client-runtime/state/terminal"; import { act, useImperativeHandle, useLayoutEffect, type ReactNode } from "react"; import { createRoot } from "react-dom/client"; @@ -106,7 +106,7 @@ function setup(revision: number | null) { ? null : (revision ?? 0) >= 1 ? "" - : terminalOutputText(state.output) + : terminalOutputReplay(state.output) } isRunning onInput={() => {}} @@ -163,6 +163,24 @@ it.each([null, 1])( } else { expect(mocks.write).not.toHaveBeenCalled(); expect(mocks.initialBuffers).toEqual(["retained", "ined-new"]); + // An older binary recreates its emulator unless the next buffer extends the last one. + // The buffer is full here, so the erase must not push the earlier output out. + let cleared = applyTerminalAttachStreamEvent( + state, + { type: "output", threadId: "thread", terminalId: "term-1", data: "\u001b[?1049h" }, + 16, + ); + await harness.render(cleared); + cleared = applyTerminalAttachStreamEvent( + cleared, + { type: "cleared", threadId: "thread", terminalId: "term-1" }, + 16, + ); + await harness.render(cleared); + expect(mocks.initialBuffers.slice(2)).toEqual([ + "ined-new\u001b[?1049h", + "ined-new\u001b[?1049h\u001b[H\u001b[2J\u001b[3J", + ]); } }, ); diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx index 1702c2f303..333cb9c0ea 100644 --- a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx +++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx @@ -1,4 +1,8 @@ -import type { TerminalGrid, TerminalOutputState } from "@t3tools/client-runtime/state/terminal"; +import { + terminalOutputText, + type TerminalGrid, + type TerminalOutputState, +} from "@t3tools/client-runtime/state/terminal"; import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react"; import { Pressable, @@ -199,7 +203,12 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface({ }); export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) { - const buffer = useTerminalSurfaceBuffer(props); + // The text fallback draws escape sequences literally, so it gets displayed text, not the replay. + const buffer = useTerminalSurfaceBuffer( + resolveNativeTerminalSurfaceView() || props.output === null + ? props + : { terminalKey: props.terminalKey, buffer: terminalOutputText(props.output) }, + ); return ; }); diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index 90fac17f80..f3ed8b0198 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -2,6 +2,7 @@ import * as Dialog from "../../components/ui/Dialog"; import { AuthTerminalReadScope, AuthTerminalOperateScope, + chunkTerminalWrite, DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId, @@ -40,7 +41,6 @@ import { LoadingScreen } from "../../components/LoadingScreen"; import { ScreenContent } from "../../components/ui/ScreenContent"; import { Button } from "../../components/ui/Button"; import { IconButton } from "../../components/ui/IconButton"; -import { environmentCatalog } from "../../connection/catalog"; import { useEnvironmentPresentation } from "../../state/presentation"; import { terminalEnvironment } from "../../state/terminal"; import { environmentSession, readEnvironmentScope } from "../../state/session"; @@ -64,6 +64,7 @@ import { import { useThreadSelection } from "../../state/use-thread-selection"; import { useSelectedThreadProjection } from "../../state/use-thread-detail"; import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice"; +import { useRetryEnvironment } from "../connection/useRetryEnvironment"; import { TerminalSurface, type TerminalSurfaceHandle } from "./NativeTerminalSurface"; import { getMobileTerminalTheme } from "./terminalTheme"; import { useTerminalExitNavigation } from "./useTerminalExitNavigation"; @@ -381,7 +382,7 @@ function ThreadTerminal(props: { const navigation = useNavigation(); const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear"); - const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry"); + const retryEnvironment = useRetryEnvironment(); const selectedThreadDetail = useSelectedThreadProjection(); const selectedThreadDetailWorktreePath = selectedThreadDetail?.projection.thread.worktreePath ?? null; @@ -607,15 +608,21 @@ function ThreadTerminal(props: { return false; } - const result = await writeTerminal({ - environmentId: selectedThread.environmentId, - input: { - threadId: selectedThread.id, - terminalId, - data, - }, - }); - return result._tag === "Success"; + // Android's IME delivers a system paste as one input, which can exceed one write. + const isSameShell = pasteSession.liveness(); + for (const chunk of chunkTerminalWrite(data)) { + if (!isSameShell()) return false; + const result = await writeTerminal({ + environmentId: selectedThread.environmentId, + input: { + threadId: selectedThread.id, + terminalId, + data: chunk, + }, + }); + if (result._tag !== "Success") return false; + } + return true; }; const pasteText = async (readText: () => Promise) => { @@ -893,7 +900,7 @@ function ThreadTerminal(props: { title="No terminal sessions" detail="Existing terminals will appear here when another client opens one." /> - ) : !canOperateTerminal && terminal.error !== null ? ( + ) : terminal.error !== null && (!canOperateTerminal || terminal.status === "error") ? ( ) : ( <> diff --git a/apps/mobile/src/features/terminal/terminalInput.test.ts b/apps/mobile/src/features/terminal/terminalInput.test.ts index 17fabe5881..6e5046dab3 100644 --- a/apps/mobile/src/features/terminal/terminalInput.test.ts +++ b/apps/mobile/src/features/terminal/terminalInput.test.ts @@ -1,11 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { - chunkTerminalWrite, - encodeTerminalPaste, - resolveModifiedTerminalInput, - TERMINAL_WRITE_MAX_LENGTH, -} from "./terminalInput"; +import { encodeTerminalPaste, resolveModifiedTerminalInput } from "./terminalInput"; const byte = (code: number) => String.fromCharCode(code); const ESC = byte(0x1b); @@ -78,23 +73,3 @@ describe("encodeTerminalPaste", () => { expect(encodeTerminalPaste(`safe${ESC}[201~; rm -rf /\n`)).toBe("safe [201~; rm -rf /\r"); }); }); - -describe("chunkTerminalWrite", () => { - it("splits oversized writes so every chunk fits the contract", () => { - const chunks = chunkTerminalWrite("y".repeat(TERMINAL_WRITE_MAX_LENGTH * 2 + 5)); - expect(chunks.map((chunk) => chunk.length)).toEqual([ - TERMINAL_WRITE_MAX_LENGTH, - TERMINAL_WRITE_MAX_LENGTH, - 5, - ]); - expect(chunks.join("")).toHaveLength(TERMINAL_WRITE_MAX_LENGTH * 2 + 5); - }); - - it("does not cut a surrogate pair in half at the boundary", () => { - const data = `${"z".repeat(TERMINAL_WRITE_MAX_LENGTH - 1)}😀tail`; - const chunks = chunkTerminalWrite(data); - expect(chunks[0]).toHaveLength(TERMINAL_WRITE_MAX_LENGTH - 1); - expect(chunks[1]).toBe("😀tail"); - expect(chunks.join("")).toBe(data); - }); -}); diff --git a/apps/mobile/src/features/terminal/terminalInput.ts b/apps/mobile/src/features/terminal/terminalInput.ts index 9c5e05dcc2..0f09d109e3 100644 --- a/apps/mobile/src/features/terminal/terminalInput.ts +++ b/apps/mobile/src/features/terminal/terminalInput.ts @@ -3,9 +3,6 @@ import type { ExecutionEnvironmentPlatformOs } from "@t3tools/contracts"; export type PendingModifier = "ctrl" | "meta"; export type HostPlatform = "mac" | "linux" | "windows" | "unknown"; -/** Upper bound of `TerminalWriteInput.data`; longer writes are rejected by the server. */ -export const TERMINAL_WRITE_MAX_LENGTH = 65_536; - export type ModifiedTerminalInput = | { readonly kind: "write"; readonly data: string } | { readonly kind: "paste" }; @@ -64,21 +61,6 @@ export function encodeTerminalPaste(text: string): string { return text.replace(UNSAFE_PASTE_BYTES, " ").replace(/\r\n|\n/g, "\r"); } -export function chunkTerminalWrite(data: string): ReadonlyArray { - const chunks: string[] = []; - let start = 0; - while (start < data.length) { - let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length); - const last = data.charCodeAt(end - 1); - if (end < data.length && last >= 0xd800 && last <= 0xdbff) { - end -= 1; - } - chunks.push(data.slice(start, end)); - start = end; - } - return chunks; -} - /** Returns null for unknown OSes so callers can try weaker signals. */ export function hostPlatformFromOs(os: ExecutionEnvironmentPlatformOs | null): HostPlatform | null { if (os === "darwin") return "mac"; diff --git a/apps/mobile/src/features/terminal/terminalPaste.test.ts b/apps/mobile/src/features/terminal/terminalPaste.test.ts index ec9bd9d74d..2545085137 100644 --- a/apps/mobile/src/features/terminal/terminalPaste.test.ts +++ b/apps/mobile/src/features/terminal/terminalPaste.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { TERMINAL_WRITE_MAX_LENGTH } from "./terminalInput"; +import { TERMINAL_WRITE_MAX_LENGTH } from "@t3tools/contracts"; import { createTerminalPasteSession } from "./terminalPaste"; function deferred() { @@ -34,6 +34,15 @@ describe("terminal paste session", () => { expect(writes).toEqual([]); }); + it("reports a liveness change after capture, including a restart in place", () => { + const session = createTerminalPasteSession(); + session.reset(true); + const isSameShell = session.liveness(); + expect(isSameShell()).toBe(true); + session.reset(true); + expect(isSameShell()).toBe(false); + }); + it("never overlaps writes from rapid paste requests", async () => { const session = createTerminalPasteSession(); session.reset(true); diff --git a/apps/mobile/src/features/terminal/terminalPaste.ts b/apps/mobile/src/features/terminal/terminalPaste.ts index d070bdc168..b09e365587 100644 --- a/apps/mobile/src/features/terminal/terminalPaste.ts +++ b/apps/mobile/src/features/terminal/terminalPaste.ts @@ -1,4 +1,6 @@ -import { chunkTerminalWrite, encodeTerminalPaste } from "./terminalInput"; +import { chunkTerminalWrite } from "@t3tools/contracts"; + +import { encodeTerminalPaste } from "./terminalInput"; interface TerminalPasteInput { readonly readText: () => Promise; @@ -8,6 +10,8 @@ interface TerminalPasteInput { export interface TerminalPasteSession { readonly reset: (active: boolean) => void; + /** True until the terminal's liveness changes (stop, start or restart) after this call. */ + readonly liveness: () => () => boolean; readonly paste: (input: TerminalPasteInput) => Promise; } @@ -21,6 +25,11 @@ export function createTerminalPasteSession(): TerminalPasteSession { liveTarget = active ? {} : null; }, + liveness() { + const target = liveTarget; + return () => liveTarget === target; + }, + async paste({ readText, write, onReadError }) { const target = liveTarget; if (target === null) { diff --git a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx index 304820fa81..f49391212b 100644 --- a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx +++ b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx @@ -167,7 +167,7 @@ function emptyText(triggerKind: ComposerTriggerKind | null, isLoading: boolean): case "pull-request": return "No matching pull requests."; case "path": - return "No matching files or folders."; + return "No matching mentions."; case "skill": return "No skills found."; case "slash-command": @@ -242,7 +242,10 @@ const CommandRow = memo(function CommandRow(props: { ) : null} {props.isSlashSkill && props.item.type === "skill" ? ( diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx index 231708c29e..82877a13d8 100644 --- a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx +++ b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx @@ -19,12 +19,14 @@ import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; +import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; const ROW_BOTTOM_MARGIN = 8; +const ACTION_ROW_HEIGHT = 32; const FULL_SCREEN_GUTTER = 16; export function htmlRenderRowHeight(frameHeight: number) { - return frameHeight + ROW_BOTTOM_MARGIN; + return ACTION_ROW_HEIGHT + frameHeight + ROW_BOTTOM_MARGIN; } function useHtmlRenderTheme() { @@ -128,6 +130,7 @@ export function HtmlRenderWebView(props: { showsVerticalScrollIndicator={!props.nested} showsHorizontalScrollIndicator={!props.nested} scrollEnabled={scrollable} + decelerationRate={webViewDecelerationRate} // Android's patched WebView always keeps horizontal drags. Only pages // with vertical overflow hold vertical drags until they reach an edge. nestedScrollEnabled={props.nested && overflow.y} @@ -209,6 +212,34 @@ export function ThreadHtmlRender(props: { return ( + + {uri !== null && !failed ? ( + + navigation.navigate("ThreadAttachment", { + environmentId: String(props.environmentId), + threadId: String(props.threadId), + attachmentId, + name: fileName, + mimeType: "text/html", + sizeBytes: "0", + htmlRender: "1", + }) + } + > + + + ) : null} + {uri !== null && !failed ? ( )} - {uri !== null && !failed ? ( - - navigation.navigate("ThreadAttachment", { - environmentId: String(props.environmentId), - threadId: String(props.threadId), - attachmentId, - name: fileName, - mimeType: "text/html", - sizeBytes: "0", - htmlRender: "1", - }) - } - > - - - ) : null} ); diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx index b13e9e4470..aee091d9f5 100644 --- a/apps/mobile/src/features/threads/LinkRequestCard.tsx +++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx @@ -290,6 +290,7 @@ function LinkRequestSheet(props: { dismissDisabled={busy} > - Agents here can then launch, message and wait on threads there. It appears in that - machine's Connections, where it can be revoked. + Agents here can then launch, message and wait on threads there. It appears under + Authorized clients in that machine's Sharing & access, where it can be revoked. {item.url !== undefined && target.kind === "machine" ? ( @@ -374,7 +375,7 @@ function LinkRequestSheet(props: { {useExisting ? ( This environment is already linked to {targetName}. The agent can use that link as it - is; change its access in Settings → Connections. + is; change its access in Settings → Environments. ) : target.kind === "none" ? null : ( <> @@ -393,8 +394,8 @@ function LinkRequestSheet(props: { spellCheck={false} /> - Create a link on {targetName}: Settings → Connections → Create link, then paste - its code here. + Create a link on {targetName}: Settings → Sharing & access → Authorized clients → + Create link, then paste its code here. )} diff --git a/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx b/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx index de3041c06b..747b9a9fc1 100644 --- a/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx +++ b/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx @@ -56,6 +56,41 @@ function descendsFrom( /** Resolve apps from stored tool calls so links cannot supply apps the call never produced. */ export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) { + const navigation = useNavigation(); + const { environmentId, threadId, itemId } = route.params; + if (!environmentId?.trim() || !threadId?.trim() || !itemId?.trim()) { + return ( + + navigation.goBack()} + closeAccessibilityLabel="Exit full screen" + /> + This app cannot be shown. + + ); + } + return ( + + ); +} + +function McpAppFullscreen({ + params, + environmentId, + threadId, + itemId, +}: { + readonly params: McpAppFullscreenScreenProps["route"]["params"]; + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly itemId: TurnItemId; +}) { const navigation = useNavigation(); const insets = useSafeAreaInsets(); // Wait for focus before goBack; an exit under another screen must not pop that screen. @@ -74,10 +109,6 @@ export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) { }); }; const [size, setSize] = useState({ width: 0, height: 0 }); - const params = route.params; - const environmentId = EnvironmentId.make(params.environmentId); - const threadId = ThreadId.make(params.threadId); - const itemId = TurnItemId.make(params.itemId); const conversationThreadId = useConversationThreadId( environmentId, threadId, diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsx index 5fff5e2069..6b8e11895a 100644 --- a/apps/mobile/src/features/threads/McpAppWebView.tsx +++ b/apps/mobile/src/features/threads/McpAppWebView.tsx @@ -34,6 +34,7 @@ import { shareGeneratedAttachment } from "../../lib/attachmentDownload"; import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { uuidv4 } from "../../lib/uuid"; +import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; import { useAssetUrlState } from "../../state/assets"; import { appAtomRegistry } from "../../state/atom-registry"; import { useThreadShell } from "../../state/entities"; @@ -261,6 +262,8 @@ export function ThreadMcpApp(props: { ); }, [host, detailAtom]); const userActive = useRef(false); + // Teardown completions check this so a replaced document's late callback is ignored. + const currentHost = useRef(null); // Each WebView document gets its own host: the view is keyed by document, // restart generation and URL, and a changed app re-attaches this callback. @@ -396,6 +399,8 @@ export function ThreadMcpApp(props: { } if (mode === "fullscreen" && current.displayMode !== "fullscreen") { await documentHost.teardown(); + // A crash restart or reload during the wait already replaced this document. + if (currentHost.current !== documentHost) return "inline"; // Approval arrival or navigation during the wait requires reloading inline. const navigation = latest.current.navigation; if (latest.current.awaitingUser || !navigation.isFocused()) { @@ -414,7 +419,7 @@ export function ThreadMcpApp(props: { } if (mode === "inline" && current.displayMode === "fullscreen") { await documentHost.teardown(); - current.onExitFullscreen?.(); + if (currentHost.current === documentHost) current.onExitFullscreen?.(); return "inline"; } return current.displayMode ?? "inline"; @@ -457,11 +462,11 @@ export function ThreadMcpApp(props: { }, onRequestTeardown: () => { const current = latest.current.props; - if (current.displayMode === "fullscreen") { - void documentHost.teardown().then(() => current.onExitFullscreen?.()); - } else { - void documentHost.teardown().then(() => setClosed(true)); - } + void documentHost.teardown().then(() => { + if (currentHost.current !== documentHost) return; + if (current.displayMode === "fullscreen") current.onExitFullscreen?.(); + else setClosed(true); + }); }, onSizeChanged: (size) => { if (latest.current.props.displayMode === "fullscreen") return; @@ -470,7 +475,9 @@ export function ThreadMcpApp(props: { }, }); setHost(documentHost); + currentHost.current = documentHost; return () => { + if (currentHost.current === documentHost) currentHost.current = null; // An unmount cannot wait: the request goes out before the view does. void documentHost.teardown(); setHost((current) => (current === documentHost ? null : current)); @@ -534,6 +541,7 @@ export function ThreadMcpApp(props: { accessibilityLabel={`${app.server} app`} style={{ flex: 1, backgroundColor: "transparent" }} nestedScrollEnabled + decelerationRate={webViewDecelerationRate} originWhitelist={["*"]} // Android misreports nested frames as top-level; rely on iframe sandboxing there and gate navigation elsewhere. onShouldStartLoadWithRequest={(request) => diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index c96c7768b5..a32062daad 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -284,11 +284,15 @@ export function NewTaskDraftScreen(props: { ), ); // A route naming a draft that is gone, or whose project is gone, also - // returns to the picker. - const isRouteDraftMissing = - props.draftId !== undefined && flow.missingRouteDraftId === props.draftId; + // returns to the picker; a draft that survives goes along with it. + const unopenableRouteDraftKind = + props.draftId !== undefined && flow.unopenableRouteDraft?.draftId === props.draftId + ? flow.unopenableRouteDraft.kind + : null; + const pickerDraftId = unopenableRouteDraftKind === "pickProject" ? props.draftId : undefined; const isProjectPickerReturnActive = - (isReturningToProjectPicker && !requestedInitialProjectAvailable) || isRouteDraftMissing; + (isReturningToProjectPicker && !requestedInitialProjectAvailable) || + unopenableRouteDraftKind !== null; const isIncomingShareAwaitingServerConfig = Boolean( incomingShare?.attachments.some((attachment) => attachment.type === "file") && selectedEnvironmentServerConfig === null, @@ -367,10 +371,6 @@ export function NewTaskDraftScreen(props: { }; const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : []; useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment); - const composerWorkspaceCwd = - (flow.workspaceMode === "worktree" - ? selectedProject?.workspaceRoot - : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null; const preventRemove = (isIncomingShareHoldingRoute && !isProjectPickerReturnActive) || flow.submitting; usePreventRemove(preventRemove, () => undefined); @@ -391,7 +391,10 @@ export function NewTaskDraftScreen(props: { // Wait for usePreventRemove to disable before replacing, or the transfer guard swallows the fallback. const frame = requestAnimationFrame(() => { navigation.dispatch( - StackActions.replace("NewTaskProject", { incomingShareId: props.incomingShareId }), + StackActions.replace("NewTaskProject", { + incomingShareId: props.incomingShareId, + draftId: pickerDraftId, + }), ); }); return () => cancelAnimationFrame(frame); @@ -399,6 +402,7 @@ export function NewTaskDraftScreen(props: { isProjectPickerReturnActive, isReturningToProjectPicker, navigation, + pickerDraftId, props.incomingShareId, requestedInitialProjectAvailable, ]); @@ -969,7 +973,7 @@ export function NewTaskDraftScreen(props: { + } draftMode={{ content: heroViewport, @@ -1010,7 +1014,7 @@ export function NewTaskDraftScreen(props: { onCancelQueuedRunEdit={() => {}} onRemoveQueuedEditAttachment={() => {}} projectWorkspaceRoot={selectedProject.workspaceRoot} - threadCwd={composerWorkspaceCwd} + threadCwd={flow.workspaceCwd} selectedThreadQueueCount={0} queuedMessages={[]} dispatchingMessageId={null} diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx index 6e2eaee5ec..568730a36b 100644 --- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx @@ -31,6 +31,7 @@ import { ProjectFavicon } from "../../components/ProjectFavicon"; import { useProjects, useServerConfigs } from "../../state/entities"; import { projectEnvironment } from "../../state/projects"; import { useAtomCommand } from "../../state/use-atom-command"; +import { retargetSavedNewTaskDraft } from "../../state/use-composer-drafts"; import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry"; import type { WorkspaceState } from "../../state/workspaceModel"; import { useWorkspaceState } from "../../state/workspace"; @@ -46,6 +47,8 @@ import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspace type NewTaskRouteParams = { readonly incomingShareId?: string | string[]; + /** An existing draft whose project is gone; the chosen project takes it over. */ + readonly draftId?: string | string[]; readonly prompt?: string | string[]; readonly repo?: string | string[]; readonly pr?: string | string[]; @@ -166,6 +169,9 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps found, + () => null, + ); + if (retargeted === null) { + Dialog.alert("Could not change project", "Saved drafts could not be loaded. Try again."); + return; + } + const draftId = retargeted ? routeDraftId : undefined; selectDetail({ name: "Thread", params: { draft: { environmentId: String(project.environmentId), projectId: String(project.id), + draftId, incomingShareId: incomingShare?.id, }, }, @@ -503,7 +526,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps } @@ -529,7 +552,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx index 671df8e217..d7a2cae3e1 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -87,6 +87,7 @@ function QuestionText(props: { readonly threadId: ThreadId; readonly workspaceRoot: string | null; readonly setDirection: TextDirection | undefined; + readonly preserveSoftBreaks?: boolean; }) { const styles = useMarkdownPreviewStyles(); const markdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); @@ -119,6 +120,7 @@ function QuestionText(props: { Platform.OS === "android" ? undefined : props.setDirection === "rtl" ? "right" : "left" } onLinkPress={openLink} + preserveSoftBreaks={props.preserveSoftBreaks} /> ); } @@ -235,6 +237,16 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { })); const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value })); + const stopButton = props.onStopThread ? ( + + ) : null; const bar = ( - {props.onStopThread ? ( - - ) : null} + {stopButton} ); const card = ( @@ -348,6 +351,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { type="monochrome" /> + {stopButton} {activeQuestion.options.map((option) => { @@ -385,36 +390,49 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { const description = option.description !== option.label ? option.description : undefined; return ( - selectOption(activeQuestion, optionValue)} - > - - - {option.label} - - {description ? ( + + selectOption(activeQuestion, optionValue)} + > + - {description} + {option.label} - ) : null} - - + {description ? ( + + {description} + + ) : null} + + + {option.preview ? ( + + + + ) : null} + ); })} diff --git a/apps/mobile/src/features/threads/QuestionAttachments.tsx b/apps/mobile/src/features/threads/QuestionAttachments.tsx index 6a4f111a89..5cfc1bf28c 100644 --- a/apps/mobile/src/features/threads/QuestionAttachments.tsx +++ b/apps/mobile/src/features/threads/QuestionAttachments.tsx @@ -106,18 +106,18 @@ export function QuestionAttachments(props: { props.question.id, ); changeQuestionAttachmentPreparation(key, 1); - void convertPastedImagesToAttachments({ - uris, - existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0, - }) - .then(async (images) => { + void convertPastedImagesToAttachments({ uris }) + .then(async (result) => { if ( scope.active && (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0 ) { - if (append(key, images) > 0) - Dialog.alert("Could not paste image", "Too many attachments."); - } else await releaseUnusedComposerAttachmentFiles(images); + const problems = [ + ...(result.error ? [result.error] : []), + ...(append(key, result.attachments) > 0 ? ["Too many attachments."] : []), + ]; + if (problems.length) Dialog.alert("Could not paste image", problems.join("\n\n")); + } else await releaseUnusedComposerAttachmentFiles(result.attachments); }) .catch((error) => Dialog.alert( diff --git a/apps/mobile/src/features/threads/SubagentRow.tsx b/apps/mobile/src/features/threads/SubagentRow.tsx index 7c71ac2680..77097c565a 100644 --- a/apps/mobile/src/features/threads/SubagentRow.tsx +++ b/apps/mobile/src/features/threads/SubagentRow.tsx @@ -4,7 +4,10 @@ import { resolveProviderInstanceDisplayName, shouldShowInstanceBadge, } from "@t3tools/client-runtime/state/provider-instance-display"; -import { resolveSubagentMetadata } from "@t3tools/client-runtime/state/subagent-display"; +import { + resolveSubagentMetadata, + subagentCardDetail, +} from "@t3tools/client-runtime/state/subagent-display"; import { formatSubagentEffort } from "@t3tools/client-runtime/state/thread-execution"; import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts"; import type { ReactNode } from "react"; @@ -15,7 +18,6 @@ import { SymbolView } from "../../components/ui/AppSymbol"; import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIcon"; import { cn } from "../../lib/cn"; import { useEnvironmentServerConfig, useProject, useThreadShell } from "../../state/entities"; -import { subagentCardDetail } from "./subagent-card-presentation"; import { SUBAGENT_TONE_TEXT_CLASS, SubagentStatusDot } from "./SubagentStatusDot"; import { resolveSubagentRowPresentation } from "./threadAgentsPresentation"; @@ -126,6 +128,9 @@ function SubagentMetadata(props: { (candidate) => candidate.instanceId === subagent.providerInstanceId, ); const showBadge = provider !== undefined && shouldShowInstanceBadge(provider, providers); + // A remote task's own driver is only a "remote" label. + const driver = + provider?.driver ?? (subagent.remoteChild === undefined ? subagent.driver : undefined); const parent = useThreadShell(scopeThreadRef(environmentId, subagent.threadId))?.source; const child = useThreadShell( subagent.childThreadId === null ? null : scopeThreadRef(environmentId, subagent.childThreadId), @@ -156,12 +161,10 @@ function SubagentMetadata(props: { accentColor={provider.accentColor} showBadge /> + ) : driver === undefined ? ( + ) : ( - + )} {provider ? `${resolveProviderInstanceDisplayName(provider)} · ` : ""} diff --git a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx index f4ec86584b..f6223aaf36 100644 --- a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx @@ -1,3 +1,4 @@ +import { LegendList, type LegendListRef } from "@legendapp/list/react-native"; import { SheetHeader } from "../../components/ui/SheetHeader"; import { appAtomRegistry } from "../../state/atom-registry"; import { useAtomValue } from "@effect/atom-react"; @@ -5,7 +6,7 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { sortInboxThreadsByReturn } from "@t3tools/client-runtime/state/thread-inbox"; import { type ReactNode, useEffect, useMemo, useRef, useState } from "react"; -import { Animated, FlatList, Modal, Pressable, useWindowDimensions, View } from "react-native"; +import { Animated, Modal, Pressable, useWindowDimensions, View } from "react-native"; import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler"; import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated"; import { threadDragGapOffset } from "./threadDragGap"; @@ -17,7 +18,7 @@ import { scopedThreadKey } from "../../lib/scopedEntities"; import { deriveThreadArrangementSizing } from "../../lib/layout"; import { environmentServerConfigsAtom } from "../../state/server"; import { threadListEnvironmentsAtom } from "../../state/presentation"; -import { environmentThreadShells } from "../../state/threads"; +import { steadyNavigationThreadShellsAtom, steadyShellsHoldingAtom } from "../../state/threads"; import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort"; import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf"; import { @@ -176,13 +177,14 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { baseFontSize: appearance.baseFontSize, fontScale, }); - const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom); + const threads = useAtomValue(steadyNavigationThreadShellsAtom); const configs = useAtomValue(environmentServerConfigsAtom); const listEnvironments = useAtomValue(threadListEnvironmentsAtom); const { workingShelfEnabled } = useThreadListV2ShelfPreferences(); const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom); const pendingOrder = useAtomValue(pendingThreadOrderAtom); const dropBusy = useAtomValue(threadDropBusyAtom); + const holdingRows = useAtomValue(steadyShellsHoldingAtom); const { moveThread } = useThreadListActions(); const now = useThreadListNow(threads); const [expanded, setExpanded] = useState({ snoozed: false, settled: false }); @@ -255,7 +257,7 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { } return result; }, [sections, expanded, visibleSettled, settledCount, rowHeight, headerHeight]); - const list = useRef>(null); + const list = useRef(null); const geometry = useRef({ height: 0, offset: 0 }); const drag = useRef(null); const frame = useRef(null); @@ -413,21 +415,28 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { className="flex-1" style={{ overflow: "hidden" }} > - row.key} + extraData={{ + visiblePreview, + insertionOffset, + dropBusy, + pendingOrder, + listEnvironments, + planners, + configs, + }} + // Rows hold their drag gesture, so each keeps its own view. + recycleItems={false} scrollEnabled={visiblePreview === null} - removeClippedSubviews={false} onScroll={(event) => { geometry.current.offset = event.nativeEvent.contentOffset.y; }} scrollEventThrottle={16} - getItemLayout={(_, index) => ({ - length: rows[index]!.height, - offset: rows[index]!.offset, - index, - })} + getFixedItemSize={(row) => row.height} renderItem={({ item }) => { const thread = item.thread; const planner = @@ -486,6 +495,7 @@ function ThreadArrangementSheet(props: { onClose: () => void }) { disabled={ dropBusy || pendingOrder !== null || + holdingRows || (!listEnvironments.pinReorderEnvironmentIds.has( thread.environmentId, ) && diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 779df8e7ec..782b495b4e 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -14,6 +14,7 @@ import { useAtomValue } from "@effect/atom-react"; import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments"; import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste"; import { + AuthOrchestrationOperateScope, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, type ChatAttachment, @@ -66,17 +67,16 @@ import { themeColorWithAlpha } from "../../lib/mobileTheme"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { getComposerDraftSnapshot, - composerDraftsAtom, setComposerDraftText, composerContextImportsAtom, countComposerDraftAttachmentsAfterSelection, useComposerDraft, } from "../../state/use-composer-drafts"; -import { appAtomRegistry } from "../../state/atom-registry"; import type { ComposerDocumentAttachment } from "../../lib/composerContext"; import { useProject, useVisibleThreadShells } from "../../state/entities"; import { useMentionableEnvironments } from "../../state/environments"; import { useLinkedEnvironments } from "../../state/peerLinks"; +import { useEnvironmentScopeDenied } from "../../state/session"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { AppText as Text } from "../../components/ui/AppText"; @@ -89,19 +89,31 @@ import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/ import { GlassSurface } from "../../components/ui/GlassSurface"; import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor"; import { fileRoutePathSegments } from "../files/filePath"; -import { ComposerActionButton, ComposerToolbarRow } from "../../components/ComposerToolbar"; +import { + ComposerActionButton, + ComposerInlineControl, + ComposerToolbarRow, +} from "../../components/ComposerToolbar"; +import { formatTokens } from "@t3tools/shared/usageFormat"; import { ComposerModelControl } from "../../components/ComposerModelControl"; import { composerStripAttachments, type DraftComposerFileAttachment, } from "../../lib/composerImages"; -import { buildModelOptions, isModelSelectionUnavailable } from "../../lib/modelOptions"; -import { useScaledTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole"; +import { + buildModelOptions, + isModelSelectionUnavailable, + serverConfigForCwd, +} from "../../lib/modelOptions"; +import { useComposerTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole"; import type { RemoteClientConnectionState } from "../../lib/connection"; import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; import { Menu } from "../../components/ui/Menu"; -import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch"; +import { + composerRunsDraftLocally, + type ActiveTurnComposerAction, +} from "@t3tools/client-runtime/state/composer-dispatch"; import type { FollowUpBehavior } from "../../lib/followUpBehavior"; import { resolveComposerSendPresentation, @@ -149,7 +161,11 @@ function collapsedEditorInset(text: ScaledTextRole): number { return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift)); } -function useCompactComposerEditor(text: ScaledTextRole, value: string) { +const EXPANDED_EDITOR_INSET = 14; +// Room under the expanded editor for the toolbar row. +const EXPANDED_EDITOR_BOTTOM = 52; + +function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) { const [contentSize, setContentSize] = useState({ width: 0, height: 0 }); const [compactWidth, setCompactWidth] = useState(0); const contentHeight = contentSize.height; @@ -170,25 +186,55 @@ function useCompactComposerEditor(text: ScaledTextRole, value: string) { (contentHeight > text.lineHeight * 1.5 || (compactWidth > 0 && contentSize.width > compactWidth)); const compactRowHeight = Math.max(44, minimum); + const compactBottom = (compactRowHeight - minimum) / 2; const isRTL = I18nManager.isRTL; - const editorStyle = useAnimatedStyle(() => ({ - position: "absolute", - overflow: "hidden", - height, - ...(isExpanded - ? { left: 14, right: 14 } - : compactEditorInsets({ - slotX: editorX.value, - slotWidth: editorWidth.value, - rowWidth: rowWidth.value, - isRTL, - })), - // The full-width editor must move above the controls in the same frame it widens. - bottom: isExpanded ? 52 : (compactRowHeight - minimum) / 2, + const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM; + const expansion = useDerivedValue(() => { + const target = isExpanded ? 1 : 0; + return animate + ? withTiming(target, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : target; + }); + const editorStyle = useAnimatedStyle(() => { + const compactInsets = compactEditorInsets({ + slotX: editorX.value, + slotWidth: editorWidth.value, + rowWidth: rowWidth.value, + isRTL, + }); + const progress = expansion.value; + // Hanging from the row top lets the text ride the growing edge and ignore the stale + // height measured while it still wrapped in the compact slot. Layout props only: + // Reanimated applies transforms frames ahead of layout, which tore the text from its frame. + return { + position: "absolute", + overflow: "hidden", + // The compact slot is unknown until its first layout, so the editor would draw over the + button. + opacity: isExpanded || editorWidth.value > 0 ? 1 : 0, + height, + top: compactBottom * (1 - progress), + left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress, + // Snapping the far edge keeps the line from rewrapping while the near edge moves. + right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right, + }; + }); + const containerStyle = useAnimatedStyle(() => ({ + height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value, })); return { isExpanded, - containerStyle: { height: isExpanded ? height + 52 : compactRowHeight }, + containerStyle, + // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted. + // An entering animation hides it from its first frame, which a shared-value opacity cannot. + toolbarControlsEntering: + animate && isExpanded + ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2) + .duration(COMPOSER_TRANSITION_DURATION_MS / 2) + .reduceMotion(ReduceMotion.System) + : undefined, editorStyle, onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => { rowWidth.set(event.nativeEvent.layout.width); @@ -227,12 +273,20 @@ export interface ThreadComposerProps { readonly selectedThread: EnvironmentThreadShell; readonly reportedModelSelection?: ModelSelection | null; readonly hasCompactableConversation: boolean; + /** Set while the next send compacts the thread first. */ + readonly compactBeforeSend?: { + readonly tokens: number; + readonly keepFullHistory: boolean; + readonly toggleKeepFullHistory: () => void; + } | null; /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */ readonly onFreshSession?: () => void; readonly offersSideChat?: boolean; readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; readonly activeThreadBusy: boolean; + /** Sending declines a pending approval and redirects the agent, so `/side` is plain text. */ + readonly redirectsApproval: boolean; readonly canStopThread: boolean; readonly environmentId: EnvironmentId; readonly projectCwd: string | null; @@ -431,7 +485,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const composerPanel = materialTheme["--color-composer-panel"]; const navigation = useNavigation(); const foregroundColor = useUniwindTheme()["--color-foreground"]; - const bodyText = useScaledTextRole("body"); + const bodyText = useComposerTextRole(); const fallbackInputRef = useRef(null); const inputRef = props.editorRef ?? fallbackInputRef; const [isFocused, setIsFocused] = useState(false); @@ -473,7 +527,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [previewVideo, setPreviewVideo] = useState(null); const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerDraftKey = props.draftKey ?? composerOwnerKey; - const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey); + const { + text: draftMessage, + attachments: draftAttachments, + context: draftContext, + } = useComposerDraft(composerDraftKey); const queuedEdit = props.queuedEdit ?? null; const hasContent = draftMessage.trim().length > 0 || @@ -492,6 +550,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps setResumingQueue(false); }; + const operateDenied = useEnvironmentScopeDenied( + props.environmentId, + AuthOrchestrationOperateScope, + ); const uploadStates = useAtomValue(composerAttachmentUploadsAtom); const attachmentsUploading = props.connectionState === "connected" && @@ -501,15 +563,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps serverConfig: props.serverConfig, states: uploadStates, }); - const sendPresentation = resolveComposerSendPresentation({ - editingQueuedMessage: queuedEdit !== null, - running: props.activeThreadBusy, - canSteer: props.canSteerActiveTurn, - followUpBehavior: props.followUpBehavior, - deliveryDeferred: - props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading, - }); - const sendLabel = sendPresentation.label; const currentModelSelection = props.selectedThread.modelSelection; const modelUnavailable = props.connectionState === "connected" && @@ -569,6 +622,25 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ) ?? null ); }, [currentModelSelection.instanceId, props.serverConfig, usageReportNow]); + const draftRunsLocally = composerRunsDraftLocally({ + text: draftMessage, + holdsOnlyText: draftAttachments.length === 0, + // A redirect's text answers its approval, so `/side` there is that text. + sideChat: !props.redirectsApproval, + usageLimits: usageLimitsOffered, + codexFeedback: selectedProviderStatus?.driver === "codex", + freshSession: props.onFreshSession !== undefined && draftContext === undefined, + }); + const sendPresentation = resolveComposerSendPresentation({ + editingQueuedMessage: queuedEdit !== null, + running: props.activeThreadBusy && !draftRunsLocally, + canSteer: props.canSteerActiveTurn, + followUpBehavior: props.followUpBehavior, + deliveryDeferred: + !draftRunsLocally && + (props.connectionState !== "connected" || props.queueCount > 0 || attachmentsUploading), + }); + const sendLabel = sendPresentation.label; const openUsageLimits = () => { const report = collectProviderUsageLimits( currentModelSelection.instanceId, @@ -617,6 +689,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps offersUsageLimits: usageLimitsOffered, onUsageLimits: usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined, + onOpenModelPicker: settingsSheetPresentation.open, modelOptions: mentionModelOptions, modelProviders: props.serverConfig?.providers, ...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }), @@ -626,7 +699,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ownerKey: composerDraftKey, label: props.selectedThread.title || "Untitled thread", readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text, - subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange), selection: composerMenu.selection, onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text), onChangeSelection: composerMenu.onSelectionChange, @@ -645,7 +717,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const surfacePaddingVertical = usesLargeControls ? 9 : 2; const [compactRowWidth, setCompactRowWidth] = useState(0); const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1; - const compactEditor = useCompactComposerEditor(bodyText, draftMessage); + // Animate only while typing; a thread switch or restored draft lands in place. + const compactEditor = useCompactComposerEditor( + bodyText, + draftMessage, + Platform.OS === "ios" && isFocused, + ); const showsCompactDictation = isVoiceInputPresented; const isToolbarVisible = isVoiceInputPresented; const hasEditingAttachments = @@ -757,7 +834,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ? undefined : currentModelSelection.instanceId; const modelOptions = buildModelOptions( - props.serverConfig, + serverConfigForCwd(props.serverConfig, props.projectCwd), currentModelSelection, lockedProviderInstanceId, props.selectedThread.projectId, @@ -886,6 +963,32 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ); + const compactBeforeSend = + props.compactBeforeSend && !showResumeAction && queuedEdit === null + ? props.compactBeforeSend + : null; + const compactTokens = compactBeforeSend ? formatTokens(compactBeforeSend.tokens) : null; + const compactControl = + compactBeforeSend && compactTokens !== null ? ( + + ) : null; + return ( props.onHeightChange?.(event.nativeEvent.layout.height)} @@ -1209,7 +1312,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined } > - {modelControl} + + {compactControl} + {modelControl} + - {props.connectionState === "connected" && !props.canOperateThread ? ( + {props.connectionState === "connected" && operateDenied ? ( This connection cannot control this task. You can still edit your draft. diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 069b1d6fd2..1368f02681 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -34,13 +34,16 @@ import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-e import { childThreadInputsTitle, type CodexFeedbackSubmission, - type EnvironmentThreadStatus, } from "@t3tools/client-runtime/state/threads"; import { useKeyboardScrollToEnd } from "@legendapp/list/keyboard"; import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills"; import type { LegendListRef } from "@legendapp/list/react-native"; import { NativeLayoutObserver } from "../../native/NativeLayoutObserver"; -import { deriveBottomControlInsets, type NativeLayoutMetrics } from "../../lib/reserved-regions"; +import { + deriveBottomControlInsets, + deriveContentSideInsets, + type NativeLayoutMetrics, +} from "../../lib/reserved-regions"; import type { EnvironmentId, MessageId, @@ -121,6 +124,7 @@ import { useBarOverlap } from "../../components/ui/useBarInset"; import { useWorkspaceContentWidth, WorkspaceSettledContentWidthContext, + useWorkspaceSettledContentWidth, } from "../layout/workspace-content-width"; import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context"; import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns"; @@ -142,6 +146,7 @@ import { type LayoutVariant, } from "../../lib/layout"; import { editPendingThreadMessage } from "../../state/edit-pending-thread-message"; +import { environmentCatalog } from "../../connection/catalog"; import { deviceEnvironment } from "../../state/device"; import { useEnvironmentQuery } from "../../state/query"; import { threadDevicePreviews } from "../devices/threadDevicePreviews"; @@ -199,6 +204,7 @@ import { COMPOSER_COLLAPSED_CHROME, THREAD_COMPOSER_BOTTOM_GUTTER, ThreadComposer, + type ThreadComposerProps, } from "./ThreadComposer"; import { ComposerPopoverHost } from "./ComposerPopoverHost"; import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed"; @@ -248,6 +254,8 @@ export interface ThreadDetailScreenProps { readonly providerSubagentStatus?: ProviderSubagentStatus | null; readonly extensionStatuses?: NonNullable; readonly isCompacting: boolean; + /** Set while the next send compacts the thread first. */ + readonly compactBeforeSend?: ThreadComposerProps["compactBeforeSend"]; readonly creationState: | { readonly kind: "preparing"; @@ -264,7 +272,6 @@ export interface ThreadDetailScreenProps { readonly activePendingUserInputAnswers: Record> | null; readonly respondingUserInputId: RuntimeRequestId | null; readonly connectionStateLabel: EnvironmentConnectionPhase; - readonly threadSyncStatus?: EnvironmentThreadStatus; readonly historyControls?: ThreadFeedHistoryControls; readonly activeThreadBusy: boolean; readonly canStopThread: boolean; @@ -326,12 +333,14 @@ export interface ThreadDetailScreenProps { // iOS questions overlay the controls; Android questions stack with child approvals. const ComposerPanels = Platform.OS === "android" ? Animated.ScrollView : Animated.View; -/** Hands the feed the screen width measured for a native column; elsewhere keeps the inherited one. */ +/** + * Hands the feed the screen width measured for a native column; elsewhere keeps the inherited one. + * Always the same element, so the feed below is not remounted when the width arrives. + */ function ColumnWidth(props: { readonly width: number | null; readonly children: React.ReactNode }) { - return props.width === null ? ( - props.children - ) : ( - + const inherited = useWorkspaceSettledContentWidth(); + return ( + {props.children} ); @@ -368,6 +377,7 @@ const wakeAwareVisitShell = Atom.family((key: string) => { const threadVisitTracker = createThreadVisitTracker({ threadShellAtom: (ref) => wakeAwareVisitShell(threadKey(ref)), + sessionGenerationAtom: environmentCatalog.sessionGenerationAtom, visit: threadEnvironment.visit, }); @@ -563,20 +573,6 @@ function ThreadDetailBody( ); const composerKeyboardOffset = composerBottomInset; const contentPresentationKind = props.contentPresentation.kind; - const realThreadSyncLabel = (() => { - switch (props.threadSyncStatus) { - case "empty": - case "cached": - case "synchronizing": - if (contentPresentationKind === "ready") { - return "Syncing messages..."; - } - return contentPresentationKind === "loading" ? "Loading messages..." : null; - default: - return null; - } - })(); - const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel); const connectionRetrying = props.connectionStateLabel === "connecting" || props.connectionStateLabel === "reconnecting"; const retryError = connectionRetrying ? props.connectionError : null; @@ -798,18 +794,13 @@ function ThreadDetailBody( return null; } if (props.creationState?.kind === "preparing") { - if (props.worktreeSetup) return null; - return { - kind: "preparing", - label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…", - }; + // The feed shows worktree setup in place, so only a plain start needs the pill. + if (props.worktreeSetup || props.creationState.preparingWorktree) return null; + return { kind: "preparing", label: "Starting…" }; } if (props.creationState?.kind === "failed") { return null; } - if (threadSyncLabel !== null) { - return { kind: "syncing", label: threadSyncLabel }; - } const childInput = childThreadInputs[0]; if (childInput && contentPresentationKind === "ready") { return { @@ -826,7 +817,11 @@ function ThreadDetailBody( return { kind: "compacting" }; } if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") { - return { kind: "working", startedAt: props.activeWorkStartedAt }; + return { + kind: "working", + environmentId: props.environmentId, + startedAt: props.activeWorkStartedAt, + }; } if (pendingBackgroundWork !== null && contentPresentationKind === "ready") { return { @@ -894,6 +889,11 @@ function ThreadDetailBody( return null; })(); const showWorkingControl = floatingStatus !== null; + // A pending message holds the pill's row for its Starting/Working pill. Worktree setup reports + // progress in the feed instead, so holding the row there only leaves a gap that later closes. + const worktreeSetupInFeed = + props.worktreeSetup?.snapshot.phase === "running" || + (props.creationState?.kind === "preparing" && props.creationState.preparingWorktree); const showFloatingStatus = showWorkingControl || queuedCount > 0 || @@ -901,10 +901,11 @@ function ThreadDetailBody( devicePreviews.length > 0 || browserTabs.tabs.length > 0 || props.connectionStateLabel !== "connected" || - props.queuedMessages.length > 0 || - props.selectedThreadFeed.some( - (entry) => "acknowledged" in entry && entry.acknowledged === true, - ); + (!worktreeSetupInFeed && + (props.queuedMessages.length > 0 || + props.selectedThreadFeed.some( + (entry) => "acknowledged" in entry && entry.acknowledged === true, + ))); const selectedThreadFeed = props.selectedThreadFeed; // A palette message result opens the thread at that message: earlier // history loads until the message is in the feed, which then scrolls to it. @@ -1072,11 +1073,16 @@ function ThreadDetailBody( windowHeight: screenAreaHeight, keyboardHeight: keyboardStickyEnabled ? -keyboardTranslation.value : 0, navigationHeaderHeight, - composerOverlapHeight: composerBottomInset, + // An in-flow question shares the room above it with the floating control. + composerOverlapHeight: + composerBottomInset + + (questionInFlow && showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0), }), ); + // A question pads itself clear of the bottom inset, below the card's own height limit. + const questionBottomInset = activeUserInputRequestId !== null ? composerBottomInset : 0; const composerPanelsHeightStyle = useAnimatedStyle(() => ({ - maxHeight: pendingUserInputMaxHeight.value, + maxHeight: pendingUserInputMaxHeight.value + questionBottomInset, flexGrow: 0, })); // Questions overlay the composer on iOS; an approval sits above it, so it gives up its height. @@ -1491,6 +1497,11 @@ function ThreadDetailBody( pendingHandoff={props.pendingHandoff} worktreeSetup={props.worktreeSetup} setupWorkingStartedAt={props.setupWorkingStartedAt} + preparingWorktree={ + props.creationState?.kind === "preparing" && + props.creationState.preparingWorktree && + !props.worktreeSetup + } queuedMessages={props.queuedMessages} dispatchingMessageId={props.dispatchingMessageId} // A native subagent has no composer to edit a pending message in; @@ -1522,7 +1533,7 @@ function ThreadDetailBody( } contentMaxWidth={contentMaxWidth} historyControls={props.historyControls} - contentSideInsets={nativeMetrics?.safeArea} + contentSideInsets={deriveContentSideInsets(nativeMetrics)} layoutVariant={layoutVariant} usesAutomaticContentInsets={props.usesAutomaticContentInsets} onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange} @@ -1865,6 +1876,7 @@ function ThreadDetailBody( draftControls={props.draftMode?.controls(draftViewportHeight)} connectionState={props.connectionStateLabel} selectedThread={props.selectedThread} + compactBeforeSend={props.compactBeforeSend ?? null} hasCompactableConversation={ hasCompactableConversation && !props.isCompacting } @@ -1884,6 +1896,10 @@ function ThreadDetailBody( serverConfig={props.serverConfig} queueCount={props.selectedThreadQueueCount} activeThreadBusy={props.activeThreadBusy} + redirectsApproval={ + props.activePendingApprovals.length > 0 && + props.activePendingUserInput === null + } canStopThread={props.canStopThread} environmentId={props.environmentId} projectCwd={props.threadCwd ?? props.projectWorkspaceRoot} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 238cc00ba0..7fc936d01f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -5,7 +5,11 @@ import { Button } from "../../components/ui/Button"; import * as Dialog from "../../components/ui/Dialog"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width"; -import { ThreadMarkdownVideo, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo"; +import { + ThreadMarkdownVideo, + ThreadMediaRetainContext, + ThreadMediaVisibleContext, +} from "./ThreadMarkdownVideo"; import { useMarkdownImageSource } from "../../native/useMarkdownImageSource"; import { enrichedContextLinkCustomization, @@ -13,10 +17,10 @@ import { withChipIcon, } from "../../native/useEnrichedLinkVariants"; import { - enrichedSkillDisplayName, enrichedSkillInstructionsPath, enrichedSkillReference, } from "../../lib/enrichedLinkPresentation"; +import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; import { ThreadContextDivider } from "./thread-context-divider"; import { ThreadHandoffDivider, @@ -27,6 +31,7 @@ import { LinkRequestCard } from "./LinkRequestCard"; import { SecretRequestCard } from "./SecretRequestCard"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { + WorktreePreparingHeader, WorktreeWorkingHeader, WorktreeSetupCard, type WorktreeSetupCardProps, @@ -80,6 +85,7 @@ import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { executeAtomQuery, + isAtomCommandInterrupted, settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; @@ -96,7 +102,8 @@ import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3too import { imageMimeType } from "@t3tools/shared/image"; import { videoMimeType } from "@t3tools/shared/video"; import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; -import { useFocusEffect, useNavigation } from "@react-navigation/native"; +import { textDirection } from "@t3tools/shared/textDirection"; +import { useFocusEffect, useIsFocused, useNavigation } from "@react-navigation/native"; import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns"; import { useDeviceType } from "../../native/native-layout-metrics"; import { isDuoDevice } from "../../lib/device-type"; @@ -112,8 +119,10 @@ import { useSyncExternalStore, useId, type ComponentPropsWithRef, + type Dispatch, type ReactNode, type RefObject, + type SetStateAction, } from "react"; import { Image, @@ -132,9 +141,18 @@ import { useResolveClassNames } from "uniwind"; import { useReduceMotionEnabled } from "../../lib/appState"; import { useFilePreviewGallery, FilePreviewGallery } from "../../components/ui/FilePreviewGallery"; import { assetImageSource } from "../../lib/assetImageSource"; +import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery"; import { composerImageGallery } from "../../lib/composerImageGallery"; -import { isFileBackedComposerAttachment } from "../../lib/composerImages"; +import { + isFileBackedComposerAttachment, + type FileBackedComposerAttachment, +} from "../../lib/composerImages"; import { useLocalAttachmentPreview } from "../../lib/localAttachmentPreview"; +import { + rememberSentImage, + sentImageHandoff, + type SentImageHandoff, +} from "../../lib/sentImageHandoff"; import { messageImageGallery } from "./messageImageGallery"; import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize"; import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; @@ -150,6 +168,7 @@ import { scopedThreadKey } from "../../lib/scopedEntities"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { downloadAndShareAttachment } from "../../lib/attachmentDownload"; import { splitMarkdownDetails } from "../../lib/markdownDetails"; +import { markdownReferenceDefinitions, withReferenceDefinitions } from "../../lib/markdownDocument"; import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks"; import { SelectableMarkdownText, @@ -164,7 +183,11 @@ import { import { AppText as Text } from "../../components/ui/AppText"; import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal"; import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia"; -import { attachmentVideoPreviewSource } from "../../lib/videoPreviewSource"; +import { + attachmentVideoPreviewSource, + mediaVideoThumbnailKey, + type MediaVideoPreviewSource, +} from "../../lib/videoPreviewSource"; import { CopyTextButton } from "./CopyTextButton"; import { getReviewSectionIdForCheckpoint } from "../review/reviewModel"; import { setReviewSelectedSectionId } from "../review/reviewState"; @@ -229,9 +252,12 @@ import { ThreadMcpApp } from "./McpAppWebView"; import { assetEnvironment, useAssetUrl, useRefreshAssetUrl } from "../../state/assets"; import { useAtomQueryRunner } from "../../state/use-atom-query-runner"; import { readEnvironmentScope, usePreparedConnection } from "../../state/session"; -import { projectEnvironment } from "../../state/projects"; +import { environmentProjects, projectEnvironment } from "../../state/projects"; import { + agentWorkingDirectories, + findAgentDirectoryMatch, needsWorkspaceBasenameLookup, + pickProjectLinkMatch, pickWorkspaceLinkMatch, WORKSPACE_BASENAME_LOOKUP_LIMIT, workspaceLinkLookupQuery, @@ -242,6 +268,7 @@ import { useQuietThreadShell, useThreadChipIcons, } from "../../state/entities"; +import { useEnvironmentPresentation } from "../../state/presentation"; import { useThreadSelection } from "../../state/use-thread-selection"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; @@ -249,12 +276,17 @@ import { useModelMentions } from "../../state/model-mentions"; import { composerDocumentAttachmentRecord } from "../../lib/composerContext"; import * as Option from "effect/Option"; import { appAtomRegistry } from "../../state/atom-registry"; -import { environmentThreadShells, threadEnvironment } from "../../state/threads"; +import { + environmentThreadDetails, + environmentThreadShells, + threadEnvironment, +} from "../../state/threads"; import { ThreadWorkflowOpening, useWorkflowOpening } from "./thread-workflow-opening"; import { useAtomCommand } from "../../state/use-atom-command"; import { useV2ItemSupport } from "../../state/v2-item-support"; import { fileRoutePathSegments, + isAbsolutePath, resolveFileLinkPath, resolveWorkspaceFilePath, resolveWorkspaceRelativeFilePath, @@ -270,9 +302,10 @@ import { ThreadMarkdownImageUnavailable, ThreadMarkdownImageView, } from "./ThreadMarkdownImage"; +import { ZoomableImagePressable } from "./ZoomableImagePressable"; import { openSettings } from "../settings/settings-navigation"; import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; -import { formatMessageTimestamp } from "./messageTimestamp"; +import { useMessageTimeFormatter } from "./useMessageTimeFormatter"; const WIDE_MARKDOWN_BLOCK_OPTIONS = { // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width. @@ -305,6 +338,7 @@ export interface ThreadFeedProps { readonly toolCallVisibility?: ToolCallVisibility; readonly worktreeSetup?: WorktreeSetupCardProps | null; readonly setupWorkingStartedAt?: string | null; + readonly preparingWorktree?: boolean; readonly queuedMessages: ReadonlyArray; readonly dispatchingMessageId: MessageId | null; readonly onEditPendingMessage: ((message: QueuedThreadMessage) => void) | null; @@ -386,7 +420,14 @@ function AssistantForkButton(props: { }, }) .then(async (result) => { - if (result._tag !== "Success") return; + if (isAtomCommandInterrupted(result)) return; + if (result._tag !== "Success") { + Dialog.alert( + "Could not confirm fork", + "Reconnect and check the thread list before trying again.", + ); + return; + } const targetThreadReady = await waitForThreadShell( scopeThreadRef(props.environmentId, targetThreadId), ); @@ -430,11 +471,19 @@ function MessageImage(props: { readonly className: string; readonly maxWidth?: number; readonly height?: number; - readonly onLoad?: () => void; + readonly accessibilityLabel: string; + readonly handoff?: SentImageHandoff; + readonly onPress: () => void; + readonly onLoad?: (size: { readonly width: number; readonly height: number }) => void; readonly onError?: () => void; }) { const imageStyle = useResolveClassNames(props.className); - const [size, setSize] = useState<{ width: number; height: number } | null>(null); + const [loadedSize, setSize] = useState<{ width: number; height: number } | null>(null); + // Until it loads, assume a handed-off image is a photo larger than the bubble's caps. + const size = + loadedSize ?? + (props.handoff ? { width: props.handoff.aspectRatio * 4096, height: 4096 } : null); + const contentFit = props.maxWidth === undefined ? "cover" : "contain"; const displaySize = props.maxWidth !== undefined && size !== null ? resolveMarkdownImageDisplaySize({ @@ -444,11 +493,13 @@ function MessageImage(props: { }) : null; return ( - { - if (props.maxWidth !== undefined) setSize(event.source); - props.onLoad?.(); - }} - onError={props.onError} - /> + > + { + if (props.maxWidth !== undefined) setSize(event.source); + props.onLoad?.(event.source); + }} + onError={props.onError} + /> + ); } @@ -476,21 +535,34 @@ function MessageAttachmentImage(props: { readonly className: string; readonly maxWidth?: number; readonly height?: number; + readonly handoff?: SentImageHandoff; + readonly onImageLoad?: (image: SentImageHandoff) => void; readonly onPressPreview: (source: FilePreviewSource) => void; }) { const withGallery = useFilePreviewGallery(); - const sourceIdentifier = useId(); const resource = { _tag: "attachment" as const, attachmentId: props.attachmentId, fileName: props.name, mimeType: props.mimeType, }; + const sourceIdentifier = filePreviewSourceIdentifier({ + kind: "image", + environmentId: props.environmentId, + resource, + }); const uri = useAssetUrl(props.environmentId, resource); const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource); const retriedImage = useRef(false); + const { handoff } = props; + const source = + uri !== null + ? assetImageSource(props.environmentId, resource, uri) + : handoff !== undefined + ? { uri: handoff.uri } + : null; - if (uri === null) { + if (source === null) { return ( - props.onPressPreview( withGallery({ @@ -529,22 +606,17 @@ function MessageAttachmentImage(props: { }), ) } - > - { - retriedImage.current = false; - }} - onError={() => { - if (retriedImage.current) return; - retriedImage.current = true; - void refreshAssetUrl(); - }} - /> - + onLoad={(size) => { + retriedImage.current = false; + if (handoff) + props.onImageLoad?.({ uri: handoff.uri, aspectRatio: size.width / size.height }); + }} + onError={() => { + if (retriedImage.current) return; + retriedImage.current = true; + void refreshAssetUrl(); + }} + /> ); } @@ -569,7 +641,6 @@ function MessageAttachmentFile(props: { readonly attachment: ChatFileAttachment; readonly onPressPreview: (source: FilePreviewSource) => void; readonly onPlaybackStart: () => void; - readonly standaloneMedia?: boolean; readonly standaloneFile?: boolean; readonly available?: boolean; }) { @@ -706,14 +777,10 @@ function MessageAttachmentFile(props: { if (videoType !== null) { return ( - + ); @@ -776,7 +843,10 @@ function MessageAttachmentFile(props: { ); } +const handoffProps = (handoff: SentImageHandoff | undefined) => (handoff ? { handoff } : {}); + function UserMessageMedia(props: { + readonly messageId: string; readonly attachments: ReadonlyArray; readonly pendingAttachments: QueuedThreadMessage["attachments"]; readonly environmentId: EnvironmentId; @@ -801,7 +871,6 @@ function UserMessageMedia(props: { ...props.pendingAttachments.map((attachment, index) => { const image = isImageAttachment(attachment); return { - id: attachment.id, image, content: image && attachment.uploadedAttachmentId ? ( @@ -811,30 +880,35 @@ function UserMessageMedia(props: { name={attachment.name} mimeType={attachment.mimeType} {...imageProps(index)} + {...handoffProps(sentImageHandoff(props.messageId, index, attachment.id))} + onImageLoad={(loaded) => rememberSentImage(props.messageId, index, loaded)} onPressPreview={props.onPressPreview} /> - ) : !image && attachment.uploadedAttachmentId ? ( - ) : ( - rememberSentImage(props.messageId, index, image)} onPressPreview={props.onPressPreview} - onPlaybackStart={props.onPlaybackStart} /> ), }; }), ...props.attachments.map((attachment, index) => ({ - id: attachment.id, image: isImageAttachment(attachment), content: isImageAttachment(attachment) ? ( ) : isFileAttachment(attachment) ? ( - ) : null, })), @@ -875,7 +951,8 @@ function UserMessageMedia(props: { media .filter((_, index) => index % 2 === 0) .map((item, index) => ( - + // oxlint-disable-next-line react/no-array-index-key -- delivery re-ids attachments; position is the stable identity + {item.content} {media[index * 2 + 1] ? ( {media[index * 2 + 1]!.content} @@ -887,9 +964,10 @@ function UserMessageMedia(props: { ) : ( - {media.map((item) => ( + {media.map((item, index) => ( @@ -904,39 +982,78 @@ function UserMessageMedia(props: { ); } -function PendingMessageMedia(props: { +function PendingMessageImage(props: { readonly attachment: QueuedThreadMessage["attachments"][number]; readonly className: string; readonly maxWidth?: number; readonly height?: number; + readonly handoff?: SentImageHandoff; + readonly onImageLoad?: (image: SentImageHandoff) => void; readonly onPressPreview: (source: FilePreviewSource) => void; - readonly onPlaybackStart: () => void; }) { const withGallery = useFilePreviewGallery(); - const { attachment } = props; + const { attachment, handoff } = props; const fileBacked = isFileBackedComposerAttachment(attachment); const preview = useLocalAttachmentPreview(fileBacked ? attachment : null); - if (isImageAttachment(attachment)) { - const uri = fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri); - return ( - { - const source = composerImageGallery([attachment])[0]; - if (source) props.onPressPreview(withGallery(source)); - }} - > - - - ); + // The composer already showed this image; reuse its pixels and shape instead of a blank box. + const uri = + handoff?.uri ?? (fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri)); + return ( + { + if (uri) props.onImageLoad?.({ uri, aspectRatio: size.width / size.height }); + }} + onPress={() => { + const source = composerImageGallery([attachment])[0]; + if (source) props.onPressPreview(withGallery(source)); + }} + /> + ); +} + +/** + * A sent video from queueing through delivery. Every stage renders this one player under a + * thumbnail key of message and position, so swapping the local file for the server copy keeps + * the poster on screen instead of remounting to black and extracting a frame again. + */ +function UserMessageVideo(props: { + readonly environmentId: EnvironmentId; + readonly messageId: string; + readonly index: number; + readonly local: FileBackedComposerAttachment | null; + readonly uploaded: ChatFileAttachment | null; + readonly onPlaybackStart: () => void; +}) { + const sourceIdentifier = useId(); + const preview = useLocalAttachmentPreview(props.local); + const current: MediaVideoPreviewSource | null = + props.local !== null && preview.uri !== null + ? { + type: "media", + name: props.local.name, + mimeType: props.local.mimeType, + uri: preview.uri, + } + : props.uploaded !== null + ? attachmentVideoPreviewSource(props.environmentId, props.uploaded, sourceIdentifier) + : null; + // Each copy of a message reopens its local file; keep the last source while the next one loads. + const [shown, setShown] = useState(current); + if ( + current !== null && + (shown === null || mediaVideoThumbnailKey(current) !== mediaVideoThumbnailKey(shown)) + ) { + setShown(current); } - if (preview.uri === null) { + const source = current ?? shown; + if (source === null) { return ( {preview.error ? ( @@ -949,12 +1066,8 @@ function PendingMessageMedia(props: { } return ( @@ -1017,19 +1130,44 @@ function ThreadFeedScrollView(props: ComponentPropsWithRef>; + readonly children: ReactNode; +}) { + const { rowId, setRetainedRowId } = props; const [visible, setVisible] = useState(false); useViewabilityAmount( useCallback((token) => setVisible(token.sizeVisible > 0), []), ); - return {props.children}; + const retain = useCallback( + (retained: boolean) => + setRetainedRowId((current) => (retained ? rowId : current === rowId ? null : current)), + [rowId, setRetainedRowId], + ); + return ( + + {props.children} + + ); } +/** The reply a link sits in; a file it cites may be where the agent worked before writing it. */ +type MarkdownLinkReply = Pick; + interface MarkdownLinkHandlers { - readonly onLinkPress: (href: string) => void; + readonly onLinkPress: (href: string, reply?: MarkdownLinkReply) => void; readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined; - readonly onFileContextMenuAction: (href: string, actionId: string) => void; - readonly onImagePress?: (href: string) => void; + readonly onFileContextMenuAction: ( + href: string, + actionId: string, + reply?: MarkdownLinkReply, + ) => void; + /** `withGallery` pages the image through its message's images; the feed's viewer sits outside that scope. */ + readonly onImagePress?: ( + href: string, + withGallery?: (source: FilePreviewSource) => FilePreviewSource, + ) => void; readonly resolveImageSource?: MarkdownImageSourceResolver; readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null; readonly linkCustomization?: (href: string) => MarkdownLinkCustomization | undefined; @@ -1064,8 +1202,12 @@ function ArtifactTemplateCard(props: { readonly template: CodexArtifactTemplate; readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined; }) { + const direction = textDirection(props.template.displayName); return ( - + void) | undefined; readonly renderImage: MarkdownImageRenderer; readonly skills?: ReadonlyArray | undefined; @@ -1106,8 +1249,14 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { const models = useModelMentions(props.environmentId, props.markdown); const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown); + const withGallery = useFilePreviewGallery(); + const onImagePress = props.linkHandlers.onImagePress; const linkHandlers: MarkdownLinkHandlers = { ...props.linkHandlers, + ...(onImagePress ? { onImagePress: (href: string) => onImagePress(href, withGallery) } : {}), + onLinkPress: (href) => props.linkHandlers.onLinkPress(href, props.reply), + onFileContextMenuAction: (href, actionId) => + props.linkHandlers.onFileContextMenuAction(href, actionId, props.reply), linkCustomization: (href) => withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)), }; @@ -1128,6 +1277,8 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { // Folds split first, so an artifact card inside a fold stays inside it. function AssistantMarkdownBlocks(props: { readonly markdown: string; + /** The reply's reference definitions, passed down by the enclosing fold. */ + readonly definitions?: ReadonlyArray | undefined; readonly markdownStyles: MarkdownStyleSet; readonly linkHandlers: MarkdownLinkHandlers; readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined; @@ -1135,15 +1286,20 @@ function AssistantMarkdownBlocks(props: { readonly skills?: ReadonlyArray | undefined; readonly models: ReturnType; }) { - const blocks = useMemo( - () => - splitMarkdownDetails(props.markdown).map((block) => - block.kind === "details" - ? block - : { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) }, - ), - [props.markdown], - ); + const { blocks, definitions } = useMemo(() => { + const blocks = splitMarkdownDetails(props.markdown).map((block) => + block.kind === "details" + ? block + : { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) }, + ); + const [first] = blocks; + // A reply rendered as one document resolves its own references; skip the extra parse. + const whole = blocks.length === 1 && first?.kind === "markdown" && first.segments.length === 1; + return { + blocks, + definitions: props.definitions ?? (whole ? [] : markdownReferenceDefinitions(props.markdown)), + }; + }, [props.markdown, props.definitions]); return blocks.map((block) => { if (block.kind === "details") { return ( @@ -1152,7 +1308,7 @@ function AssistantMarkdownBlocks(props: { summary={block.summary} initiallyOpen={block.open} > - + ); } @@ -1171,7 +1327,9 @@ function AssistantMarkdownBlocks(props: { return ( void; @@ -1337,7 +1497,7 @@ function AgentMessageFoldHeader(props: { const senderShell = useQuietThreadShell( props.senderThreadId ? scopeThreadRef(props.environmentId, props.senderThreadId) : null, ); - const label = senderShell?.title.trim() || "Agent"; + const label = senderShell?.title.trim() || props.senderTitle?.trim() || "Agent"; return ( & { + readonly formatMessageTime: (input: string) => string; readonly copiedRowId: string | null; readonly expandedWorkRows: Record; readonly workRowSizing: ReturnType; @@ -1686,6 +1851,7 @@ function renderFeedEntry( rowSizing={props.workRowSizing} iconSubtleColor={iconSubtleColor} label={entry.label} + providerStartingLabel={entry.providerStartingLabel} /> ); } @@ -1702,6 +1868,24 @@ function renderFeedEntry( ); } + if (entry.type === "sent-message") { + return ( + + + + + + ); + } + if (entry.type === "viewed-images") { const thumbnailWidth = Math.floor((props.contentWidth - VIEWED_IMAGE_GAP) / 2); return ( @@ -1826,7 +2010,7 @@ function renderFeedEntry( const presentation = resolveUserMessagePresentation(message); const renderedText = renderAssistantCitationsAsText(presentation.text); const styles = isUser ? markdownStyles.user : markdownStyles.assistant; - const timestampLabel = formatMessageTimestamp(isUser ? message.createdAt : message.updatedAt); + const timestampLabel = props.formatMessageTime(isUser ? message.createdAt : message.updatedAt); const attachments = message.attachments ?? []; const hasReviewCommentContext = presentation.text.includes(" {foldRowId !== null ? ( ref.label) .split(/\r?\n/) @@ -2119,10 +2311,11 @@ function renderFeedEntry( ) : null} {bubbleBodyVisible ? ( - {foldRowId !== null && message.senderThreadId ? ( + {foldRowId !== null && senderRef ? ( ) : null} {intentBadge ? ( @@ -2216,6 +2409,7 @@ function renderFeedEntry( environmentId={props.environmentId} markdownStyles={styles} linkHandlers={props.markdownLinkHandlers} + reply={message.projectedItem} onUseArtifactTemplate={props.onUseArtifactTemplate} renderImage={props.renderMarkdownImage} skills={props.skills} @@ -2649,7 +2843,12 @@ const THREAD_FEED_MAINTAIN_SCROLL_AT_END = { on: { dataChange: true, itemLayout: true, layout: true }, } as const; +// A thread switch remounts the feed. Starting from the last split pane's size lays rows out once, +// instead of at width 0 and again when the new feed's own layout reports the same width. +let lastSplitViewport: { windowWidth: number; width: number; height: number } | null = null; + export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { + const formatMessageTime = useMessageTimeFormatter(); const { listRef, onIsAtEndChange, onHeaderMaterialVisibilityChange } = props; const workflowOpening = useWorkflowOpening(props.detailRef); const deviceType = useDeviceType(); @@ -2657,6 +2856,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const openPullRequest = useOpenPullRequest(); const navigation = useNavigation(); const openLinkedThread = useOpenLinkedThread(); + // Recycling a row disposes its native audio player, so a started clip's row stays rendered. + const [retainedMediaRowId, setRetainedMediaRowId] = useState(null); + const focused = useIsFocused(); + if (!focused && retainedMediaRowId !== null) setRetainedMediaRowId(null); const onOpenTurnDiff = useCallback( (checkpoint: ThreadCheckpointSummary) => { setReviewSelectedSectionId( @@ -2681,10 +2884,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }); const settledPaneWidth = useWorkspaceSettledContentWidth(); const splitLayout = (props.layoutVariant ?? "compact") !== "compact"; - const [measuredViewportWidth, setViewportWidth] = useState(() => (splitLayout ? 0 : windowWidth)); + const [initialSplitViewport] = useState(() => + splitLayout && lastSplitViewport?.windowWidth === windowWidth ? lastSplitViewport : null, + ); + const [measuredViewportWidth, setViewportWidth] = useState(() => + splitLayout ? (initialSplitViewport?.width ?? 0) : windowWidth, + ); const viewportWidth = settledPaneWidth !== null ? Math.round(settledPaneWidth) : measuredViewportWidth; - const [viewportHeight, setViewportHeight] = useState(0); + const [viewportHeight, setViewportHeight] = useState(() => initialSplitViewport?.height ?? 0); const [disclosureLayout, setDisclosureLayout] = useState(null); const disclosureMotionRef = useRef(null); const disclosureMotionTimer = useRef | null>(null); @@ -2796,7 +3004,121 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // A v1 link names no environment, so it falls back to this message's. return scopeThreadRef(props.environmentId, link.threadId); }; - const onMarkdownLinkPress = (href: string, imageEmbed = false) => { + // The file a chat link names: in this workspace, else in the one other project that has it. + const findFileLinkTarget = async ( + linkPath: string, + path: string, + signal: AbortSignal, + reply: MarkdownLinkReply | undefined, + ): Promise => { + const relativePath = resolveWorkspaceRelativeFilePath(props.workspaceRoot, path); + if ( + !props.workspaceRoot || + !relativePath || + /[\\/]$/.test(linkPath) || + workspaceLinkLookupQuery(linkPath, props.workspaceRoot) === null || + !readEnvironmentScope(props.environmentId, AuthFilesystemReadScope) + ) { + return relativePath ?? path; + } + const workspaceRoot = props.workspaceRoot; + const originalPath = resolveWorkspaceFilePath(workspaceRoot, relativePath); + const queryOptions = { signal, reportFailure: false, reportDefect: false }; + const searchRoot = (root: string) => + executeAtomQuery( + appAtomRegistry, + projectEnvironment.searchEntries({ + environmentId: props.environmentId, + input: { + cwd: root, + query: workspaceLinkLookupQuery(relativePath, root) ?? relativePath, + kind: "file", + limit: WORKSPACE_BASENAME_LOOKUP_LIMIT, + }, + }), + queryOptions, + ).then((result) => ({ + root, + entries: result._tag === "Success" ? result.value.entries : [], + })); + const metadataOf = (target: string) => + executeAtomQuery( + appAtomRegistry, + projectEnvironment.fileMetadata({ + environmentId: props.environmentId, + input: { path: target }, + }), + queryOptions, + ); + const lookup = async () => { + const own = await searchRoot(workspaceRoot); + let match = pickWorkspaceLinkMatch(relativePath, workspaceRoot, own.entries); + const otherProject = match === null; + if (otherProject) { + const threadProjectId = appAtomRegistry.get( + environmentThreadShells.threadShellAtom( + scopeThreadRef(props.environmentId, props.threadId), + ), + )?.projectId; + const otherRoots = appAtomRegistry + .get(environmentProjects.projectsAtom) + .flatMap((project) => + project.environmentId === props.environmentId && + project.id !== threadProjectId && + project.workspaceRoot !== workspaceRoot + ? [project.workspaceRoot] + : [], + ); + match = + otherRoots.length === 0 + ? null + : pickProjectLinkMatch(relativePath, await Promise.all(otherRoots.map(searchRoot))); + } + if (match === null && reply !== undefined && !signal.aborted) { + // No project has the file, so it opens where the agent last worked, as written. + const agentRoots = agentWorkingDirectories( + appAtomRegistry.get( + environmentThreadDetails.quietThreadAtom( + scopeThreadRef(props.environmentId, props.threadId), + ), + )?.projection.visibleTurnItems ?? [], + reply, + ).filter((root) => root !== workspaceRoot); + const agentPaths = agentRoots.map((root) => resolveWorkspaceFilePath(root, relativePath)); + if (agentPaths.length === 0) return relativePath; + const [original, ...found] = await Promise.all( + [originalPath, ...agentPaths].map(metadataOf), + ); + if (original?._tag !== "Success" || original.value !== null) return relativePath; + const index = found.findIndex( + (result) => result._tag === "Success" && result.value?.kind === "file", + ); + const literal = agentPaths[index]; + if (literal !== undefined || !needsWorkspaceBasenameLookup(relativePath)) { + return literal ?? relativePath; + } + return ( + (await findAgentDirectoryMatch(relativePath, agentRoots, searchRoot)) ?? relativePath + ); + } + if (!match || match === relativePath || signal.aborted) return relativePath; + const metadata = await metadataOf(originalPath); + // Another project's file never replaces a thread-local file the search missed. + return metadata._tag === "Success" && + (needsWorkspaceBasenameLookup(relativePath) && !otherProject + ? metadata.value?.kind !== "directory" + : metadata.value === null) + ? match + : relativePath; + }; + return lookup().catch(() => relativePath); + }; + const onMarkdownLinkPress = ( + href: string, + imageEmbed = false, + reply?: MarkdownLinkReply, + withGallery?: (source: FilePreviewSource) => FilePreviewSource, + ) => { markdownLinkRequest.current?.abort(); const request = new AbortController(); markdownLinkRequest.current = request; @@ -2829,7 +3151,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (request.signal.aborted) return; openPreview( scope, - media.kind === "video" ? { video: media.source } : { file: media.source }, + media.kind === "video" + ? { video: media.source } + : { file: withGallery ? withGallery(media.source) : media.source }, ); }; const resource = "resource" in media.source ? media.source.resource : null; @@ -2863,8 +3187,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (presentation.kind === "file") { const path = resolveFileLinkPath(props.workspaceRoot, presentation.path); if (path === null) return; - const relativePath = resolveWorkspaceRelativeFilePath(props.workspaceRoot, path); - const openAt = (target: string) => { + void findFileLinkTarget(presentation.path, path, request.signal, reply).then((target) => { if (request.signal.aborted) return; void Haptics.selectionAsync(); navigation.navigate("ThreadFile", { @@ -2873,62 +3196,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { path: fileRoutePathSegments(target), ...(presentation.line ? { line: String(presentation.line) } : {}), }); - }; - if ( - props.workspaceRoot && - relativePath && - !/[\\/]$/.test(presentation.path) && - workspaceLinkLookupQuery(presentation.path, props.workspaceRoot) !== null && - readEnvironmentScope(props.environmentId, AuthFilesystemReadScope) - ) { - const workspaceRoot = props.workspaceRoot; - const originalPath = resolveWorkspaceFilePath(props.workspaceRoot, relativePath); - void executeAtomQuery( - appAtomRegistry, - projectEnvironment.searchEntries({ - environmentId: props.environmentId, - input: { - cwd: workspaceRoot, - query: workspaceLinkLookupQuery(relativePath, workspaceRoot) ?? relativePath, - kind: "file", - limit: WORKSPACE_BASENAME_LOOKUP_LIMIT, - }, - }), - { signal: request.signal, reportFailure: false, reportDefect: false }, - ).then( - (result) => { - const match = - result._tag === "Success" - ? pickWorkspaceLinkMatch(relativePath, workspaceRoot, result.value.entries) - : null; - if (!match || match === relativePath) { - openAt(relativePath); - return; - } - if (request.signal.aborted) return; - void executeAtomQuery( - appAtomRegistry, - projectEnvironment.fileMetadata({ - environmentId: props.environmentId, - input: { path: originalPath }, - }), - { signal: request.signal, reportFailure: false, reportDefect: false }, - ).then( - (metadata) => - openAt( - metadata._tag === "Success" && - (needsWorkspaceBasenameLookup(relativePath) - ? metadata.value?.kind !== "directory" - : metadata.value === null) - ? match - : relativePath, - ), - () => openAt(relativePath), - ); - }, - () => openAt(relativePath), - ); - } else openAt(relativePath ?? path); + }); return; } @@ -2958,15 +3226,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }, standalone, ), - onLinkPress: onMarkdownLinkPress, + onLinkPress: (href, reply) => onMarkdownLinkPress(href, false, reply), linkCustomization: enrichedThreadLinkCustomization, - onImagePress: (href) => onMarkdownLinkPress(href, true), + onImagePress: (href, withGallery) => onMarkdownLinkPress(href, true, undefined, withGallery), resolveImageSource, fileContextMenu: (href) => { const skill = enrichedSkillReference(href, props.skills); if (skill) { return { - title: enrichedSkillDisplayName(skill), + title: formatProviderSkillDisplayName(skill), actions: [ { id: "open-skill", @@ -2988,7 +3256,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const target = resolveFileChipTarget(href, props.workspaceRoot); return target ? fileChipMenu(target) : undefined; }, - onFileContextMenuAction: (href, actionId) => { + onFileContextMenuAction: (href, actionId, reply) => { const skill = enrichedSkillReference(href, props.skills); if (skill) { const instructionsPath = enrichedSkillInstructionsPath(skill); @@ -3006,12 +3274,41 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { switch (actionId) { case "copy-full-path": case "copy-relative-path": { - const clipboardPath = fileChipClipboardPath(target, actionId); - if (clipboardPath !== undefined) copyTextWithHaptic(clipboardPath); + const presentation = resolveMarkdownLinkPresentation(href); + const path = + presentation.kind === "file" + ? resolveFileLinkPath(props.workspaceRoot, presentation.path) + : null; + if (presentation.kind !== "file" || path === null) return; + markdownLinkRequest.current?.abort(); + const request = new AbortController(); + markdownLinkRequest.current = request; + void findFileLinkTarget(presentation.path, path, request.signal, reply).then((found) => { + if (request.signal.aborted) return; + const fullPath = + props.workspaceRoot && !isAbsolutePath(found) + ? resolveWorkspaceFilePath(props.workspaceRoot, found) + : found; + const clipboardPath = fileChipClipboardPath( + { + ...target, + ...(target.fullPath ? { fullPath } : {}), + ...(target.relativePath + ? { + relativePath: + resolveWorkspaceRelativeFilePath(props.workspaceRoot, fullPath) ?? + target.relativePath, + } + : {}), + }, + actionId, + ); + if (clipboardPath !== undefined) copyTextWithHaptic(clipboardPath); + }); return; } case "open-file": - onMarkdownLinkPress(href); + onMarkdownLinkPress(href, false, reply); return; case "save": shareFileChip(target); @@ -3155,8 +3452,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const listAppearanceData = { disclosureLayout, reduceMotion, + formatMessageTime, worktreeSetup: props.worktreeSetup, setupWorkingStartedAt: props.setupWorkingStartedAt, + preparingWorktree: props.preparingWorktree, dispatchingMessageId: props.dispatchingMessageId, unsettledTurnId, copiedRowId, @@ -3180,10 +3479,28 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { headerMaterialVisibleRef.current = visible; onHeaderMaterialVisibilityChange?.(visible); }; - const handleMetricsChange = () => { + const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); + const [loadedListKey, setLoadedListKey] = useState(null); + const [landedListKey, setLandedListKey] = useState(null); + // LegendList reports ready, and shows its rows, while rows measured during its initial scroll can + // still leave it hundreds of points short of the end; isAtEnd stays true through that. + const settling = props.feed.length > 0 && landedListKey !== feedThreadKey; + const landingFallback = useRef | null>(null); + const reportMetrics = (ready: boolean) => { const state = listRef.current?.getState(); - if (state) onIsAtEndChange?.(state.isAtEnd); + if (!state) return; + if ( + settling && + ready && + (state.distanceFromEnd <= 2 || !state.isFollowingEnd || props.jumpToMessageId) + ) { + setLandedListKey(feedThreadKey); + } + // Offset 0 before the first positioning, and the gaps while rows measure in, are not the + // user leaving the end; only a scroll away stops end following. + onIsAtEndChange?.(settling || state.isAtEnd || state.isFollowingEnd); }; + const handleMetricsChange = () => reportMetrics(loadedListKey === feedThreadKey); const handleScroll = (event: NativeSyntheticEvent) => { reportHeaderMaterialVisibility( event.nativeEvent.contentOffset.y + (usesNativeAutomaticInsets ? barInset : 0) > 6, @@ -3197,6 +3514,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { handleMetricsChange(); const stops = [ state.listen("isAtEnd", handleMetricsChange), + state.listen("isFollowingEnd", handleMetricsChange), state.listen("totalSize", handleMetricsChange), state.listen("footerSize", handleMetricsChange), state.listen("headerSize", handleMetricsChange), @@ -3205,7 +3523,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { for (const stop of stops) stop(); }; }, [listRef, handleMetricsChange]); - const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the landing fallback timer when the feed unmounts + useEffect( + () => () => { + if (landingFallback.current !== null) clearTimeout(landingFallback.current); + }, + [], + ); const [workGroupScrollPositions] = useState( () => new Map(), ); @@ -3213,7 +3537,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // Opening at a message: once the filled list has loaded, the render that sees // the jump unfolds a run hiding the message and stops following the end, so // the committed list holds the target row with end maintenance off. - const [loadedListKey, setLoadedListKey] = useState(null); const { jumpToMessageId } = props; const jumpReady = !!jumpToMessageId && loadedListKey === feedThreadKey; if (jumpReady && revealedMessageId !== jumpToMessageId) { @@ -3228,7 +3551,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const jumpRunId = jumpReady && !presentedFeed.some((entry) => entry.type === "message" && entry.id === jumpToMessageId) - ? messageFoldRunId(props.feed, jumpToMessageId) + ? messageFoldRunId(props.feed, jumpToMessageId, presentedFeed) : null; if (jumpRunId && !expandedTurnIds.has(jumpRunId)) { setInteractionState((current) => ({ @@ -3243,7 +3566,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const groupedFeed = groupFeed(presentedFeed, { workflowOpeningMessageId: workflowOpening?.messageId, setupAnchorIndex: - props.worktreeSetup || props.setupWorkingStartedAt ? setupAnchorIndex : undefined, + props.worktreeSetup || props.setupWorkingStartedAt || props.preparingWorktree + ? setupAnchorIndex + : undefined, }); const { contentInsetEndAdjustment } = props; const attachList = (list: LegendListRef | null) => { @@ -3277,6 +3602,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const handleViewportLayout = (event: LayoutChangeEvent) => { const nextWidth = Math.round(event.nativeEvent.layout.width); const nextHeight = Math.round(event.nativeEvent.layout.height); + if (splitLayout) lastSplitViewport = { windowWidth, width: nextWidth, height: nextHeight }; setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current)); setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current)); }; @@ -3544,7 +3870,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { threadId={props.threadId} workspaceRoot={props.workspaceRoot} > - + {info.item.type === "message" && info.item.message.projectedItem?.item.type === "user_message" && info.item.message.projectedItem.item.freshContext ? ( @@ -3566,6 +3892,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ) : null} {renderFeedEntry(info, { userMessageGrouping: info.item.userMessageGrouping, + formatMessageTime, environmentId: props.environmentId, dispatchingMessageId: props.dispatchingMessageId, onEditPendingMessage: props.onEditPendingMessage, @@ -3611,6 +3938,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? ( + ) : props.preparingWorktree && info.index === setupAnchorIndex ? ( + ) : null} @@ -3619,13 +3948,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (props.contentPresentation.kind === "unavailable" && props.queuedMessages.length === 0) { return ( - + + + ); } @@ -3643,7 +3974,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { { setLoadedListKey(feedThreadKey); - handleMetricsChange(); + reportMetrics(true); + // Never leave the feed hidden if end following stalls short of the end. + landingFallback.current = setTimeout(() => setLandedListKey(feedThreadKey), 1000); }} onLayout={handleMetricsChange} onItemSizeChanged={handleItemSizeChanged} @@ -3705,6 +4039,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { {usesNativeAutomaticInsets ? null : } {setupAnchorIndex < 0 && props.worktreeSetup ? ( + ) : setupAnchorIndex < 0 && props.preparingWorktree ? ( + ) : null} {props.historyControls ? ( diff --git a/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx b/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx index e44a422212..b73f6f458e 100644 --- a/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx +++ b/apps/mobile/src/features/threads/ThreadInlineFilePreview.tsx @@ -10,7 +10,7 @@ import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView } from "../../components/ui/AppSymbol"; import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../../lib/videoAudioSession"; import { useRefreshAssetUrl } from "../../state/assets"; -import { ThreadMediaVisibleContext } from "./ThreadMarkdownVideo"; +import { ThreadMediaRetainContext, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo"; import { acquireAudioSession, activateAudioSession, @@ -59,7 +59,13 @@ function timestamp(seconds: number) { return `${Math.floor(value / 60)}:${String(value % 60).padStart(2, "0")}`; } -function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise }) { +function InlineAudio( + props: PreviewProps & { + readonly resolveUri: () => Promise; + readonly onPlaybackActivityChange?: (active: boolean) => void; + }, +) { + const { onPlaybackActivityChange } = props; // An empty source keeps native buffering off until the user explicitly plays. const player = usePlaybackAudioPlayer(null); const status = useAudioPlayerStatus(player); @@ -90,8 +96,16 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise< // oxlint-disable-next-line react/set-state-in-effect -- Native completion and fullscreen takeover invalidate the pending playback request. requestPlayback(false); } + if (status.didJustFinish || status.error) onPlaybackActivityChange?.(false); if (fullscreenVideoOpen) pauseAudioPlayer(player); - }, [fullscreenVideoOpen, status.didJustFinish, status.error, player, requestPlayback]); + }, [ + fullscreenVideoOpen, + status.didJustFinish, + status.error, + player, + requestPlayback, + onPlaybackActivityChange, + ]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to AppState to pause audio in the background and releases the audio session on cleanup useEffect(() => { active.current = true; @@ -131,6 +145,7 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise< ); if (!isAudioSessionOwner(token)) return; props.onPlaybackStart?.(); + onPlaybackActivityChange?.(true); audioToken.current = token; requestPlayback(true); const generation = ++requestGeneration.current; @@ -149,6 +164,7 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise< if (!isCurrentRequest() || AppState.currentState !== "active") return; if (!uri) { requestPlayback(false); + onPlaybackActivityChange?.(false); setError(true); return; } @@ -163,6 +179,7 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise< .catch(() => { if (isCurrentRequest()) { requestPlayback(false); + onPlaybackActivityChange?.(false); setError(true); } }) @@ -221,7 +238,9 @@ function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise< ); } -function VisibleFilePreview(props: PreviewProps) { +function VisibleFilePreview( + props: PreviewProps & { readonly onPlaybackActivityChange?: (active: boolean) => void }, +) { // Each mounted preview owns its source; feed streaming must not restart a fetch or player. const [source] = useState(props.source); const refresh = useRefreshAssetUrl( @@ -235,13 +254,27 @@ function VisibleFilePreview(props: PreviewProps) { export function ThreadInlineFilePreview(props: PreviewProps) { const visible = useContext(ThreadMediaVisibleContext); const focused = useIsFocused(); + const retainRow = useContext(ThreadMediaRetainContext); + // Unmounting disposes the native player, so a started player stays mounted off-screen + // (and its feed row out of recycling) until it finishes or fails. Leaving the screen + // disposes it, so the latch resets too; the feed drops its row pin on blur itself. + const [playbackActive, setPlaybackActive] = useState(false); + if (!focused && playbackActive) setPlaybackActive(false); + const onPlaybackActivityChange = (active: boolean) => { + setPlaybackActive(active); + retainRow(active); + }; return ( - {visible && focused ? ( - + {focused && (visible || playbackActive) ? ( + ) : ( <> diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx index 209cccf8d2..82f5cc62a7 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx @@ -3,19 +3,71 @@ import { act } from "react"; import { createRoot } from "react-dom/client"; import { expect, it, vi } from "vite-plus/test"; +type HandlerProps = Record void) | undefined>; +type GestureHandlers = Record void>; +type Transform = [{ translateX: number }, { translateY: number }, { scale: number }]; + const harness = vi.hoisted(() => ({ failImage: () => {}, loadImage: (_event: { source: { width: number; height: number } }) => {}, Passthrough: ({ children }: { children?: unknown }) => children, + pressable: {} as HandlerProps, + gestures: {} as Record, + contentStyle: () => ({}) as { transform?: Transform }, })); -vi.mock("react-native", () => ({ - Pressable: harness.Passthrough, - StyleSheet: { absoluteFill: {} }, - View: ({ children, style }: { children?: ReactNode; style?: unknown }) => ( +vi.mock("react-native", () => { + const View = ({ children, style }: { children?: ReactNode; style?: unknown }) => (
{children}
- ), -})); + ); + return { + Platform: { OS: "ios" }, + Pressable: (props: HandlerProps & { children?: ReactNode; style?: unknown }) => { + harness.pressable = props; + return {props.children}; + }, + StyleSheet: { absoluteFill: {} }, + View, + }; +}); +vi.mock("react-native-gesture-handler", () => { + // Records each gesture's callbacks so a test can drive the worklets with native-shaped events. + const builder = (kind: string) => () => { + const handlers: GestureHandlers = {}; + harness.gestures[kind] = handlers; + const gesture: object = new Proxy( + {}, + { + get: (_target, name) => (callback: GestureHandlers[string]) => { + if (typeof name === "string" && name.startsWith("on")) handlers[name] = callback; + return gesture; + }, + }, + ); + return gesture; + }; + return { + Gesture: { Pinch: builder("pinch"), Pan: builder("pan"), Simultaneous: () => ({}) }, + GestureDetector: ({ children }: { children?: ReactNode }) => children, + }; +}); +vi.mock("react-native-reanimated", async () => { + const { useState } = await import("react"); + return { + default: { View: ({ children }: { children?: ReactNode }) =>
{children}
}, + runOnJS: (callback: () => void) => callback, + // Reads the UI-thread style on demand, as Reanimated would after a gesture frame. + useAnimatedStyle: (updater: () => { transform?: Transform }) => { + harness.contentStyle = updater; + return {}; + }, + useSharedValue: (initial: T) => + useState(() => { + let value = initial; + return { get: () => value, set: (next: T) => void (value = next) }; + })[0], + }; +}); vi.mock("expo-image", () => ({ Image: (props: { onError: () => void; @@ -203,3 +255,146 @@ it("does not parse an obsolete SVG response after its last reader unmounts", asy registry.dispose(); } }); + +const zoom = () => { + const [{ translateX }, { translateY }, { scale }] = harness.contentStyle().transform!; + // Clamping at fit can yield -0, which is the same position. + return { scale, x: translateX + 0, y: translateY + 0 }; +}; +const pinch = (phase: "onStart" | "onUpdate", focalX: number, focalY: number, scale: number) => + act(async () => harness.gestures.pinch![phase]!({ focalX, focalY, scale, numberOfPointers: 2 })); +const endPinch = () => act(async () => harness.gestures.pinch!.onFinalize!({})); +const layout = (width: number, height: number) => + act(async () => harness.pressable.onLayout?.({ nativeEvent: { layout: { width, height } } })); +const markdownImage = (sourceKey: string, onPressPreview: () => void = () => {}) => ( + + + +); + +it("does not open the preview when a touch on the inline image pinches or pans it", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const onPressPreview = vi.fn(); + const touch = (fingers: number) => + act(async () => + harness.pressable.onTouchStart?.({ + nativeEvent: { touches: Array.from({ length: fingers }, () => ({})) }, + }), + ); + const release = () => + act(async () => harness.pressable.onPress?.({ nativeEvent: { identifier: 1 } })); + try { + await act(async () => root.render(markdownImage("hero", onPressPreview))); + await touch(1); + await touch(2); + await release(); + expect(onPressPreview).not.toHaveBeenCalled(); + + await touch(1); + await act(async () => harness.gestures.pan!.onStart!({ translationX: 5, translationY: 0 })); + await release(); + expect(onPressPreview).not.toHaveBeenCalled(); + + await touch(1); + await release(); + expect(onPressPreview).toHaveBeenCalledOnce(); + + // VoiceOver activation has no touch, so an earlier pinch must not swallow it. + await touch(2); + await act(async () => harness.pressable.onPress?.({ nativeEvent: {} })); + expect(onPressPreview).toHaveBeenCalledTimes(2); + } finally { + await act(async () => root.unmount()); + } +}); + +it("zooms the inline image around the pinch and keeps it until the source or frame changes", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const touchPan = () => { + const manager = { fail: vi.fn() }; + harness.gestures.pan!.onTouchesDown!({}, manager); + return manager; + }; + try { + await act(async () => root.render(markdownImage("a"))); + // The frame center is (172.5, 101); the pinch is off center. + await layout(345, 202); + await pinch("onStart", 300, 150, 1); + await pinch("onUpdate", 300, 150, 2); + expect(zoom()).toEqual({ scale: 2, x: -127.5, y: -49 }); + await pinch("onUpdate", 280, 140, 2); + expect(zoom()).toEqual({ scale: 2, x: -147.5, y: -59 }); + await act(async () => + harness.gestures.pinch!.onUpdate!({ focalX: 90, focalY: 90, scale: 2, numberOfPointers: 1 }), + ); + expect(zoom()).toEqual({ scale: 2, x: -147.5, y: -59 }); + await endPinch(); + + await act(async () => harness.loadImage({ source: { width: 1000, height: 585 } })); + await act(async () => root.render(markdownImage("a"))); + await layout(345, 202); + expect(zoom()).toEqual({ scale: 2, x: -147.5, y: -59 }); + + await pinch("onStart", 100, 50, 1); + await pinch("onUpdate", 100, 50, 1.5); + expect(zoom()).toEqual({ scale: 3, x: -185, y: -63 }); + await pinch("onUpdate", 100, 50, 10); + expect(zoom().scale).toBe(6); + await endPinch(); + + const zoomedPan = touchPan(); + await act(async () => harness.gestures.pan!.onStart!({ translationX: 5, translationY: 0 })); + await act(async () => + harness.gestures.pan!.onUpdate!({ translationX: 5000, translationY: -5000 }), + ); + expect(zoomedPan.fail).not.toHaveBeenCalled(); + expect(zoom()).toEqual({ scale: 6, x: 862.5, y: -505 }); + + await pinch("onStart", 172, 100, 1); + await pinch("onUpdate", 172, 100, 0.01); + await endPinch(); + expect(zoom()).toEqual({ scale: 1, x: 0, y: 0 }); + expect(touchPan().fail).toHaveBeenCalledOnce(); + + await pinch("onStart", 300, 150, 1); + await pinch("onUpdate", 300, 150, 2); + await endPinch(); + await layout(300, 175); + expect(zoom()).toEqual({ scale: 1, x: 0, y: 0 }); + + await pinch("onStart", 300, 150, 1); + await pinch("onUpdate", 300, 150, 2); + await endPinch(); + await act(async () => root.render(markdownImage("b"))); + expect(zoom()).toEqual({ scale: 1, x: 0, y: 0 }); + + for (const panFirst of [true, false]) { + await act(async () => root.render(markdownImage(`handoff-${panFirst}`))); + await layout(300, 200); + await pinch("onStart", 150, 100, 1); + await pinch("onUpdate", 150, 100, 2); + await endPinch(); + await act(async () => harness.gestures.pan!.onStart!({ translationX: 0, translationY: 0 })); + await pinch("onStart", 150, 100, 1); + const panUpdate = () => + act(async () => harness.gestures.pan!.onUpdate!({ translationX: 10, translationY: 0 })); + if (panFirst) await panUpdate(); + await pinch("onUpdate", 150, 100, 1.5); + if (!panFirst) await panUpdate(); + await endPinch(); + await act(async () => harness.gestures.pan!.onUpdate!({ translationX: 20, translationY: 0 })); + expect(zoom()).toEqual({ scale: 3, x: 10, y: 0 }); + } + } finally { + await act(async () => root.unmount()); + } +}); diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx index da9ba93583..7f4d51f19f 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx @@ -20,7 +20,9 @@ import { useMediaActions } from "../../state/mediaActions"; import type { MediaActionsSource } from "../../lib/mediaActionsSource"; import { useAssetUrlState } from "../../state/assets"; import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext"; +import { ZoomableImagePressable } from "./ZoomableImagePressable"; import { assetImageCacheKey } from "../../lib/assetImageSource"; +import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery"; import { MARKDOWN_IMAGE_MAX_WIDTH, type MarkdownImageDisplaySize, @@ -90,6 +92,7 @@ const noSvgDocumentAtom = Atom.make(AsyncResult.initial void; }) { const withGallery = useFilePreviewGallery(); - const sourceIdentifier = useId(); + const localSourceIdentifier = useId(); + const sourceIdentifier = props.sourceIdentifier ?? localSourceIdentifier; const mediaActions = useMediaActions(props.actionsSource); const contextWidth = useContext(MarkdownImageAvailableWidthContext); const [measuredWidth, setMeasuredWidth] = useState(0); @@ -167,7 +171,8 @@ export function ThreadMarkdownImageView(props: { ) : ( - - - {props.format === "svg" ? ( - - ) : ( - - // Only the first decode counts: later loads report the bitmap - // downsampled for the current frame (969 vs 970 wide), so keeping - // them resizes the frame, which reloads the image, and so on. - setDecoded((current) => - current?.sourceKey === props.sourceKey - ? current - : { sourceKey: props.sourceKey, size }, - ) - } - onError={() => setFailure({ uri: props.uri, failed: true })} - /> - )} - - + {props.format === "svg" ? ( + + ) : ( + + // Only the first decode counts: later loads report the bitmap + // downsampled for the current frame (969 vs 970 wide), so keeping + // them resizes the frame, which reloads the image, and so on. + setDecoded((current) => + current?.sourceKey === props.sourceKey + ? current + : { sourceKey: props.sourceKey, size }, + ) + } + onError={() => setFailure({ uri: props.uri, failed: true })} + /> + )} + )} @@ -310,6 +310,11 @@ export function ThreadMarkdownImage(props: { : undefined } sourceKey={sourceKey} + sourceIdentifier={filePreviewSourceIdentifier({ + kind: "image", + environmentId: props.environmentId, + resource: props.resource, + })} unavailable={assetUrl._tag === "Failure"} unavailableDetail={ assetUrl._tag === "Failure" && assetUrl.reason === "missing-file-access" diff --git a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx index 457b7878ea..3e2d5dc050 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx @@ -1,3 +1,4 @@ +import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets"; import { createContext, useContext } from "react"; import { MediaVideoPlayer } from "../../components/MediaVideoPlayer"; import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets"; @@ -8,9 +9,13 @@ import { } from "../../lib/videoPreviewSource"; export const ThreadMediaVisibleContext = createContext(false); +/** Asks the feed to keep this row out of list recycling while its media holds playback state. */ +export const ThreadMediaRetainContext = createContext<(retained: boolean) => void>(() => {}); export function ThreadMarkdownVideo(props: { readonly source: MediaVideoPreviewSource; + /** Keeps the player and its poster across source changes that show the same video. */ + readonly thumbnailKey?: string; readonly thumbnailVisible?: boolean; readonly onPlaybackStart?: () => void; readonly borderRadius?: number; @@ -18,7 +23,7 @@ export function ThreadMarkdownVideo(props: { const { source } = props; const feedVisible = useContext(ThreadMediaVisibleContext); const visible = props.thumbnailVisible ?? feedVisible; - const thumbnailKey = mediaVideoThumbnailKey(source); + const thumbnailKey = props.thumbnailKey ?? mediaVideoThumbnailKey(source); const asset = useAssetUrlState( "environmentId" in source ? source.environmentId : null, "resource" in source ? source.resource : null, @@ -43,6 +48,11 @@ export function ThreadMarkdownVideo(props: { visible={visible} onPlaybackStart={props.onPlaybackStart} unavailable={"resource" in source && asset._tag === "Failure"} + unavailableDetail={ + asset._tag === "Failure" && asset.reason === "missing-file-access" + ? MISSING_FILE_ACCESS_MESSAGE + : undefined + } actionsSource={source.actionsSource} borderRadius={props.borderRadius} /> diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 9b05470c53..0cf93babfe 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -2,10 +2,7 @@ // shared sidebar thread navigation with native chrome import { useActiveNewTask } from "../../state/active-new-task"; import { ThreadUndoNotice } from "../home/ThreadUndoNotice"; -import { - pickableProjectGroups, - resolveScratchProjectScopeKey, -} from "@t3tools/client-runtime/state/project-grouping"; +import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import type { EnvironmentProject, @@ -23,7 +20,7 @@ import { SidebarRowButton, SidebarViewToggle } from "../../fincke/SidebarViewTog import { useSidebarView } from "../../fincke/use-sidebar-view"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; import { AnimatedLegendList } from "@legendapp/list/reanimated"; -import { THREAD_SIDEBAR_ROW_LAYOUT } from "./threadListAnimations"; +import { THREAD_LIST_ROW_LAYOUT } from "./threadListAnimations"; import { useAtomValue } from "@effect/atom-react"; import { useMemo, useRef, useState } from "react"; import { Platform, StyleSheet, View } from "react-native"; @@ -32,8 +29,10 @@ import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSw import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; -import { useProjects, useNavigationThreadShells } from "../../state/entities"; +import { useProjects } from "../../state/entities"; +import { steadyNavigationThreadShellsAtom } from "../../state/threads"; import { useThreadSearch } from "../../state/queries"; import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences"; import { useThreadListNow } from "./use-thread-list-now"; @@ -48,12 +47,20 @@ import { useQueuedThreadKeys } from "../../state/use-thread-outbox"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { useThreadListV2 } from "./useThreadListV2"; +import { useSidebarRowThreadKey } from "./useSidebarRowThreadKey"; import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts"; import { requestThreadMessageJump } from "./threadMessageJump"; import { useThreadListSearchMatches } from "./useThreadListSearchMatches"; import { useHomeListOptions } from "../home/home-list-options"; -import { buildHomeListFilterMenuItems } from "../home/home-list-filter-menu"; -import { buildHomeProjectScopes, sortHomeProjectScopes } from "../home/homeThreadList"; +import { + buildHomeListFilterMenuItems, + homeListFilterEnvironments, +} from "../home/home-list-filter-menu"; +import { + buildHomeProjectScopes, + resolveHomeProjectFilterScope, + sortHomeProjectScopes, +} from "../home/homeThreadList"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions"; import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; import { useThreadListActions } from "../home/useThreadListActions"; @@ -136,7 +143,8 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { const insets = useSafeAreaInsets(); const projects = useProjects(); - const threads = useNavigationThreadShells(); + const threads = useAtomValue(steadyNavigationThreadShellsAtom); + const selectedThreadKey = useSidebarRowThreadKey(props.selectedThreadKey); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); const { savedConnectionsById } = useSavedRemoteConnections(); const openSwipeableRef = useRef(null); @@ -163,12 +171,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { const { confirmDeletePendingTask } = usePendingTaskListActions((params) => selectDetail({ name: "Thread", params }), ); - const environments = Object.values(savedConnectionsById) - .map((connection) => ({ - environmentId: connection.environmentId, - label: connection.environmentLabel, - })) - .sort((left, right) => left.label.localeCompare(right.label)); + const environments = homeListFilterEnvironments(workspaceEnvironments); const availableEnvironmentIds = new Set( environments.map((environment) => environment.environmentId), ); @@ -186,12 +189,6 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ) ? [options.selectedEnvironmentId] : []; - // A legacy per-environment scratch key resolves here on every render; the stored - // value is only rewritten when the user picks a filter. - const resolvedProjectKey = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { - sidebarProjectGroupingMode: options.projectGroupingMode, - sidebarProjectGroupingOverrides: {}, - }); const projectScopes = useMemo( () => buildHomeProjectScopes({ @@ -201,7 +198,14 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { }), [projects, options.selectedEnvironmentId, options.projectGroupingMode], ); - const projectFilterOptions = pickableProjectGroups(projectScopes).map((scope) => ({ + const projectFilterOptions = pickableProjectGroups( + sortHomeProjectScopes({ + scopes: projectScopes, + threads, + pendingTasks: [], + projectSortOrder: "updated_at", + }), + ).map((scope) => ({ key: scope.key, label: scope.title, })); @@ -220,9 +224,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ), [projectScopes], ); - // An archived project's filter reads as all projects, matching the filter menu. - const selectedProjectScope = - pickableProjectGroups(projectScopes).find((scope) => scope.key === resolvedProjectKey) ?? null; + const selectedProjectScope = resolveHomeProjectFilterScope(projectScopes, projects, options); const threadSearch = useThreadSearch( searchEnvironmentIds, props.searchQuery, @@ -304,7 +306,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded, - selectedThreadKey: props.selectedThreadKey ?? null, + selectedThreadKey, timeOnStatusRows: true, }); // fincke: the projects view groups the same rows under their projects, like desktop @@ -323,7 +325,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { }), collapsedScopeKeys: sidebarView.collapsedProjectKeys, expandedScopeKeys: sidebarView.expandedProjectKeys, - selectedThreadKey: props.selectedThreadKey ?? null, + selectedThreadKey, selectedPendingKey: activeNewTask?.pendingKey ?? null, }) : settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 @@ -386,7 +388,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { // Recycle equality needs project/search data for titles and favicons; keep the minute clock on items to limit updates. const listExtraData = { activeNewTask, - selectedThreadKey: props.selectedThreadKey ?? "", + selectedThreadKey: selectedThreadKey ?? "", projectByKey, projectTitleByProjectKey, savedConnectionsById, @@ -442,10 +444,9 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { scopedThreadKey( item.pendingTask.environmentId, item.pendingTask.message.threadId, - ) === props.selectedThreadKey) + ) === selectedThreadKey) } project={projectByKey.get(pendingScopeKey) ?? null} - projectTitle={projectTitleByProjectKey.get(pendingScopeKey)} environmentLabel={ Object.keys(savedConnectionsById).length > 1 ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null) @@ -507,7 +508,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { showActiveHeading={item.showActiveHeading} selected={ !activeNewTask && - scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey + scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey } fullSwipeWidth={props.width - 20} onSelectThread={handleSelectThread} @@ -615,26 +616,43 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { }} /> ); + const showAddEnvironment = + !catalogState.isLoadingConnections && + !catalogState.hasReadyEnvironment && + !catalogState.hasConnectingEnvironment; const listEmpty = ( - - {catalogState.isLoadingConnections - ? "Loading threads…" - : Platform.OS === "android" && !catalogState.hasConnections - ? "No environments connected" - : props.searchQuery.trim().length > 0 - ? threadSearch.isPending - ? "Searching thread messages…" - : "No matching threads" - : selectedProjectScope !== null - ? `No threads in ${selectedProjectScope.title}` - : "No threads yet"} - + + + {catalogState.isLoadingConnections + ? "Loading threads…" + : showAddEnvironment + ? "No environments connected" + : props.searchQuery.trim().length > 0 + ? threadSearch.isPending + ? "Searching thread messages…" + : "No matching threads" + : selectedProjectScope !== null + ? `No threads in ${selectedProjectScope.title}` + : "No threads yet"} + + {showAddEnvironment ? ( + + - ), - useWindowDimensions: () => ({ height: 800 }), -})); vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) })); -vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) })); vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); -vi.mock("../../../components/ui/ScreenContent", () => ({ - ScreenContent: ({ children }: { children: ReactNode }) =>
{children}
, +vi.mock("../../../components/ui/FitSheet", () => ({ + FitSheet: ({ children }: { children: ReactNode }) =>
{children}
, })); vi.mock("../../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null })); -vi.mock("../../../components/ui/AppText", () => ({ - AppText: ({ children }: { children: ReactNode }) => {children}, - AppTextInput: () => null, +vi.mock("../../../components/ui/FormSection", () => ({ + FormSection: () => null, + FormField: () => null, +})); +vi.mock("../../../components/ui/ListSection", () => ({ + ListSection: ({ children }: { children: ReactNode }) =>
{children}
, +})); +vi.mock("../../../components/ui/ListChoiceRow", () => ({ + ListChoiceRow: (props: { label: string; description: string; disabled: boolean }) => ( + + ), })); vi.mock("./gitSheetComponents", () => ({ SheetActionButton: () => null })); vi.mock("../../../state/entities", () => ({})); diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx index 6bd008116b..fef45b5c88 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx @@ -17,28 +17,20 @@ const state = vi.hoisted(() => ({ })); vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ goBack() {} }) })); -vi.mock("react-native", () => ({ - Platform: { OS: "android" }, - useWindowDimensions: () => ({ height: 800 }), - View: ({ children }: { children: ReactNode }) => children, - ScrollView: ({ children }: { children: ReactNode }) => children, - Pressable: () => null, -})); -vi.mock("react-native-safe-area-context", () => ({ - useSafeAreaInsets: () => ({ bottom: 0 }), -})); vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); -vi.mock("../../../components/ui/ScreenContent", () => ({ - ScreenContent: ({ children }: { children: ReactNode }) => children, +vi.mock("../../../components/ui/FitSheet", () => ({ + FitSheet: ({ children }: { children: ReactNode }) => children, })); vi.mock("../../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null })); -vi.mock("../../../components/ui/AppText", () => ({ - AppText: ({ children }: { children: ReactNode }) => children, - AppTextInput: (props: InputProps) => { +vi.mock("../../../components/ui/FormSection", () => ({ + FormSection: ({ children }: { children: ReactNode }) => children, + FormField: (props: InputProps) => { state.inputs.set(props.accessibilityLabel, props); return null; }, })); +vi.mock("../../../components/ui/ListSection", () => ({ ListSection: () => null })); +vi.mock("../../../components/ui/ListChoiceRow", () => ({ ListChoiceRow: () => null })); vi.mock("../../../state/query", () => ({ useEnvironmentQuery: () => ({ data: state.refName === null ? undefined : { refName: state.refName }, diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index 67d0818ee6..0f3d785b41 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -1,13 +1,12 @@ import { sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useState } from "react"; -import { Platform, Pressable, ScrollView, useWindowDimensions, View } from "react-native"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SheetHeader } from "../../../components/ui/SheetHeader"; -import { ScreenContent } from "../../../components/ui/ScreenContent"; -import { AppText as Text, AppTextInput as TextInput } from "../../../components/ui/AppText"; -import { cn } from "../../../lib/cn"; +import { FitSheet } from "../../../components/ui/FitSheet"; +import { FormField, FormSection } from "../../../components/ui/FormSection"; +import { ListChoiceRow } from "../../../components/ui/ListChoiceRow"; +import { ListSection } from "../../../components/ui/ListSection"; import { useEnvironmentQuery } from "../../../state/query"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; @@ -23,8 +22,6 @@ type GitBranchesSheetProps = StaticScreenProps<{ export function GitBranchesSheet(_props: GitBranchesSheetProps) { const navigation = useNavigation(); - const insets = useSafeAreaInsets(); - const { height: windowHeight } = useWindowDimensions(); const { selectedThread } = useThreadSelection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); @@ -62,160 +59,113 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) { const disabledExistingBranches = new Set(disabledExistingBranchNames); return ( - navigation.goBack()} />} + keyboardShouldPersistTaps="handled" + showsVerticalScrollIndicator={false} > - - + + { + const branch = sanitizeFeatureBranchName(newBranchName.trim()); + if (branch.length === 0) return; + void gitActions.onCreateSelectedThreadBranch(branch).then((result) => { + if (result === null) return; + setNewBranchName(""); + navigation.goBack(); + }); + }} + /> + + + + + + - - - New branch - - - { + const baseBranch = worktreeBaseBranch.trim(); + const newBranch = worktreeBranchName.trim(); + if (baseBranch.length === 0 || newBranch.length === 0) return; + void gitActions + .onCreateSelectedThreadWorktree({ baseBranch, newBranch }) + .then((result) => { + if (result === null) return; + setWorktreeBranchName(""); + navigation.goBack(); + }); + }} + /> + + + + {availableBranches.map((branch, index) => { + const disabled = disabledExistingBranches.has(branch.name); + const subtitle = branch.worktreePath + ? branch.worktreePath === currentWorktreePath + ? "Checked out in this thread" + : "Checked out in another worktree" + : branch.isDefault + ? "Default branch" + : "Local branch"; + + return ( + 0} + disabled={!canChangeThreadBranch || busy || disabled} onPress={() => { - const branch = sanitizeFeatureBranchName(newBranchName.trim()); - if (branch.length === 0) return; - void gitActions.onCreateSelectedThreadBranch(branch).then((result) => { + void gitActions.onCheckoutSelectedThreadBranch(branch.name).then((result) => { if (result === null) return; - setNewBranchName(""); navigation.goBack(); }); }} /> - - - - - New worktree - - {Platform.OS === "android" ? ( - Base branch - ) : null} - - {Platform.OS === "android" ? ( - New branch - ) : null} - - { - const baseBranch = worktreeBaseBranch.trim(); - const newBranch = worktreeBranchName.trim(); - if (baseBranch.length === 0 || newBranch.length === 0) return; - void gitActions - .onCreateSelectedThreadWorktree({ baseBranch, newBranch }) - .then((result) => { - if (result === null) return; - setWorktreeBranchName(""); - navigation.goBack(); - }); - }} - /> - - - - - Existing branches - - {branchesLoading ? ( - - Loading branches... - - ) : null} - {!branchesLoading && availableBranches.length === 0 ? ( - - No local branches found. - - ) : null} - {availableBranches.map((branch) => { - const disabled = disabledExistingBranches.has(branch.name); - const subtitle = branch.worktreePath - ? branch.worktreePath === currentWorktreePath - ? "Checked out in this thread" - : "Checked out in another worktree" - : branch.isDefault - ? "Default branch" - : "Local branch"; - - return ( - { - void gitActions.onCheckoutSelectedThreadBranch(branch.name).then((result) => { - if (result === null) return; - navigation.goBack(); - }); - }} - > - {Platform.OS !== "android" ? ( - - ) : null} - - {branch.name} - - {subtitle} - - ); - })} - -
- - navigation.goBack()} /> - + ); + })} + + ); } diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx index 637dab6768..fb1f7a19af 100644 --- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx @@ -1,11 +1,10 @@ -import { ScreenContent } from "../../../components/ui/ScreenContent"; +import { FitSheet } from "../../../components/ui/FitSheet"; import { SheetHeader } from "../../../components/ui/SheetHeader"; import { Button } from "../../../components/ui/Button"; import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useState } from "react"; -import { Platform, Pressable, ScrollView, useWindowDimensions, View } from "react-native"; +import { Pressable, View } from "react-native"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SymbolView } from "../../../components/ui/AppSymbol"; import { AppText as Text, AppTextInput as TextInput } from "../../../components/ui/AppText"; @@ -24,8 +23,6 @@ type GitCommitSheetProps = StaticScreenProps<{ export function GitCommitSheet(_props: GitCommitSheetProps) { const navigation = useNavigation(); - const insets = useSafeAreaInsets(); - const { height: windowHeight } = useWindowDimensions(); const { selectedThread } = useThreadSelection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); const gitState = useSelectedThreadGitState(); @@ -66,168 +63,149 @@ export function GitCommitSheet(_props: GitCommitSheetProps) { }); }; - const android = Platform.OS === "android"; - const header = ( - navigation.goBack()} - accessibilityLabel="Cancel commit" - /> - ); - return ( - // Material sheet drags follow the first nested-scrolling native view, and the inline - // header's Compose button is one, so Android renders content first and reverses the column. - navigation.goBack()} + accessibilityLabel="Cancel commit" + /> + } + keyboardShouldPersistTaps="handled" + keyboardDismissMode="on-drag" + automaticallyAdjustKeyboardInsets + contentContainerClassName="px-5 pt-4 gap-5" > - - - {isDefaultRef ? ( - - You’re on the default branch. You can create a new branch when committing. - - ) : null} - - Commit message - + {isDefaultRef ? ( + + You’re on the default branch. You can create a new branch when committing. + + ) : null} + + Commit message + + + Leave empty to generate a message automatically. + + + + + + Changed files - Leave empty to generate a message automatically. + {selectedFiles.length} of {allFiles.length} selected · + + {formatDiffCount(selectedInsertions)} −{formatDiffCount(selectedDeletions)} - - - - Changed files - - {selectedFiles.length} of {allFiles.length} selected · + - {formatDiffCount(selectedInsertions)} −{formatDiffCount(selectedDeletions)} - - - {allFiles.length > 0 ? ( -
"); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original"); @@ -153,6 +375,25 @@ describe("server browser element refs", () => { expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe(""); }); + it("types after a click by coordinates into a shadow-root field, and refuses a field inside an editable frame", async () => { + await page.setContent( + `
`, + ); + const field = page.locator("#host #field"); + const box = (await field.boundingBox())!; + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await ServerBrowserPage.type(page, { text: "shadow" }); + expect(await field.inputValue()).toBe("shadow"); + + // Refused for now: focus inside a frame cannot be checked from the top document. + const inner = page.frameLocator("iframe").locator("#inner"); + await inner.click(); + await expect(ServerBrowserPage.type(page, { text: "frame" })).rejects.toMatchObject({ + tag: "PreviewAutomationTargetNotEditableError", + }); + expect(await inner.inputValue()).toBe(""); + }); + it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => { await page.setContent(`
password:
@@ -288,6 +529,15 @@ describe("server browser element refs", () => { expect(result).toBe("Ready"); }); + it("returns object contents even when a legacy caller asks for a remote reference", async () => { + const input = decodeEvaluateInput({ + expression: "({ answer: 42, nested: { ready: true } })", + returnByValue: false, + }); + const result = await ServerBrowserPage.evaluate(cdp, input, 5_000); + expect(result).toEqual({ answer: 42, nested: { ready: true } }); + }); + it("still awaits the promise an async function returns", async () => { const result = await ServerBrowserPage.evaluate( cdp, @@ -378,7 +628,7 @@ describe("server browser snapshot screenshot", () => { const screenshotOf = async (html: string) => { const page = await context.newPage(); await page.setContent(html); - const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot({ + const input = { page, cdp: await context.newCDPSession(page), renderScale: 2, @@ -386,7 +636,8 @@ describe("server browser snapshot screenshot", () => { consoleEntries: [], networkEntries: [], actionTimeline: [], - }); + }; + const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot(input); // The server has no DOM types, so the decoder runs as page source. const points = [ [0.15, 0.75], @@ -405,7 +656,7 @@ describe("server browser snapshot screenshot", () => { Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data), ); })()`)) as Array<[number, number, number, number]>; - return { screenshot, fullScreenshot, pixels }; + return { screenshot, fullScreenshot, pixels, input }; }; const colorOf = ([red, green, blue]: readonly [number, number, number, number]) => blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`; @@ -420,13 +671,55 @@ describe("server browser snapshot screenshot", () => { }); it("captures a plain page at the shrunk size with its content in place", async () => { - const { screenshot, fullScreenshot, pixels } = await screenshotOf(halves("")); + const { screenshot, fullScreenshot, pixels, input } = await screenshotOf(halves("")); + const metadata = await ServerBrowserPage.snapshotMetadata(input); expect({ size: [screenshot.width, screenshot.height], fullSize: [fullScreenshot?.width, fullScreenshot?.height], + metadataSize: metadata.screenshot, colors: pixels.map(colorOf), - }).toEqual({ size: [1280, 800], fullSize: [2560, 1600], colors: ["blue", "red", "red"] }); + }).toEqual({ + size: [1280, 800], + fullSize: [2560, 1600], + metadataSize: { width: 1280, height: 800 }, + colors: ["blue", "red", "red"], + }); + }); + + it("records the destination of a finite entrance animation without waiting on infinite ones", async () => { + const page = await context.newPage(); + await page.setContent(` + + +
+
+ `); + await page.getByRole("button", { name: "Open" }).click(); + const frame = await ServerBrowserPage.captureFinalRecordingFrame( + await context.newCDPSession(page), + 80, + ); + expect(frame).toBeDefined(); + const pixel = (await page.evaluate(`(async () => { + const bytes = Uint8Array.from(atob(${JSON.stringify(frame)}), char => char.charCodeAt(0)); + const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" })); + const canvas = document.createElement("canvas"); + canvas.width = bitmap.width; + canvas.height = bitmap.height; + const context = canvas.getContext("2d"); + context.drawImage(bitmap, 0, 0); + return Array.from(context.getImageData(bitmap.width / 2, bitmap.height / 2, 1, 1).data); + })()`)) as [number, number, number, number]; + expect(colorOf(pixel)).toBe("red"); }); it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => { @@ -484,6 +777,144 @@ describe("server browser drag", () => { process.off("unhandledRejection", onUnhandled); } }); + + it("moves the mouse after dragstart, so pages that track a drag with mousemove see it", async () => { + const browser = await chromium.launch({ headless: true }); + try { + const page = await browser.newPage(); + await page.setContent(` +
+
source
+
target
+
+ `); + + await ServerBrowserPage.drag(page, { source: "#source", target: "#target" }); + + const events = (await page.evaluate("window.events")) as Array; + expect(events.slice(0, 2)).toEqual(["dragstart", "mousemove"]); + expect(events.at(-1)).toBe("mouseup"); + } finally { + await browser.close(); + } + }); +}); + +describe("server browser action timeout", () => { + type StepOptions = { readonly timeout?: number }; + it.each([ + { + action: "hover", + act: (page: Page) => ServerBrowserPage.hover(page, { selector: "#a", timeoutMs: 9_000 }), + last: ["#a.hover 1"], + }, + { + action: "drag", + act: (page: Page) => + ServerBrowserPage.drag(page, { source: "#a", target: "#b", timeoutMs: 9_000 }), + last: ["#a.dragTo 1", "#b.boundingBox 1"], + }, + ])("gives the $action's steps one shared timeout", async ({ act, last }) => { + let now = 0; + using _now = vi.spyOn(Date, "now").mockImplementation(() => now); + const steps: Array = []; + const box = { x: 0, y: 0, width: 20, height: 20 }; + const page = { + locator: (selector: string) => { + const record = (step: string, options: StepOptions) => + steps.push(`${selector}.${step} ${options.timeout}`); + return { + // Each step that finds the target takes 5 of the 9 seconds. + scrollIntoViewIfNeeded: async (options: StepOptions) => { + record("scrollIntoViewIfNeeded", options); + now += 5_000; + }, + boundingBox: async (options: StepOptions) => { + record("boundingBox", options); + now += 5_000; + return box; + }, + hover: async (options: StepOptions) => record("hover", options), + dragTo: async (_target: unknown, options: StepOptions) => record("dragTo", options), + }; + }, + } as unknown as Page; + + await act(page); + + expect(steps).toEqual(["#a.scrollIntoViewIfNeeded 9000", "#a.boundingBox 4000", ...last]); + }); +}); + +describe("server browser click", () => { + it("clicks a target the page replaced while it was being scrolled into view", async () => { + let scrolls = 0; + const clicks: Array = []; + const page = { + locator: () => ({ + // Playwright resolves the node once; a page re-rendering it detaches that node. + scrollIntoViewIfNeeded: async () => { + if (scrolls++ === 0) { + throw new Error("locator.scrollIntoViewIfNeeded: Element is not attached to the DOM"); + } + }, + boundingBox: async () => ({ x: 0, y: 0, width: 20, height: 20 }), + click: async (options: unknown) => { + clicks.push(options); + }, + count: async () => 1, + }), + once: () => {}, + off: () => {}, + } as unknown as Page; + + await expect(ServerBrowserPage.click(page, { selector: "#save" })).resolves.toEqual({ + x: 10, + y: 10, + }); + expect(clicks).toHaveLength(1); + }); + + it("retries a replaced target only within the action's timeout", async () => { + vi.useFakeTimers(); + try { + const timeouts: Array = []; + const clicks: Array = []; + const detached = new Error( + "locator.scrollIntoViewIfNeeded: Element is not attached to the DOM", + ); + const page = { + locator: () => ({ + scrollIntoViewIfNeeded: async (options?: { timeout?: number }) => { + timeouts.push(options?.timeout); + vi.advanceTimersByTime(60); + throw detached; + }, + click: async (options: unknown) => { + clicks.push(options); + }, + }), + } as unknown as Page; + + await expect( + ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 100 }), + ).rejects.toBe(detached); + expect(timeouts).toEqual([100, 40]); + expect(clicks).toHaveLength(0); + } finally { + vi.useRealTimers(); + } + }); }); describe("server browser evaluate", () => { @@ -520,6 +951,83 @@ describe("server browser evaluate", () => { }); }); +describe("server browser type", () => { + // As on a desktop tab whose Playwright utility world never answers. + const stalledPage = (focusAnswer: () => Promise, typed: string[]) => + ({ + locator: () => ({ last: () => ({ count: () => new Promise(() => {}) }) }), + evaluate: focusAnswer, + keyboard: { insertText: async (text: string) => void typed.push(text) }, + }) as unknown as Page; + + it("types into the focused field when Playwright's utility world never answers", async () => { + vi.useFakeTimers(); + try { + const typed: string[] = []; + let outcome: unknown = "pending"; + const page = stalledPage(async () => true, typed); + void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then( + () => (outcome = "typed"), + (error: unknown) => (outcome = error), + ); + await vi.advanceTimersByTimeAsync(300); + expect(outcome).toBe("typed"); + expect(typed).toEqual(["hello"]); + } finally { + vi.useRealTimers(); + } + }); + + it("stops at its timeout without typing when the page never answers", async () => { + vi.useFakeTimers(); + try { + const typed: string[] = []; + let outcome: unknown = "pending"; + const page = stalledPage(() => new Promise(() => {}), typed); + void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then( + () => (outcome = "typed"), + (error: unknown) => (outcome = error), + ); + await vi.advanceTimersByTimeAsync(300); + expect(outcome).toMatchObject({ + tag: "PreviewAutomationTimeoutError", + detail: { timeoutMs: 300 }, + }); + expect(typed).toEqual([]); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe("server browser unresponsive script", () => { + it("leaves a page that answers alone", async () => { + const send = vi.fn(async (_method: string) => ({})); + await ServerBrowserPage.stopUnresponsiveScript({ send } as unknown as CDPSession); + expect(send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]); + }); +}); + +describe("server browser wait", () => { + it("ends at its timeout when a check never answers", async () => { + // As on a desktop tab whose Playwright utility world never answers. + const page = { + locator: () => ({ count: () => new Promise(() => {}) }), + } as unknown as Page; + vi.useFakeTimers(); + try { + let failure: unknown; + void ServerBrowserPage.waitFor(page, { selector: "button", timeoutMs: 300 }).catch( + (error: unknown) => (failure = error), + ); + await vi.advanceTimersByTimeAsync(300); + expect(failure).toMatchObject({ tag: "PreviewAutomationTimeoutError" }); + } finally { + vi.useRealTimers(); + } + }); +}); + describe("server browser net errors", () => { it.each([ ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102], diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index 31cff821c6..f772c608ca 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -14,6 +14,8 @@ import { type PreviewAutomationSelectInput, type PreviewAutomationSelectResult, type PreviewAutomationSnapshot, + type PreviewAutomationSnapshotMetadata, + type PreviewAutomationSnapshotStage, type PreviewAutomationTypeInput, type PreviewAutomationUploadInput, type PreviewAutomationWaitForInput, @@ -22,6 +24,7 @@ import { constVoid } from "effect/Function"; import * as Schema from "effect/Schema"; import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core"; import * as NodeCrypto from "node:crypto"; +import * as NodeUtil from "node:util"; import { BrowserControlInterrupted } from "./SessionControl.ts"; const isBrowserControlInterrupted = Schema.is(BrowserControlInterrupted); @@ -29,6 +32,8 @@ const isBrowserControlInterrupted = Schema.is(BrowserControlInterrupted); const MAX_EVALUATION_BYTES = 64_000; const MAX_VISIBLE_TEXT_LENGTH = 20_000; const MAX_SCREENSHOT_WIDTH = 1280; +// Two attempts must fit in a snapshot's 10-second deadline. +const SCREENSHOT_TIMEOUT_MS = 3_000; const WAIT_POLL_MS = 100; export const DIAGNOSTIC_BUFFER_LIMIT = 200; @@ -60,13 +65,11 @@ export const toOperationError = ( if (cause instanceof Error && cause.name === "TimeoutError") { return new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: firstLine, + message: withActionabilityReason(firstLine, cause), detail: timeoutMs === undefined ? undefined : { timeoutMs }, }); } - if ( - /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message) - ) { + if (/while parsing selector|Unknown engine|Unexpected token/i.test(message)) { return new ServerBrowserOperationError({ tag: "PreviewAutomationInvalidSelectorError", message: firstLine, @@ -84,6 +87,17 @@ export const toOperationError = ( }); }; +/** Playwright puts why an element was not actionable in its call log, below the first line. */ +const withActionabilityReason = (message: string, cause: Error) => { + // Playwright dims call-log lines with ANSI escapes when colour is on. + const reason = NodeUtil.stripVTControlCharacters(cause.message) + .split("\n") + .map((line) => line.trim()) + .findLast((line) => line.startsWith("- element is ")) + ?.slice(2); + return reason === undefined ? message : `${message} Playwright last saw: ${reason}.`; +}; + const DEFAULT_TIMEOUT_MS = 15_000; const TARGET_COUNT_MS = 250; const MAX_TARGET_CHARS = 200; @@ -147,15 +161,32 @@ export type PointerReporter = ( ) => Promise; const noPointer: PointerReporter = async () => {}; +// Locator.scrollIntoViewIfNeeded resolves its node once and fails when the page replaces it; the +// input actions after it re-resolve, so the scroll does too, within the same timeout. +const DETACHED = /^locator\.scrollIntoViewIfNeeded: Element is not attached to the DOM(?:\n|$)/; + +const scrollIntoView = async (locator: Locator, timeout: number) => { + const deadline = Date.now() + timeout; + for (;;) { + try { + return await locator.scrollIntoViewIfNeeded({ timeout: Math.max(1, deadline - Date.now()) }); + } catch (cause) { + if (!(cause instanceof Error && DETACHED.test(cause.message)) || Date.now() >= deadline) { + throw cause; + } + } + } +}; + const targetPoint = async ( page: Page, locator: Locator | null, input: { readonly x?: number | undefined; readonly y?: number | undefined }, - timeout: number, + timeout: () => number, ) => { if (locator === null) return { x: input.x ?? 0, y: input.y ?? 0 }; - await locator.scrollIntoViewIfNeeded({ timeout }); - const box = await locator.boundingBox({ timeout }); + await scrollIntoView(locator, timeout()); + const box = await locator.boundingBox({ timeout: timeout() }); if (box) return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; const viewport = page.viewportSize(); return { x: (viewport?.width ?? 0) / 2, y: (viewport?.height ?? 0) / 2 }; @@ -248,13 +279,36 @@ const pageChanged = () => message: "The page changed while capturing its snapshot. Take another snapshot.", }); -const tooBusy = () => +type SnapshotStage = typeof PreviewAutomationSnapshotStage.Type; + +/** + * Running stages are counted, since a retry can overlap the previous attempt's unanswered + * screenshot. A stage whose own timeout fired has stopped running but is still the cause. + */ +interface SnapshotStages { + readonly running: Map; + readonly timedOut: Set; +} + +const snapshotTimedOut = (stages?: SnapshotStages) => new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: - "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.", + message: `Snapshot capture timed out after ${SNAPSHOT_TIMEOUT_MS}ms. Try the snapshot again.`, + detail: { + timeoutMs: SNAPSHOT_TIMEOUT_MS, + pendingStages: stages ? [...new Set([...stages.timedOut, ...stages.running.keys()])] : [], + }, }); +const frameUnanswered = () => + new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: `A frame on the page didn't answer within ${FRAME_ANSWER_MS}ms, so its content couldn't be checked for hidden values. Try the snapshot again.`, + detail: { timeoutMs: FRAME_ANSWER_MS, pendingStages: ["frames"] }, + }); + +const isTimeout = (cause: unknown) => cause instanceof Error && cause.name === "TimeoutError"; + const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken."; /** Reuse one CDP session per out-of-process frame across snapshots. */ @@ -430,6 +484,37 @@ const pngSize = (base64: string) => { return { width: header.readUInt32BE(16), height: header.readUInt32BE(20) }; }; +export const jpegSize = (base64: string) => { + const bytes = Buffer.from(base64, "base64"); + if (bytes.length < 4 || bytes.readUInt16BE(0) !== 0xffd8) + throw new Error("Invalid JPEG screenshot."); + let offset = 2; + while (offset < bytes.length) { + if (bytes[offset++] !== 0xff) throw new Error("Invalid JPEG screenshot."); + while (bytes[offset] === 0xff) offset++; + const marker = bytes[offset++]; + if (marker === undefined || marker === 0xd9 || marker === 0xda) break; + if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue; + if (offset + 2 > bytes.length) break; + const length = bytes.readUInt16BE(offset); + if (length < 2 || offset + length > bytes.length) break; + if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) { + if (length < 7) break; + const height = bytes.readUInt16BE(offset + 3); + const width = bytes.readUInt16BE(offset + 5); + if (width && height) return { width, height }; + break; + } + offset += length; + } + throw new Error("Invalid JPEG screenshot."); +}; + +const scaledSize = (size: { readonly width: number; readonly height: number }, scale: number) => + scale < 1 + ? { width: Math.round(size.width * scale), height: Math.round(size.height * scale) } + : size; + /** * A page's display ratio and CSS viewport, read in an isolated world since page script can * reassign `devicePixelRatio`, `innerWidth`, and `innerHeight` in its own, and its page zoom. @@ -470,13 +555,48 @@ export const captureViewport = async ( cdp: CDPSession, options: { readonly format: "png" | "jpeg"; readonly quality?: number }, ) => { - const { data } = await cdp.send("Page.captureScreenshot", { + const capture = cdp.send("Page.captureScreenshot", { format: options.format, ...(options.quality === undefined ? {} : { quality: options.quality }), }); + let timer: ReturnType | undefined; + const expired = new Promise((_, reject) => { + timer = setTimeout( + () => + reject( + new ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: + "The browser is not producing screenshot frames. For a desktop tab, show or restore the 456code window and try again.", + }), + ), + SCREENSHOT_TIMEOUT_MS, + ); + }); + // Hidden native guests can leave CDP captures pending forever. This deadline also + // releases a viewer's still-capture lock, which an agent snapshot may be waiting for. + const { data } = await Promise.race([capture, expired]).finally(() => clearTimeout(timer)); return data; }; +export const captureFinalRecordingFrame = (cdp: CDPSession, quality: number) => + answered( + cdp + .send("Runtime.evaluate", { + // Capture the destination of finite transitions, not their initially transparent frame. + expression: `(async () => { + const paint = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + await paint(); + await Promise.allSettled(document.getAnimations() + .filter(animation => animation.playState === "running" && animation.effect?.getComputedTiming().iterations !== Infinity) + .map(animation => animation.finished)); + await paint(); + })()`, + awaitPromise: true, + }) + .then(() => captureViewport(cdp, { format: "jpeg", quality })), + ); + /** Runs in the page's own isolated world, as the server has no image library. */ const SHRINK_PNG = `async function (png, width, height) { const bytes = Uint8Array.from(atob(png), (char) => char.charCodeAt(0)); @@ -545,41 +665,73 @@ const renderingOf = async (input: SnapshotInput) => { const capture = async ( input: SnapshotInput, deadline: number, -): Promise => { - const { renderScale, viewport } = await renderingOf(input); + stages: SnapshotStages, + metadataOnly: boolean, +) => { + const { running } = stages; + const track = async
(stage: SnapshotStage, operation: () => Promise) => { + running.set(stage, (running.get(stage) ?? 0) + 1); + try { + const result = await operation(); + stages.timedOut.delete(stage); + return result; + } catch (cause) { + if (isTimeout(cause)) stages.timedOut.add(stage); + throw cause; + } finally { + const count = (running.get(stage) ?? 1) - 1; + if (count === 0) running.delete(stage); + else running.set(stage, count); + } + }; + const { renderScale, viewport } = await track("metrics", () => renderingOf(input)); // A late metrics reply must not begin a capture after viewers have resumed. - if (Date.now() >= deadline) throw tooBusy(); + if (Date.now() >= deadline) throw snapshotTimedOut(); const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * renderScale)); const state = refsFor(input.page); invalidateRefs(input.page); const generation = state.generation; - const { readers, read } = await openReaders(input.page, input.cdp); - const before = await read(); + const { readers, read } = await track("frames", () => openReaders(input.page, input.cdp)); + const before = await track("frames", () => read()); // Bracket the tree with value reads to detect changes; await tree completion before retrying failed captures. const pageAndScreenshot = Promise.all([ - input.page.evaluate(SNAPSHOT_SCRIPT) as Promise< - Pick< - PreviewAutomationSnapshot, - "url" | "title" | "loading" | "visibleText" | "interactiveElements" - > - >, - captureViewport(input.cdp, { format: "png" }).then(async (full) => - scale < 1 - ? { - data: await shrinkPng(input.cdp, full, scale), - full: input.fullScreenshot ? full : undefined, - } - : { data: full, full: undefined }, + track( + "page state", + () => + input.page.evaluate(SNAPSHOT_SCRIPT) as Promise< + Pick< + PreviewAutomationSnapshot, + "url" | "title" | "loading" | "visibleText" | "interactiveElements" + > + >, + ), + // A cheap real frame still sizes the screenshot; computing it from metrics drifted from the PNG. + track("screenshot", () => + metadataOnly + ? captureViewport(input.cdp, { format: "jpeg", quality: 10 }).then((data) => ({ + data, + full: undefined, + })) + : captureViewport(input.cdp, { format: "png" }).then(async (full) => + scale < 1 + ? { + data: await shrinkPng(input.cdp, full, scale), + full: input.fullScreenshot ? full : undefined, + } + : { data: full, full: undefined }, + ), ), ]); void pageAndScreenshot.catch(constVoid); // Leaves time for the second read; a frame that never loads holds the tree until then. - const tree = await input.page.ariaSnapshot({ - mode: "ai", - boxes: true, - timeout: Math.max(1, deadline - Date.now() - 2_000), - }); - const after = await read(before); + const tree = await track("accessibility tree", () => + input.page.ariaSnapshot({ + mode: "ai", + boxes: true, + timeout: Math.max(1, deadline - Date.now() - 2_000), + }), + ); + const after = await track("frames", () => read(before)); // A value that changed meanwhile may be in the tree under neither reading. if (after.some((values, i) => values && JSON.stringify(values) !== JSON.stringify(before[i]))) throw pageChanged(); @@ -588,11 +740,13 @@ const capture = async ( const unread = readers.flatMap((reader, i) => (after[i] ? [] : reader.frames)); const filled = /^\s*- iframe (?:\[active\] )?\[ref=(\S+?)\].*:$/gm; for (const [, ref] of unread.length ? tree.matchAll(filled) : []) { - const iframe = await input.page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 2_000 }); + const iframe = await track("frames", () => + input.page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 2_000 }), + ); if (!iframe) throw pageChanged(); - const frame = await iframe.contentFrame(); + const frame = await track("frames", () => iframe.contentFrame()); void iframe.dispose().catch(constVoid); - if (frame && unread.includes(frame)) throw tooBusy(); + if (frame && unread.includes(frame)) throw frameUnanswered(); } const [page, { full, data }] = await pageAndScreenshot; if (state.generation !== generation) throw pageChanged(); @@ -616,11 +770,10 @@ const capture = async ( consoleEntries: [...input.consoleEntries], networkEntries: [...input.networkEntries], actionTimeline: [...input.actionTimeline], - screenshot: { - mimeType: "image/png", - data, - ...pngSize(data), - }, + // Reports the size the PNG path would have shrunk to. + screenshot: metadataOnly + ? scaledSize(jpegSize(data), scale) + : { mimeType: "image/png" as const, data, ...pngSize(data) }, ...(full !== undefined ? { fullScreenshot: { data: full, ...pngSize(full) } } : {}), }; }; @@ -628,41 +781,50 @@ const capture = async ( /** Snapshots begun per page; observers' snapshots aren't queued, so two can overlap. */ const snapshotTurns = new WeakMap(); -export const snapshot = async (input: SnapshotInput): Promise => { +const runSnapshot = async (input: SnapshotInput, metadataOnly: boolean) => { const deadline = Date.now() + SNAPSHOT_TIMEOUT_MS; + const stages: SnapshotStages = { running: new Map(), timedOut: new Set() }; let timer: ReturnType | undefined; const expired = new Promise((_, reject) => { - timer = setTimeout(() => reject(tooBusy()), SNAPSHOT_TIMEOUT_MS); + timer = setTimeout(() => reject(snapshotTimedOut(stages)), SNAPSHOT_TIMEOUT_MS); }); const turn = (snapshotTurns.get(input.page) ?? 0) + 1; snapshotTurns.set(input.page, turn); // Retry only before the deadline and the next snapshot, whose refs a later retry would revoke. - const captured = capture(input, deadline).catch((cause: unknown) => + const captured = capture(input, deadline, stages, metadataOnly).catch((cause: unknown) => Date.now() < deadline && snapshotTurns.get(input.page) === turn && !(cause instanceof Error && cause.message === VALUE_TOO_LONG) - ? capture(input, deadline) + ? capture(input, deadline, stages, metadataOnly) : Promise.reject(cause), ); try { return await Promise.race([captured, expired]); } catch (cause) { - throw cause instanceof Error && cause.name === "TimeoutError" ? tooBusy() : cause; + throw isTimeout(cause) ? snapshotTimedOut(stages) : cause; } finally { clearTimeout(timer); } }; +export const snapshot = (input: SnapshotInput) => + runSnapshot(input, false) as Promise; + +export const snapshotMetadata = (input: SnapshotInput) => + runSnapshot(input, true) as Promise; + /** Return when a dialog opens; waiting for the action to finish would block until dialog resolution. */ export const click = async ( page: Page, input: PreviewAutomationClickInput, pointer: PointerReporter = noPointer, ): Promise<{ readonly x: number; readonly y: number }> => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + // One deadline across steps keeps the reply inside the broker's grace; Playwright reads 0 as none. + const deadline = Date.now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS); + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); try { - return await clickTarget(page, locator, input, timeout, pointer); + return await clickTarget(page, locator, input, remaining, pointer); } catch (cause) { throw locator === null ? cause : await namedTargetTimeout(locator, input, cause); } @@ -698,10 +860,11 @@ const namedTargetTimeout = async ( : matches === 0 ? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.` : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`; + const message = withActionabilityReason(reason, cause); return new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: reason, - detail: { reason }, + message, + detail: { reason: message }, cause, }); }; @@ -710,7 +873,7 @@ const clickTarget = async ( page: Page, locator: Locator | null, input: PreviewAutomationClickInput, - timeout: number, + timeout: () => number, pointer: PointerReporter, ) => { const point = await targetPoint(page, locator, input, timeout); @@ -719,7 +882,7 @@ const clickTarget = async ( const clicked = locator === null ? page.mouse.click(point.x, point.y, options) - : locator.click({ ...options, timeout }); + : locator.click({ ...options, timeout: timeout() }); let onDialog = constVoid; const dialogOpened = new Promise<"dialog">((resolve) => { onDialog = () => resolve("dialog"); @@ -733,6 +896,76 @@ const clickTarget = async ( return point; }; +type FocusCandidate = { + readonly tagName: string; + readonly type?: string; + readonly disabled?: boolean; + readonly readOnly?: boolean; + readonly isContentEditable?: boolean; + readonly shadowRoot?: { readonly activeElement: FocusCandidate | null } | null; + readonly focus?: () => void; + getRootNode(): { readonly activeElement?: FocusCandidate | null }; + contains(other: FocusCandidate): boolean; +}; + +// Serialized into the page's main world, so it must not reference module scope. +const focusTextTarget = (target: FocusCandidate | null) => { + let element = + target ?? + (globalThis as unknown as { document: { activeElement: FocusCandidate | null } }).document + .activeElement; + if (target === null) { + while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement; + // Focus inside a frame cannot be checked from here, and an editable frame would pass as contentEditable. + if (element && ["IFRAME", "FRAME", "FENCEDFRAME", "OBJECT", "EMBED"].includes(element.tagName)) + return false; + } + if (element == null) return false; + // Require an enabled, focused text target to avoid losing input or sending it to the previous field. + const nonText = [ + "button", + "checkbox", + "color", + "file", + "hidden", + "image", + "radio", + "range", + "reset", + "submit", + ]; + const textControl = + element.tagName === "TEXTAREA" || + (element.tagName === "INPUT" && !nonText.includes(element.type ?? "text")); + if (!(textControl || element.isContentEditable) || element.disabled || element.readOnly) { + return false; + } + element.focus?.(); + const active = element.getRootNode().activeElement; + return active != null && (active === element || element.contains(active)); +}; + +// A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. +const focusedTextField = async (page: Page, timeout: number) => { + let timer: ReturnType | undefined; + const expired = new Promise((_, reject) => { + timer = setTimeout( + () => + reject( + new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: `The page did not report its focused element within ${timeout}ms, so no text was typed.`, + detail: { timeoutMs: timeout }, + }), + ), + timeout, + ); + }); + return await Promise.race([page.evaluate(focusTextTarget, null), expired]).finally(() => + clearTimeout(timer), + ); +}; + export const type = async (page: Page, input: PreviewAutomationTypeInput) => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); @@ -740,46 +973,10 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => { await locator.fill(input.text, { timeout }); return; } - // A shadow host also matches :focus; use its innermost focused descendant. - const target = locator ?? page.locator("*:focus").last(); const focused = - (locator !== null || (await target.count()) > 0) && - (await target.evaluate( - (element) => { - // Require an enabled, focused text target to avoid losing input or sending it to the previous field. - const control = element as unknown as { - readonly type?: string; - readonly disabled?: boolean; - readonly readOnly?: boolean; - readonly isContentEditable?: boolean; - readonly focus?: () => void; - }; - const nonText = [ - "button", - "checkbox", - "color", - "file", - "hidden", - "image", - "radio", - "range", - "reset", - "submit", - ]; - const textControl = - element.tagName === "TEXTAREA" || - (element.tagName === "INPUT" && !nonText.includes(control.type ?? "text")); - if (!(textControl || control.isContentEditable) || control.disabled || control.readOnly) { - return false; - } - control.focus?.(); - const root = element.getRootNode() as { readonly activeElement?: typeof element | null }; - const active = root.activeElement; - return active != null && (active === element || element.contains(active)); - }, - undefined, - { timeout }, - )); + locator === null + ? await focusedTextField(page, timeout) + : await locator.evaluate(focusTextTarget, undefined, { timeout }); if (focused !== true) { throw new ServerBrowserOperationError({ tag: "PreviewAutomationTargetNotEditableError", @@ -798,14 +995,15 @@ export const hover = async ( input: PreviewAutomationHoverInput, pointer: PointerReporter = noPointer, ) => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const deadline = Date.now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS); + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); - await pointer(await targetPoint(page, locator, input, timeout), "move"); + await pointer(await targetPoint(page, locator, input, remaining), "move"); if (locator === null) { await page.mouse.move(input.x ?? 0, input.y ?? 0); return; } - await locator.hover({ timeout }); + await locator.hover({ timeout: remaining() }); }; export const select = async ( @@ -848,16 +1046,18 @@ export const drag = async ( input: PreviewAutomationDragInput, pointer: PointerReporter = noPointer, ) => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const deadline = Date.now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS); + const remaining = () => Math.max(1, deadline - Date.now()); const source = targetLocator(page, { locator: input.source })!; const target = targetLocator(page, { locator: input.target })!; - await pointer(await targetPoint(page, source, {}, timeout), "move"); + await pointer(await targetPoint(page, source, {}, remaining), "move"); // Observe drag rejection immediately; an unhandled rejection during cursor movement exits the server. - const dragFailure = source.dragTo(target, { timeout }).then( + // Chromium delivers a single move before dragstart; steps give the page mousemoves during the drag. + const dragFailure = source.dragTo(target, { timeout: remaining(), steps: 5 }).then( () => null, (error: unknown) => ({ error }), ); - const end = await target.boundingBox({ timeout }).catch(() => null); + const end = await target.boundingBox({ timeout: remaining() }).catch(() => null); if (end) await pointer({ x: end.x + end.width / 2, y: end.y + end.height / 2 }, "move"); const failure = await dragFailure; if (failure) throw failure.error; @@ -885,6 +1085,26 @@ export const scroll = async (page: Page, input: PreviewAutomationScrollInput) => await locator.evaluate((element, [x, y]) => element.scrollBy(x, y), delta); }; +const UNRESPONSIVE_SCRIPT_PROBE_MS = 1_000; + +/** + * A same-site navigation reuses the renderer, so it never commits while a page script holds it. + * Call before starting the navigation: Chrome does not deliver a terminate once one is pending. + */ +export const stopUnresponsiveScript = async (cdp: CDPSession, budgetMs = Infinity) => { + let timer: ReturnType | undefined; + const answered = cdp.send("Runtime.evaluate", { expression: "0" }).then( + () => true, + () => true, + ); + const expired = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), Math.min(budgetMs, UNRESPONSIVE_SCRIPT_PROBE_MS)); + }); + const responsive = await Promise.race([answered, expired]).finally(() => clearTimeout(timer)); + // Not awaited: a renderer blocked on something other than script may never acknowledge it. + if (!responsive) void cdp.send("Runtime.terminateExecution").catch(constVoid); +}; + /** Terminate expired page scripts so a hung expression cannot block the tab's control queue. */ export const evaluate = async ( cdp: CDPSession, @@ -909,7 +1129,7 @@ export const evaluate = async ( const params = { expression: input.expression, awaitPromise: input.awaitPromise ?? true, - returnByValue: input.returnByValue ?? true, + returnByValue: true, }; // The devtools console's replMode allows top-level await but returns a trailing promise unawaited, // so it only retries what the page's parser rejected. A parse error has a scriptId but no stack and @@ -947,7 +1167,6 @@ export const evaluate = async ( export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) => { const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; - const deadline = Date.now() + timeoutMs; const locator = targetLocator(page, input); const { text, urlIncludes } = input; const checks: Array<() => Promise> = []; @@ -962,16 +1181,28 @@ export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) ); } if (urlIncludes !== undefined) checks.push(async () => page.url().includes(urlIncludes)); - for (;;) { - const results = await Promise.all(checks.map((check) => check())); - if (results.every(Boolean)) return; - if (Date.now() >= deadline) { - throw new ServerBrowserOperationError({ - tag: "PreviewAutomationTimeoutError", - message: `Waited ${timeoutMs}ms without every condition holding.`, - }); + // `count()` and `evaluate()` take no timeout; a stalled check would hold the tab's control queue. + let timer: ReturnType | undefined; + const expired = new Promise((_, reject) => { + timer = setTimeout( + () => + reject( + new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: `Waited ${timeoutMs}ms without every condition holding.`, + }), + ), + timeoutMs, + ); + }); + try { + for (;;) { + const results = await Promise.race([Promise.all(checks.map((check) => check())), expired]); + if (results.every(Boolean)) return; + await Promise.race([new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS)), expired]); } - await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS)); + } finally { + clearTimeout(timer); } }; @@ -1056,7 +1287,8 @@ export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => window.__t3Recorder = { async frame(base64, cssWidth) { if (tooLarge) return false; - const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)); + // A per-character atob copy costs ~30 ms on a 3200x1800 frame and throttles recordings. + const bytes = Uint8Array.fromBase64(base64); const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" })); if (tooLarge) { bitmap.close(); return false; } if (!recorder) { @@ -1138,11 +1370,18 @@ export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => }, async chunk(index) { const bytes = new Uint8Array(await chunks[index].arrayBuffer()); + if (typeof bytes.toBase64 === "function") return bytes.toBase64(); let binary = ""; for (let offset = 0; offset < bytes.length; offset += 0x8000) { binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); } return btoa(binary); }, + download() { + const link = document.createElement("a"); + link.href = URL.createObjectURL(new Blob(chunks, { type: recorder.mimeType })); + link.download = "recording"; + link.click(); + }, }; })()`; diff --git a/apps/server/src/preview/ServerBrowserStream.test.ts b/apps/server/src/preview/ServerBrowserStream.test.ts index c4a709ed8a..c0a9fbc923 100644 --- a/apps/server/src/preview/ServerBrowserStream.test.ts +++ b/apps/server/src/preview/ServerBrowserStream.test.ts @@ -57,6 +57,7 @@ const mutations = [ { type: "navigate", url: "https://example.com" }, { type: "history", delta: -1 }, { type: "reload" }, + { type: "stopLoading" }, { type: "probe", x: 10, y: 10 }, { type: "takeControl" }, { type: "releaseControl" }, @@ -149,7 +150,7 @@ it.effect.each([ }, ]); expect(auth.requests).toEqual([resource]); - }).pipe(Effect.scoped), + }), ); it.effect("sends replies ahead of stale frames and only the newest frame after an ack", () => @@ -221,7 +222,7 @@ it.effect("sends replies ahead of stale frames and only the newest frame after a yield* Effect.promise(() => next.promise); expect(received).toEqual([1, "probe", 4]); expect(released).toEqual([2, 3, 1]); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -264,7 +265,7 @@ it.effect.each([ ); expect(response.status).toBe(testCase.status); expect(attachments).toBe(0); - }).pipe(Effect.scoped), + }), ); it.effect("serves a tab's download only to an authorized session", () => @@ -369,7 +370,7 @@ it.effect("passes uploaded files to the page's open picker and needs operate sco { chooserId: "chooser-1", files: [{ name: "notes.txt", text: "hello" }] }, ]); expect((yield* upload([AuthPreviewOperateScope], "stale")).status).toBe(409); - }).pipe(Effect.scoped), + }), ); const decodeHostSetup = Schema.decodeUnknownEffect(Schema.fromJsonString(PreviewStreamHostSetup)); @@ -430,5 +431,5 @@ it.effect.each([ need, command: "sudo t3 browser setup", }); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/process/NonBlockingSpawner.test.ts b/apps/server/src/process/NonBlockingSpawner.test.ts new file mode 100644 index 0000000000..81563cbab7 --- /dev/null +++ b/apps/server/src/process/NonBlockingSpawner.test.ts @@ -0,0 +1,200 @@ +// @effect-diagnostics nodeBuiltinImport:off - the spawner's checks are node:fs/promises calls, which the test spies on. +import * as NodeFSP from "node:fs/promises"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as NonBlockingSpawner from "./NonBlockingSpawner.ts"; + +vi.mock("node:fs/promises", { spy: true }); + +const hostPath = process.env.PATH; + +const wrapped = NonBlockingSpawner.layer.pipe(Layer.provideMerge(NodeServices.layer)); + +/** What a caller sees of a command: its output, or the error of a spawn that failed. */ +const outcome = (command: ChildProcess.Command) => + ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.string(command)).pipe( + Effect.match({ + onSuccess: (output) => ({ output }), + onFailure: (error) => ({ reason: error.reason._tag, message: error.message }), + }), + ); + +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("NonBlockingSpawner", () => { + it.live("gives callers what the native spawner gives them", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped()); + for (const [file, mode] of [ + ["stale/tool", 0o644], + ["fresh/tool", 0o755], + ["target/bin/tool", 0o755], + // GNU env reads a lone `-` as -i and `NAME=value` as an assignment, even after `--`. + ["fresh/-", 0o755], + ["fresh/launch=stable", 0o755], + ] as const) { + yield* fileSystem.makeDirectory(`${root}/${file.slice(0, file.lastIndexOf("/"))}`, { + recursive: true, + }); + yield* fileSystem.writeFileString(`${root}/${file}`, `#!/bin/sh\necho ${file} "$@"\n`); + yield* fileSystem.chmod(`${root}/${file}`, mode); + } + yield* fileSystem.makeDirectory(`${root}/target/subdir`); + yield* fileSystem.symlink(`${root}/target/subdir`, `${root}/link`); + const PATH = `${root}/stale:${root}/fresh`; + + const commands = { + "enters the cwd": ChildProcess.make("pwd", ["-P"], { cwd: root }), + "keeps argv": ChildProcess.make( + "printf", + ["%s\\n", "-n", "--", "a b", `it's "quoted"`, "$HOME", "; exit 3", "", "A=b"], + { cwd: root }, + ), + // dash would drop the exported function and add PWD and OLDPWD. + "keeps the environment": ChildProcess.make("env", [], { + cwd: root, + env: { PATH: hostPath, A: "1", "BASH_FUNC_x%%": "() { echo exported\n}" }, + }), + "skips a non-executable PATH entry": ChildProcess.make("tool", [], { env: { PATH } }), + "resolves `..` in PATH after a symlink": ChildProcess.make("tool", [], { + env: { PATH: `${root}/link/../bin` }, + }), + "searches PATH relative to the cwd": ChildProcess.make("tool", [], { + cwd: root, + env: { PATH: "fresh" }, + }), + "a command named -": ChildProcess.make("-", [], { cwd: root, env: { PATH } }), + "a command containing =": ChildProcess.make("launch=stable", [], { env: { PATH } }), + "shell mode": ChildProcess.make('pwd -P; echo "$0" "a b"', [], { cwd: root, shell: true }), + "a pipeline": ChildProcess.make("printf", ["a\\nb\\n"], { cwd: root }).pipe( + ChildProcess.pipeTo(ChildProcess.make("tail", ["-n", "1"])), + ), + "a missing command": ChildProcess.make("t3code-missing-command", ["--version"]), + "a missing command in a cwd": ChildProcess.make("t3code-missing-command", [], { + cwd: root, + }), + "a non-executable command": ChildProcess.make("tool", [], { + env: { PATH: `${root}/stale` }, + }), + "a missing explicit path": ChildProcess.make("./missing", [], { cwd: root }), + "a non-executable explicit path": ChildProcess.make(`${root}/stale/tool`, []), + "a missing cwd": ChildProcess.make("true", [], { cwd: `${root}/missing` }), + // The native check sees `missing`, although the path resolves to an existing directory. + "a cwd through a missing directory": ChildProcess.make("true", [], { + cwd: `${root}/missing/..`, + }), + }; + for (const [name, command] of Object.entries(commands)) { + const native = yield* outcome(command).pipe(Effect.provide(NodeServices.layer)); + expect(yield* outcome(command).pipe(Effect.provide(wrapped)), name).toEqual(native); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live("hands the native spawner only `env`, never a cwd or a command to look up", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped(); + const received: Array = []; + const record = (command: ChildProcess.Command): void => { + if (command._tag === "StandardCommand") received.push(command); + else [command.left, command.right].forEach(record); + }; + const recording = Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.map(ChildProcessSpawner.ChildProcessSpawner, (native) => + ChildProcessSpawner.make((command) => { + record(command); + return native.spawn(command); + }), + ), + ).pipe(Layer.provideMerge(NodeServices.layer)); + const commands = [ + ChildProcess.make("true", [], { cwd: directory }), + ChildProcess.make("true", []), + ChildProcess.make("/bin/true", []), + ChildProcess.make("t3code-missing-command", []), + ChildProcess.make("true", [], { cwd: directory, shell: true }), + ChildProcess.make("printf", ["a"], { cwd: directory }).pipe( + ChildProcess.pipeTo(ChildProcess.make("cat", [], { cwd: directory })), + ), + ]; + yield* Effect.forEach(commands, (command) => + ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.exitCode(command)).pipe( + Effect.exit, + ), + ).pipe(Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provide(recording)))); + + expect(received.map((command) => [command.command, command.options.cwd])).toEqual( + Array.from({ length: 6 }, () => ["/usr/bin/env", undefined]), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live("checks at most two paths at once, however many directories hang", () => + Effect.gen(function* () { + const allArrived = yield* Deferred.make(); + let arrivals = 0; + // Each spawn resolves its cwd, then starts its check within microtasks. + const arrivalPath = Layer.effect( + Path.Path, + Effect.map(Path.Path, (path) => ({ + ...path, + resolve: (...segments: ReadonlyArray) => { + if (++arrivals === 3) setImmediate(() => Deferred.doneUnsafe(allArrived, Effect.void)); + return path.resolve(...segments); + }, + })), + ); + const hung: Array<() => void> = []; + let releasing = false; + let running = 0; + let mostRunning = 0; + using _access = vi.spyOn(NodeFSP, "access").mockImplementation( + () => + new Promise((_resolve, reject) => { + mostRunning = Math.max(mostRunning, ++running); + const fail = () => { + running--; + reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" })); + }; + if (releasing) fail(); + else hung.push(fail); + }), + ); + const spawns = yield* Effect.forEach( + ["a", "b", "c"], + (name) => + ChildProcessSpawner.ChildProcessSpawner.use((spawner) => + spawner.exitCode(ChildProcess.make("true", [], { cwd: `/t3code-hung/${name}` })), + ).pipe(Effect.flip), + { concurrency: "unbounded" }, + ).pipe( + Effect.provide( + NonBlockingSpawner.layer.pipe( + Layer.provide(arrivalPath), + Layer.provide(NodeServices.layer), + ), + ), + Effect.forkChild, + ); + yield* Deferred.await(allArrived); + expect(mostRunning).toBe(2); + releasing = true; + for (const fail of hung.splice(0)) fail(); + yield* Fiber.join(spawns); + expect(mostRunning).toBe(2); + }), + ); +}); diff --git a/apps/server/src/process/NonBlockingSpawner.ts b/apps/server/src/process/NonBlockingSpawner.ts new file mode 100644 index 0000000000..0807b287cb --- /dev/null +++ b/apps/server/src/process/NonBlockingSpawner.ts @@ -0,0 +1,178 @@ +// @effect-diagnostics nodeBuiltinImport:off - execvp's X_OK test has no Effect FileSystem equivalent. +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; + +import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Redacted from "effect/Redacted"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as CommandLine from "effect/process/CommandLine"; + +// libuv's _PATH_DEFPATH, searched when the child environment has no PATH. +const DEFAULT_PATH = "/usr/bin:/bin"; + +// A check on a hung mount holds a libuv threadpool thread until the mount answers, and the +// pool's four threads also compress every WebSocket frame. Checks therefore run one at a time +// per directory and two at a time overall; the rest wait without holding a thread. +const CHECK_LIMIT = 2; +const directoryTails = new Map>(); +const waiting: Array<() => void> = []; +let running = 0; + +const access = async (path: string, mode: number) => { + if (running < CHECK_LIMIT) running++; + else await new Promise((resume) => waiting.push(resume)); + try { + await NodeFSP.access(path, mode); + return undefined; + } catch (error) { + return error as NodeJS.ErrnoException; + } finally { + // A waiter takes over the slot. + const next = waiting.shift(); + if (next === undefined) running--; + else next(); + } +}; + +/** The errno error of `access(path, mode)`, or undefined when it passes. */ +const check = (directory: string, path: string, mode: number) => { + const result = (directoryTails.get(directory) ?? Promise.resolve()).then(() => + access(path, mode), + ); + directoryTails.set(directory, result); + void result.then(() => { + if (directoryTails.get(directory) === result) directoryTails.delete(directory); + }); + return Effect.promise(() => result); +}; + +// The PATH the child searches, from the environment Effect's Node spawner gives it. +const childPath = ({ env, extendEnv }: ChildProcess.CommandOptions) => { + if (env === undefined) return process.env.PATH; + if (!Object.hasOwn(env, "PATH")) return extendEnv === true ? process.env.PATH : undefined; + const value = env.PATH; + return value === undefined || !Redacted.isRedacted(value) ? value : Redacted.value(value); +}; + +// The spawn error Effect's Node spawner reports when execvp fails with `code`. +const spawnFailure = (command: ChildProcess.StandardCommand, code: "ENOENT" | "EACCES") => { + const syscall = `spawn ${command.command}`; + return PlatformError.systemError({ + _tag: code === "ENOENT" ? "NotFound" : "PermissionDenied", + module: "ChildProcess", + method: "spawn", + pathOrDescriptor: CommandLine.display([command.command, ...command.args], { format: "posix" }), + syscall, + cause: Object.assign(new Error(`${syscall} ${code}`), { + errno: code === "ENOENT" ? -2 : -13, + code, + syscall, + path: command.command, + spawnargs: command.args.map((arg) => (Redacted.isRedacted(arg) ? "" : arg)), + }), + }); +}; + +// The error of the `FileSystem.access(cwd)` Effect's Node spawner runs before it spawns. +const cwdFailure = (cwd: string, cause: NodeJS.ErrnoException) => + PlatformError.systemError({ + _tag: + cause.code === "ENOENT" + ? "NotFound" + : cause.code === "EACCES" || cause.code === "EPERM" + ? "PermissionDenied" + : cause.code === "ENOTDIR" || cause.code === "ELOOP" + ? "BadResource" + : "Unknown", + module: "FileSystem", + method: "access", + pathOrDescriptor: cwd, + syscall: cause.syscall, + cause, + }); + +/** + * Fails as a native spawn does when the command is missing or not executable: callers read + * that error to tell a CLI that is not installed from one that failed. execvp reports EACCES + * when a candidate exists but cannot be run, and ENOENT otherwise. + */ +const findExecutable = Effect.fnUntraced(function* ( + command: ChildProcess.StandardCommand, + cwd: string | undefined, +) { + // Joined as text: the kernel resolves `..` after a symlink differently from a normalized path. + const fromCwd = (path: string) => + cwd === undefined || path.startsWith("/") ? path : `${cwd}/${path}`; + const candidates = command.command.includes("/") + ? [fromCwd(command.command)] + : (childPath(command.options) ?? DEFAULT_PATH) + .split(":") + .map((entry) => `${fromCwd(entry || ".")}/${command.command}`); + let denied = false; + for (const candidate of candidates) { + const error = yield* check( + candidate.slice(0, candidate.lastIndexOf("/")) || "/", + candidate, + NodeFS.constants.X_OK, + ); + // Any other errno is left for `env` to report through its exit code. + if (error === undefined || (error.code !== "ENOENT" && error.code !== "EACCES")) return; + denied ||= error.code === "EACCES"; + } + return yield* spawnFailure(command, denied ? "EACCES" : "ENOENT"); +}); + +const make = Effect.gen(function* () { + const native = yield* ChildProcessSpawner.ChildProcessSpawner; + if ((yield* HostProcess.Platform) !== "linux") return native; + if (!(yield* Effect.promise(supportsEnvChdir))) return native; + const path = yield* Path.Path; + + // Runs inside the NonBlockingSpawner.spawn span. + const prepareStandard = Effect.fnUntraced(function* (input: ChildProcess.StandardCommand) { + const { cwd: givenCwd, shell, ...options } = input.options; + // Effect rejects a shell command with arguments, and a NUL, itself. + if ((shell && input.args.length > 0) || input.command.includes("\0")) return input; + // Node's shell mode on Unix, spelled out so the trampoline can run it. + const command = shell + ? ChildProcess.make(typeof shell === "string" ? shell : "/bin/sh", ["-c", input.command]) + : input; + // Checked as given and entered resolved, as Effect's Node spawner does. + const cwd = givenCwd === undefined ? undefined : path.resolve(givenCwd); + const trampoline = envTrampoline(command.command, command.args, cwd); + if (trampoline === undefined) return input; + if (givenCwd !== undefined && cwd !== undefined) { + const error = yield* check(cwd, givenCwd, NodeFS.constants.F_OK); + if (error !== undefined) return yield* cwdFailure(givenCwd, error); + } + yield* findExecutable(ChildProcess.make(command.command, command.args, options), cwd); + return ChildProcess.make(trampoline.command, trampoline.args, options); + }); + + const prepare = ( + command: ChildProcess.Command, + ): Effect.Effect => + command._tag === "StandardCommand" + ? prepareStandard(command) + : Effect.map(Effect.all([prepare(command.left), prepare(command.right)]), ([left, right]) => + ChildProcess.pipeTo(left, right, command.options), + ); + + return ChildProcessSpawner.make( + Effect.fn("NonBlockingSpawner.spawn")(function* (command) { + return yield* native.spawn(yield* prepare(command)); + }), + ); +}); + +/** + * On Linux with GNU `env`, replaces the provided `ChildProcessSpawner` with one that never + * hands libuv a cwd or a PATH search; elsewhere it passes the provided one through. + */ +export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make); diff --git a/apps/server/src/process/SpawnWorker.test.ts b/apps/server/src/process/SpawnWorker.test.ts new file mode 100644 index 0000000000..9c88d4f586 --- /dev/null +++ b/apps/server/src/process/SpawnWorker.test.ts @@ -0,0 +1,204 @@ +// @effect-diagnostics nodeBuiltinImport:off processEnvInEffect:off - fixtures need real paths, the process resource list and the live environment. +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Result from "effect/Result"; +import * as Stream from "effect/Stream"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import * as SpawnWorker from "./SpawnWorker.ts"; + +const envChdir = vi.hoisted(() => ({ supported: true })); +vi.mock("@t3tools/shared/envTrampoline", async (importOriginal) => ({ + ...(await importOriginal()), + supportsEnvChdir: () => Promise.resolve(envChdir.supported), +})); + +const layer = SpawnWorker.layer.pipe(Layer.provide(NodeServices.layer)); +const text = (stream: Stream.Stream) => + stream.pipe(Stream.decodeText(), Stream.mkString); +const node = (script: string, args: ReadonlyArray = [], options = {}) => + ChildProcess.make(process.execPath, ["-e", script, ...args], options); + +describe("SpawnWorker", () => { + it.live("runs children on a launcher thread where the server thread would wait on them", () => + Effect.gen(function* () { + for (const [platform, hasEnvChdir, onServerThread] of [ + ["win32", true, false], + ["linux", true, true], + ["linux", false, false], + ] as const) { + envChdir.supported = hasEnvChdir; + const launched = Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn( + node("process.stdout.write('ready');process.stdin.resume()"), + ); + expect(yield* child.stdout.pipe(Stream.take(1), text)).toBe("ready"); + // The thread that called spawn owns the native process handle. + expect(process.getActiveResourcesInfo().includes("ProcessWrap")).toBe(onServerThread); + expect(yield* child.isRunning).toBe(true); + }); + yield* launched.pipe( + Effect.scoped, + Effect.provide(SpawnWorker.layerServer.pipe(Layer.provide(NodeServices.layer))), + Effect.provideService(HostProcess.Platform, platform), + ); + } + }), + ); + + it.live("preserves stdin, large output, env, cwd, literal args and additional descriptors", () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const literal = "quote' \" $HOME; * & %PATH%"; + const cwd = NodeOS.tmpdir(); + const script = ` + const fs = require('node:fs'); + const input = fs.readFileSync(0, 'utf8'); + fs.writeSync(1, JSON.stringify([input, process.cwd(), process.env.SPAWN_WORKER_TEST, process.argv[1]]) + '\\n'); + fs.writeSync(1, 'a'.repeat(1024 * 1024)); + fs.writeSync(2, 'b'.repeat(1024 * 1024)); + `; + for (let i = 0; i < 3; i++) { + const child = yield* spawner.spawn( + node(script, [literal], { + cwd, + env: { SPAWN_WORKER_TEST: "inherited value" }, + extendEnv: true, + stdin: Stream.encodeText(Stream.make("stdin value")), + }), + ); + const [stdout, stderr, code] = yield* Effect.all( + [text(child.stdout), text(child.stderr), child.exitCode], + { concurrency: "unbounded" }, + ); + expect(stdout).toBe( + JSON.stringify(["stdin value", NodePath.resolve(cwd), "inherited value", literal]) + + "\n" + + "a".repeat(1024 * 1024), + ); + expect(stderr).toBe("b".repeat(1024 * 1024)); + expect(code).toBe(0); + } + // The launcher threads already exist, so this needs the server's environment at launch time. + process.env.SPAWN_WORKER_LATE = "set after start"; + const late = yield* spawner.spawn( + node("process.stdout.write(process.env.SPAWN_WORKER_LATE)"), + ); + expect(yield* text(late.stdout)).toBe("set after start"); + delete process.env.SPAWN_WORKER_LATE; + const extra = yield* spawner.spawn( + node("require('node:fs').writeSync(3, 'fd3 value')", [], { + additionalFds: { fd3: { type: "output" } }, + }), + ); + const [fd3, extraCode] = yield* Effect.all([text(extra.getOutputFd(3)), extra.exitCode], { + concurrency: "unbounded", + }); + expect(fd3).toBe("fd3 value"); + expect(extraCode).toBe(0); + const reader = yield* spawner.spawn( + node("process.stdin.on('end', () => process.stdout.write('eof')).resume()"), + ); + yield* Stream.fail("abandoned input").pipe(Stream.run(reader.stdin), Effect.ignore); + expect(yield* text(reader.stdout)).toBe("eof"); + const pipeline = node("process.stdout.write('piped')").pipe( + ChildProcess.pipeTo( + node("process.stdin.on('data', (d) => process.stdout.write(String(d).toUpperCase()))"), + ), + ); + const piped = yield* spawner.spawn(pipeline); + expect(yield* text(piped.stdout)).toBe("PIPED"); + expect(yield* piped.exitCode).toBe(0); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + + it.live("reports launch errors and exit codes, and keeps launching after either", () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const missing = yield* spawner + .spawn(ChildProcess.make("t3-missing-command-25245")) + .pipe(Effect.result); + expect(Result.isFailure(missing)).toBe(true); + if (Result.isFailure(missing)) expect(missing.failure.reason._tag).toBe("NotFound"); + const failed = yield* spawner.spawn(node("process.exit(23)")); + expect(yield* failed.exitCode).toBe(23); + const healthy = yield* spawner.spawn(node("process.stdout.write('ok')")); + expect(yield* text(healthy.stdout)).toBe("ok"); + expect(yield* healthy.exitCode).toBe(0); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + + it.live("a short child's output ends while a sibling launched beside it still runs", () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const untilStdin = + "process.stdout.write('ready');process.stdin.once('data',()=>process.exit(0))"; + // Workers that own a child stay alive, as beside a running agent, so each round's two + // launches land on two warm workers at once. + yield* Effect.all( + Array.from({ length: 4 }, () => + Effect.gen(function* () { + const holder = yield* spawner.spawn(node(untilStdin)); + expect(yield* holder.stdout.pipe(Stream.take(1), text)).toBe("ready"); + }), + ), + { concurrency: "unbounded" }, + ); + for (let round = 0; round < 20; round++) { + const [sibling, output] = yield* Effect.all( + [ + spawner.spawn(node(untilStdin, [], { stdin: { stream: Stream.never } })), + spawner + .spawn(node("process.stdout.write('ok')")) + .pipe(Effect.flatMap((child) => text(child.stdout))), + ], + { concurrency: "unbounded" }, + ); + expect(output).toBe("ok"); + expect(yield* sibling.isRunning).toBe(true); + } + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + + it.live("kills running commands, detached or not, and on scope interruption", () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + for (const detached of [true, false]) { + const child = yield* spawner.spawn( + node("process.stdout.write(String(process.pid));process.stdin.resume()", [], { + detached, + }), + ); + const pid = yield* child.stdout.pipe(Stream.take(1), text); + expect(Number(pid)).toBe(child.pid); + yield* child.kill(); + expect(yield* child.isRunning).toBe(false); + } + const started = yield* Deferred.make(); + const running = yield* Effect.gen(function* () { + const scoped = yield* spawner.spawn(node("process.stdin.resume()")); + yield* Deferred.succeed(started, scoped); + return yield* Effect.never; + }).pipe(Effect.scoped, Effect.forkChild); + const scoped = yield* Deferred.await(started); + yield* Fiber.interrupt(running); + expect(yield* scoped.isRunning).toBe(false); + // Direct callers such as the Claude adapter pass an AbortSignal, which cannot cross to a worker. + const direct = SpawnWorker.spawnPiped(process.execPath, ["-e", "process.stdin.resume()"], { + signal: AbortSignal.abort(), + }); + const exited = new Promise((resolve) => direct.once("exit", () => resolve(direct.killed))); + expect(yield* Effect.promise(() => exited)).toBe(true); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); +}); diff --git a/apps/server/src/process/SpawnWorker.ts b/apps/server/src/process/SpawnWorker.ts new file mode 100644 index 0000000000..5a391ab18c --- /dev/null +++ b/apps/server/src/process/SpawnWorker.ts @@ -0,0 +1,569 @@ +// @effect-diagnostics nodeBuiltinImport:off - worker threads and Node streams implement the platform spawner boundary. +import * as NodeEvents from "node:events"; +import type * as NodeChildProcess from "node:child_process"; +import * as NodeStream from "node:stream"; +import * as NodeWorkerThreads from "node:worker_threads"; +import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { supportsEnvChdir } from "@t3tools/shared/envTrampoline"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +// Windows runs CreateProcess synchronously on the calling thread, and antivirus or a busy disk can +// hold it for seconds; Linux's spawn waits for chdir and the PATH search, which a hung mount +// stalls. Workers own the children, so only the worker waits. +const MAX_WORKERS = 4; +const MAX_IDLE_WORKERS = 1; + +type ToWorker = + | { + readonly type: "spawn"; + readonly id: number; + readonly command: string; + readonly args: ReadonlyArray; + readonly options: NodeChildProcess.SpawnOptions; + } + | { readonly type: "write"; readonly id: number; readonly fd: number; readonly data: Uint8Array } + | { readonly type: "end"; readonly id: number; readonly fd: number } + | { readonly type: "flow"; readonly id: number; readonly fd: number; readonly paused: boolean } + | { readonly type: "destroy"; readonly id: number; readonly fd: number } + | { readonly type: "kill"; readonly id: number; readonly signal: NodeJS.Signals | number }; + +interface SerializedError { + readonly message: string; + readonly [key: string]: unknown; +} + +type FromWorker = + | { readonly type: "spawn"; readonly id: number; readonly pid: number | undefined } + | { readonly type: "error"; readonly id: number; readonly error: SerializedError } + | { readonly type: "data"; readonly id: number; readonly fd: number; readonly data: Uint8Array } + | { + readonly type: "written"; + readonly id: number; + readonly fd: number; + readonly error?: SerializedError; + } + | { readonly type: "eof"; readonly id: number; readonly fd: number } + | { readonly type: "finished"; readonly id: number; readonly fd: number } + | { + readonly type: "stream-error"; + readonly id: number; + readonly fd: number; + readonly error: SerializedError; + } + | { + readonly type: "exit"; + readonly id: number; + readonly code: number | null; + readonly signal: NodeJS.Signals | null; + } + | { readonly type: "close"; readonly id: number }; + +// Windows makes a child's stdio pipes inheritable for the length of its CreateProcess, so a child +// another worker launches meanwhile inherits them and holds the first child's output open. Every +// pool's workers take this lock around spawn(); it holds the owning worker's threadId. +const windowsSpawnLock = new Int32Array(new SharedArrayBuffer(4)); + +// Inline source runs from bundles, asar archives and single-executable builds without module files. +const workerSource = ` +const { parentPort, threadId, workerData } = require("node:worker_threads"); +const { spawn } = require("node:child_process"); +const { lock } = workerData; +const locked = (launch) => { + if (lock === undefined) return launch(); + // Wait on the owner compareExchange saw: an unlock after it changes the value, so no wakeup is lost. + for (let owner; (owner = Atomics.compareExchange(lock, 0, 0, threadId)) !== 0; ) Atomics.wait(lock, 0, owner); + try { + return launch(); + } finally { + Atomics.store(lock, 0, 0); + Atomics.notify(lock, 0, 1); + } +}; +const children = new Map(); +const post = (message, transfer) => parentPort.postMessage(message, transfer); +const serialize = (error) => { + const out = { message: String(error && error.message) }; + for (const key of ["code", "errno", "syscall", "path", "spawnargs"]) { + if (error && error[key] !== undefined) out[key] = error[key]; + } + return out; +}; +parentPort.on("message", (request) => { + const { id } = request; + if (request.type === "spawn") { + let child; + try { + child = locked(() => spawn(request.command, request.args, request.options)); + } catch (error) { + post({ type: "error", id, error: serialize(error) }); + return; + } + children.set(id, child); + child.on("spawn", () => post({ type: "spawn", id, pid: child.pid })); + child.on("error", (error) => post({ type: "error", id, error: serialize(error) })); + child.on("exit", (code, signal) => post({ type: "exit", id, code, signal })); + // Output can still arrive after exit; close follows the last of it. + child.on("close", () => { + children.delete(id); + post({ type: "close", id }); + }); + child.stdio?.forEach((stream, fd) => { + if (!stream) return; + stream.on("error", (error) => post({ type: "stream-error", id, fd, error: serialize(error) })); + if (fd === 0) return; + // Cloning a Buffer copies its whole backing store; copy the bytes once and transfer them. + stream.on("data", (chunk) => { + const data = new Uint8Array(chunk); + post({ type: "data", id, fd, data }, [data.buffer]); + }); + stream.on("end", () => post({ type: "eof", id, fd })); + }); + return; + } + const child = children.get(id); + if (child === undefined) { + if (request.type === "write") post({ type: "written", id, fd: request.fd, error: { message: "write after exit", code: "EPIPE" } }); + if (request.type === "end") post({ type: "finished", id, fd: request.fd }); + return; + } + const stream = child.stdio?.[request.fd]; + switch (request.type) { + case "write": + if (!stream || stream.destroyed) { + post({ type: "written", id, fd: request.fd, error: { message: "write after end", code: "EPIPE" } }); + return; + } + try { + stream.write(request.data, (error) => post({ type: "written", id, fd: request.fd, error: error ? serialize(error) : undefined })); + } catch (error) { + post({ type: "written", id, fd: request.fd, error: serialize(error) }); + } + return; + case "end": + if (!stream || stream.destroyed || stream.writableFinished) post({ type: "finished", id, fd: request.fd }); + else stream.end(() => post({ type: "finished", id, fd: request.fd })); + return; + case "flow": + if (request.paused) stream?.pause(); + else stream?.resume(); + return; + case "destroy": + stream?.destroy(); + return; + case "kill": + try { + child.kill(request.signal); + } catch {} + return; + } +}); +`; + +const toError = (serialized: SerializedError) => + Object.assign(new Error(serialized.message), serialized); + +const toBuffer = (data: Uint8Array) => Buffer.from(data.buffer, data.byteOffset, data.byteLength); + +class WorkerChild + extends NodeEvents.EventEmitter + implements NodeChildProcessSpawner.SpawnedChildProcess +{ + pid: number | undefined; + exitCode: number | null = null; + signalCode: NodeJS.Signals | null = null; + stdin: NodeStream.Writable | null = null; + stdout: NodeStream.Readable | null = null; + stderr: NodeStream.Readable | null = null; + readonly stdio: Array = []; + referenced = true; + killed = false; + spawned = false; + exited = false; + readonly #writes = new Map void>>(); + readonly #finals = new Map void>(); + readonly #paused = new Set(); + + readonly worker: SpawnWorker; + readonly id: number; + + constructor(worker: SpawnWorker, id: number, stdio: ReadonlyArray) { + super(); + this.worker = worker; + this.id = id; + stdio.forEach((option, fd) => { + if (option !== "pipe" && option !== "overlapped") return; + const stream = this.#relay(fd); + this.stdio[fd] = stream; + if (fd === 0) this.stdin = stream as NodeStream.Writable; + else if (fd === 1) this.stdout = stream as NodeStream.Readable; + else if (fd === 2) this.stderr = stream as NodeStream.Readable; + }); + } + + #relay(fd: number): NodeStream.Readable | NodeStream.Writable { + const read = () => { + if (this.#paused.delete(fd)) + this.worker.post({ type: "flow", id: this.id, fd, paused: false }); + }; + const write = ( + chunk: Buffer, + _encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ) => { + if (this.worker.closed) { + callback(Object.assign(new Error("write EPIPE"), { code: "EPIPE" })); + return; + } + const pending = this.#writes.get(fd) ?? []; + pending.push(callback); + this.#writes.set(fd, pending); + const data = new Uint8Array(chunk); + this.worker.post({ type: "write", id: this.id, fd, data }, [data.buffer]); + }; + const final = (callback: (error?: Error | null) => void) => { + this.#finals.set(fd, callback); + this.worker.post({ type: "end", id: this.id, fd }); + }; + // A caller that destroys its end closes the child pipe, as it would with a real pipe. + const destroy = (error: Error | null, callback: (error?: Error | null) => void) => { + if (!this.exited) this.worker.post({ type: "destroy", id: this.id, fd }); + callback(error); + }; + if (fd === 0) return new NodeStream.Writable({ write, final, destroy }); + if (fd <= 2) return new NodeStream.Readable({ read, destroy }); + return new NodeStream.Duplex({ read, write, final, destroy, allowHalfOpen: true }); + } + + onData(fd: number, data: Uint8Array): void { + const stream = this.stdio[fd]; + if (!stream || !("push" in stream)) return; + if (!stream.push(toBuffer(data)) && !this.#paused.has(fd)) { + this.#paused.add(fd); + this.worker.post({ type: "flow", id: this.id, fd, paused: true }); + } + } + + onEof(fd: number): void { + const stream = this.stdio[fd]; + if (stream && "push" in stream) stream.push(null); + } + + onFinished(fd: number): void { + const callback = this.#finals.get(fd); + this.#finals.delete(fd); + callback?.(); + } + + onWritten(fd: number, error: SerializedError | undefined): void { + const callback = this.#writes.get(fd)?.shift(); + callback?.(error === undefined ? null : toError(error)); + } + + onStreamError(fd: number, error: SerializedError): void { + this.stdio[fd]?.destroy(toError(error)); + } + + kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean { + if (this.exited) return false; + this.killed = true; + this.worker.post({ type: "kill", id: this.id, signal }); + return true; + } + + ref(): void { + this.referenced = true; + this.worker.syncRef(); + } + + unref(): void { + this.referenced = false; + this.worker.syncRef(); + } + + exit(code: number | null, signal: NodeJS.Signals | null): void { + if (this.exited) return; + this.exited = true; + this.exitCode = code; + this.signalCode = signal; + // Node destroys stdin on exit; the Effect sink may already have removed its error listener. + this.stdin?.on("error", () => {}); + this.stdin?.destroy(); + this.emit("exit", code, signal); + } + + /** The worker is gone: end output so readers finish, and let the exit report the kill. */ + abandon(): void { + // Not destroy(error): Effect leaves an unread stderr's pipe without an error listener. + for (const stream of this.stdio) { + if (stream && "push" in stream && !stream.readableEnded) stream.push(null); + else if (stream && !("push" in stream)) stream.destroy(); + } + } +} + +class SpawnWorker { + readonly worker: NodeWorkerThreads.Worker; + readonly children = new Map(); + readonly pool: SpawnWorkerPool; + /** Node sets `worker.threadId` to -1 once the thread exits, so keep the id the lock holds. */ + readonly threadId: number; + /** Launches sent but not yet answered; the worker is inside CreateProcess for one of them. */ + launching = 0; + closed = false; + + constructor(pool: SpawnWorkerPool) { + this.pool = pool; + this.worker = new NodeWorkerThreads.Worker(workerSource, { + eval: true, + workerData: { lock: pool.platform === "win32" ? windowsSpawnLock : undefined }, + }); + this.threadId = this.worker.threadId; + this.worker.on("message", (message: FromWorker) => this.onMessage(message)); + this.worker.on("error", (error) => this.fail(error)); + this.worker.on("exit", () => this.fail(new Error("The process launcher thread exited."))); + this.worker.unref(); + } + + post(message: ToWorker, transfer?: ReadonlyArray): void { + if (!this.closed) this.worker.postMessage(message, transfer); + } + + spawn( + id: number, + command: string, + args: ReadonlyArray, + options: NodeChildProcess.SpawnOptions, + ): WorkerChild { + const io = options.stdio; + const stdio = + typeof io === "string" || io === undefined ? [io ?? "pipe", io ?? "pipe", io ?? "pipe"] : io; + const child = new WorkerChild(this, id, stdio); + // An AbortSignal cannot cross to the worker, so this thread kills on abort as Node would. + const { signal, ...rest } = options; + if (signal !== undefined) { + const abort = () => child.kill(); + if (signal.aborted) queueMicrotask(abort); + else { + signal.addEventListener("abort", abort, { once: true }); + child.once("exit", () => signal.removeEventListener("abort", abort)); + } + } + this.children.set(id, child); + this.launching++; + this.syncRef(); + this.post({ + type: "spawn", + id, + command, + args: [...args], + // A worker's process.env is a copy from when it started; children get the server's current one. + options: { ...rest, stdio, env: rest.env ?? { ...process.env } }, + }); + return child; + } + + syncRef(): void { + if (this.closed) return; + const referenced = + this.launching > 0 || [...this.children.values()].some((child) => child.referenced); + if (referenced) this.worker.ref(); + else this.worker.unref(); + } + + onMessage(message: FromWorker): void { + const child = this.children.get(message.id); + if (child === undefined) return; + switch (message.type) { + case "spawn": + this.launching--; + child.spawned = true; + child.pid = message.pid; + child.emit("spawn"); + break; + case "error": + if (!child.spawned) { + this.launching--; + child.exited = true; + this.release(child); + } + child.emit("error", toError(message.error)); + break; + case "data": + child.onData(message.fd, message.data); + break; + case "written": + child.onWritten(message.fd, message.error); + break; + case "eof": + child.onEof(message.fd); + break; + case "finished": + child.onFinished(message.fd); + break; + case "stream-error": + child.onStreamError(message.fd, message.error); + break; + case "exit": + child.exit(message.code, message.signal); + break; + case "close": + child.emit("close", child.exitCode, child.signalCode); + this.release(child); + break; + } + } + + release(child: WorkerChild): void { + this.children.delete(child.id); + this.syncRef(); + this.pool.release(this); + } + + fail(error: Error): void { + if (this.closed) return; + this.close(); + for (const child of this.children.values()) { + if (child.exited) { + child.abandon(); + continue; + } + if (!child.spawned) { + child.exited = true; + child.emit("error", error); + continue; + } + // The worker owned the only handle, so try to end the whole tree before reporting the exit. + const finish = () => { + child.exit(null, "SIGKILL"); + child.abandon(); + }; + if (child.pid === undefined) finish(); + else this.pool.killTree(child.pid, finish); + } + this.children.clear(); + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.pool.workers.delete(this); + void this.worker.terminate().then(() => { + // The thread may have died holding the lock, or between its unlock and notify, or after + // a notify woke it: free the lock and wake every waiter so none sleeps on a free lock. + Atomics.compareExchange(windowsSpawnLock, 0, this.threadId, 0); + Atomics.notify(windowsSpawnLock, 0); + }); + } +} + +class SpawnWorkerPool { + readonly workers = new Set(); + readonly platform: NodeJS.Platform; + #nextId = 0; + + constructor(platform: NodeJS.Platform) { + this.platform = platform; + } + + readonly spawn = ( + command: string, + args: ReadonlyArray, + options: NodeChildProcess.SpawnOptions, + ) => { + const workers = [...this.workers]; + // A worker inside CreateProcess cannot start another launch until it returns. + const worker = + workers.find((candidate) => candidate.launching === 0) ?? + (workers.length < MAX_WORKERS + ? this.#add() + : workers.reduce((best, candidate) => + candidate.launching < best.launching ? candidate : best, + )); + return worker.spawn(++this.#nextId, command, args, options); + }; + + killTree(pid: number, done: () => void): void { + const killPid = () => { + try { + process.kill(pid, "SIGKILL"); + } catch {} + }; + if (this.platform !== "win32") { + killPid(); + done(); + return; + } + let settled = false; + const finish = (killed: boolean) => { + if (settled) return; + settled = true; + // As Effect's own kill does when taskkill fails, end at least the direct child. + if (!killed) killPid(); + done(); + }; + this.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { + stdio: "ignore", + windowsHide: true, + }) + .on("error", () => finish(false)) + .on("exit", (code) => finish(code === 0)); + } + + #add(): SpawnWorker { + const worker = new SpawnWorker(this); + this.workers.add(worker); + return worker; + } + + release(worker: SpawnWorker): void { + if (worker.children.size > 0 || worker.launching > 0) return; + const idle = [...this.workers].filter( + (candidate) => candidate.children.size === 0 && candidate.launching === 0, + ); + if (idle.length > MAX_IDLE_WORKERS) worker.close(); + } + + close(): void { + for (const worker of this.workers) worker.close(); + } +} + +let sharedPool: SpawnWorkerPool | undefined; + +/** A piped `child_process.spawn` for Windows launches outside Effect's spawner. */ +export const spawnPiped = ( + command: string, + args: ReadonlyArray, + options: Omit, +) => + (sharedPool ??= new SpawnWorkerPool("win32")).spawn(command, args, { + ...options, + stdio: ["pipe", "pipe", "pipe"], + }) as WorkerChild & { + readonly stdin: NodeStream.Writable; + readonly stdout: NodeStream.Readable; + readonly stderr: NodeStream.Readable; + }; + +export const layer = Layer.unwrap( + Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + const pool = yield* Effect.acquireRelease( + Effect.sync(() => new SpawnWorkerPool(platform)), + (pool) => Effect.sync(() => pool.close()), + ); + return NodeChildProcessSpawner.layerWithSpawn(pool.spawn); + }), +); + +/** Workers on Windows, and on Linux where `NonBlockingSpawner` has no GNU `env -C` to use. */ +export const layerServer = Layer.unwrap( + Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") return layer; + if (platform === "linux" && !(yield* Effect.promise(supportsEnvChdir))) return layer; + return NodeChildProcessSpawner.layer; + }), +); diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 0095146a30..49674354b2 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -12,12 +12,21 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { vi } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; import * as ProcessRunner from "../processRunner.ts"; +import * as ProviderProcesses from "./providerProcesses.ts"; import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts"; +const GiB = 1024 ** 3; +const memory = vi.hoisted(() => ({ total: 16 * 1024 ** 3 })); +vi.mock("node:os", async (importOriginal) => ({ + ...(await importOriginal()), + totalmem: () => memory.total, +})); + const running: ScopeState = { loadState: "loaded", activeState: "active", @@ -48,6 +57,7 @@ const withFakeSystemd = ( readonly scope: Effect.Success; readonly units: Map; readonly calls: ReadonlyArray>; + readonly failingVerbs: Set; readonly stateDir: string; readonly cgroupRoot: string; }) => Effect.Effect, @@ -55,7 +65,14 @@ const withFakeSystemd = ( { oomPolicy = true, stopFails = false, - }: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {}, + leftovers = false, + liveOwner = false, + }: { + readonly oomPolicy?: boolean; + readonly stopFails?: boolean; + readonly leftovers?: boolean; + readonly liveOwner?: boolean; + } = {}, ) => Effect.gen(function* () { const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-")); @@ -65,6 +82,7 @@ const withFakeSystemd = ( const cgroupRoot = NodePath.join(bin, "cgroup"); const units = new Map(); const calls: Array> = []; + const failingVerbs = new Set(); const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({ stdout, stderr: "", @@ -83,6 +101,7 @@ const withFakeSystemd = ( return output("", 1); } const [, verb, unit = ""] = args; + if (failingVerbs.has(verb!)) return output("", 1); if (stopFails && verb === "stop") { return { ...output(""), @@ -102,7 +121,12 @@ const withFakeSystemd = ( }), }); const fileSystem = yield* FileSystem.FileSystem; + const { stateDir } = yield* ServerConfig.ServerConfig; + if (leftovers) { + units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" }); + } const scope = yield* make.pipe( + Effect.provideService(ProviderProcesses.ProviderProcesses, { hasOtherLiveOwner: liveOwner }), Effect.provideService(ProcessRunner.ProcessRunner, runner), Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }), @@ -114,8 +138,7 @@ const withFakeSystemd = ( fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options), }), ); - const { stateDir } = yield* ServerConfig.ServerConfig; - return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe( + return yield* body({ scope, units, calls, failingVerbs, stateDir, cgroupRoot }).pipe( Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))), ); }).pipe( @@ -308,27 +331,68 @@ describe("AgentScope service", () => { ), ); - it.effect("stops agents a killed server left before the first launch", () => - withFakeSystemd(({ scope, units, calls, stateDir }) => + it.effect("follows a live memory change at the next launch", () => { + memory.total = 16 * GiB; + return withFakeSystemd(({ scope, calls, failingVerbs }) => Effect.gen(function* () { - units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" }); - const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); - const stops = calls.filter(([, verb]) => verb === "stop"); - expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]); - expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir)); - expect(agent.args).toContain("--property=TimeoutStopSec=10s"); - const terminal = yield* scope.wrap({ - command: "agent", - args: [], - name: "terminal", - survivesRestart: true, - }); - expect(sliceOf(terminal)).toBe("app-t3code-agents.slice"); - expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1); + const launch = scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + const memoryLimits = () => + calls + .filter( + ([, verb, , slice]) => verb === "set-property" && slice === "app-t3code-agents.slice", + ) + .map((args) => args.slice(4)); + yield* launch; + yield* launch; + expect(memoryLimits()).toEqual([[`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`]]); + + // A VM balloon or `pct set --memory` grows RAM while the server keeps running. + memory.total = 22 * GiB; + failingVerbs.add("set-property"); + yield* launch; + yield* launch; + failingVerbs.delete("set-property"); + yield* launch; + yield* launch; + const grown = [`MemoryHigh=${16 * GiB}`, `MemoryMax=${18 * GiB}`]; + expect(memoryLimits()).toEqual([ + [`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`], + grown, + grown, + grown, + ]); }), + ); + }); + + it.effect("stops agents a killed server left before startup completes", () => + withFakeSystemd( + ({ scope, calls, stateDir }) => + Effect.gen(function* () { + expect(stopsOf(calls)).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]); + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir)); + expect(agent.args).toContain("--property=TimeoutStopSec=10s"); + const terminal = yield* scope.wrap({ + command: "agent", + args: [], + name: "terminal", + survivesRestart: true, + }); + expect(sliceOf(terminal)).toBe("app-t3code-agents.slice"); + expect(stopsOf(calls)).toHaveLength(1); + }), + { leftovers: true }, ), ); + it.effect("leaves the slice to another live server sharing this home", () => + withFakeSystemd(({ calls }) => Effect.sync(() => expect(stopsOf(calls)).toEqual([])), { + leftovers: true, + liveOwner: true, + }), + ); + it.effect("stops leftover processes only in an active agent scope", () => withFakeSystemd(({ scope, units, calls, cgroupRoot }) => Effect.gen(function* () { diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index b9b6b56acb..1e52e680b6 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -14,9 +14,11 @@ 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 Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; +import * as ProviderProcesses from "./providerProcesses.ts"; const AGENT_SLICE = "app-t3code-agents.slice"; // Owns every agent slice and competes with the server's unit or scope under app.slice. @@ -106,6 +108,7 @@ export const make = Effect.gen(function* () { const path = yield* Path.Path; const hostEnvironment = yield* HostProcess.Environment; const { stateDir } = yield* ServerConfig.ServerConfig; + const { hasOtherLiveOwner } = yield* ProviderProcesses.ProviderProcesses; const ownedSlice = ownedAgentSlice(stateDir); const layerScope = yield* Effect.scope; @@ -130,6 +133,7 @@ export const make = Effect.gen(function* () { const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* ( systemctl: string, ) { + if (hasOtherLiveOwner) return; const shown = yield* run(systemctl, [ "--user", "show", @@ -190,20 +194,44 @@ export const make = Effect.gen(function* () { slice, ...properties, ]); - if (result._tag === "None" || result.value.code !== 0) { - yield* Effect.logWarning("Could not set resource limits on an agents slice", { - slice, - properties, - stderr: result._tag === "Some" ? result.value.stderr.trim() : undefined, - }); - } + if (result._tag === "Some" && result.value.code === 0) return true; + yield* Effect.logWarning("Could not set resource limits on an agents slice", { + slice, + properties, + stderr: result._tag === "Some" ? result.value.stderr.trim() : undefined, + }); + return false; }); - const limits = agentSliceMemoryLimits(NodeOS.totalmem()); - yield* setProperties(AGENT_SLICE, [`MemoryHigh=${limits.high}`, `MemoryMax=${limits.max}`]); + // VMs and containers can resize RAM live, so each launch re-checks the total + // the limits came from. A failed update is retried by the next launch. + let appliedTotal: number | undefined; + const memoryLimitsLock = yield* Semaphore.make(1); + const applyMemoryLimits = memoryLimitsLock.withPermits(1)( + Effect.gen(function* () { + const total = NodeOS.totalmem(); + if (total === appliedTotal) return; + const limits = agentSliceMemoryLimits(total); + const applied = yield* setProperties(AGENT_SLICE, [ + `MemoryHigh=${limits.high}`, + `MemoryMax=${limits.max}`, + ]); + if (!applied) return; + if (appliedTotal !== undefined) { + yield* Effect.logInfo("Agent memory limits follow a memory change", { + slice: AGENT_SLICE, + previousTotal: appliedTotal, + total, + ...limits, + }); + } + appliedTotal = total; + }), + ); + yield* applyMemoryLimits; yield* setProperties(AGENTS_PARENT_SLICE, AGENTS_PARENT_PROPERTIES); yield* Effect.logInfo("Agent scopes are on", { slice: AGENT_SLICE, - ...limits, + ...agentSliceMemoryLimits(NodeOS.totalmem()), oomPolicy: supportsOomPolicy, }); return { @@ -211,10 +239,15 @@ export const make = Effect.gen(function* () { systemctl, runtimeDir, supportsOomPolicy, + applyMemoryLimits, }; }), ); + // Layer acquisition is the startup barrier: recovery must not terminalize or + // continue old runs while a previous server's providers can still execute. + yield* systemd; + // `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd. const scopeByThread = new Map(); @@ -396,6 +429,7 @@ export const make = Effect.gen(function* () { if (resolved === null) return { command, args }; const scope = yield* systemd; if (scope === undefined) return agentScopeCommand({ command: resolved, args }); + yield* scope.applyMemoryLimits; const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`; // A continuing shared scope cannot attribute a tool's OOM to one thread. // Clear the launch thread's previous scope instead. @@ -427,4 +461,7 @@ export const make = Effect.gen(function* () { } satisfies AgentScopeShape; }); -export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer)); +export const layer = Layer.effect(AgentScope, make).pipe( + Layer.provide(ProcessRunner.layer), + Layer.provideMerge(ProviderProcesses.layer), +); diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index f59b6a6187..8ce873733d 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -7,7 +7,6 @@ import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as TestClock from "effect/testing/TestClock"; import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -22,6 +21,7 @@ import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as ExternalLauncher from "./externalLauncher.ts"; +import { WindowsVerbatimSpawn } from "./windowsVerbatimSpawn.ts"; // Windows drive letters break mocked POSIX PATH splitting; these tests also require /bin/sh stubs. const windowsHost = HostProcess.Platform.defaultValue() === "win32"; @@ -60,6 +60,7 @@ function makeMockDetachedHandle(input: MockSpawnResult & { readonly onUnref?: () const layerTest = (input: { readonly platform: NodeJS.Platform; readonly env?: Record; + readonly path?: Path.Path; readonly resolveExecutable?: (command: string) => string | undefined; readonly onSpawn?: (command: ChildProcess.StandardCommand) => void; readonly onUnref?: () => void; @@ -85,7 +86,15 @@ const layerTest = (input: { ); return Layer.mergeAll( - ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, layerSpawner))), + ExternalLauncher.layer.pipe( + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + layerSpawner, + input.path ? Layer.succeed(Path.Path, input.path) : Layer.empty, + ), + ), + ), Layer.succeed(HostProcess.Platform, input.platform), Layer.succeed( SpawnExecutableResolution, @@ -96,36 +105,48 @@ const layerTest = (input: { }; // macOS command lookup cannot search a Windows drive-letter PATH. -it.effect.skipIf(windowsHost)( - "opens home-relative app bundles using the server home directory", - () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const bin = yield* fs.makeTempDirectoryScoped({ prefix: "t3-app-open-" }); - yield* fs.writeFileString(path.join(bin, "open"), "#!/bin/sh\n"); - yield* fs.chmod(path.join(bin, "open"), 0o755); - const spawned: ChildProcess.StandardCommand[] = []; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app"]) { - yield* launcher.launchEditor({ editor: "file-manager", cwd }); - } - }).pipe( - Effect.provide( - layerTest({ - platform: "darwin", - env: { PATH: bin }, - onSpawn: (command) => spawned.push(command), - }), - ), - Effect.provideService(HostProcess.HomeDirectory, "/Users/server"), - ); - assert.deepEqual( - spawned.map((command) => command.args), - [["/Users/server/Applications/My App.app"], ["/Applications/My App.app"]], - ); - }).pipe(Effect.provide(NodeServices.layer)), +it.effect.skipIf(windowsHost)("opens home-relative targets using the server home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bin = yield* fs.makeTempDirectoryScoped({ prefix: "t3-app-open-" }); + for (const name of ["open", "code", "idea"]) { + yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n"); + yield* fs.chmod(path.join(bin, name), 0o755); + } + const spawned: ChildProcess.StandardCommand[] = []; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app", "/tmp/a:12"]) { + yield* launcher.launchEditor({ editor: "file-manager", cwd, position: { line: 5 } }); + } + yield* launcher.launchEditor({ editor: "vscode", cwd: "~/notes/todo.md:3" }); + yield* launcher.launchEditor({ + editor: "idea", + cwd: "~/notes/todo.md:3", + projectRoot: "~/notes", + }); + }).pipe( + Effect.provide( + layerTest({ + platform: "darwin", + env: { PATH: bin }, + onSpawn: (command) => spawned.push(command), + }), + ), + Effect.provideService(HostProcess.HomeDirectory, "/Users/server"), + ); + assert.deepEqual( + spawned.map((command) => command.args), + [ + ["/Users/server/Applications/My App.app"], + ["/Applications/My App.app"], + ["/tmp/a:12"], + ["--goto", "/Users/server/notes/todo.md:3"], + ["/Users/server/notes", "--line", "3", "/Users/server/notes/todo.md"], + ], + ); + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect.skipIf(windowsHost)( @@ -174,6 +195,86 @@ it.effect.skipIf(windowsHost)( }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +// A project opened from T3 must not replace the editor's last active window. +it.effect.skipIf(windowsHost)( + "opens a project folder in a new VS Code window and a file in the existing one", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + const project = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-project-" }); + for (const name of ["code", "zeditor", "idea"]) { + const executable = path.join(binDir, name); + yield* fileSystem.writeFileString(executable, "#!/bin/sh\n"); + yield* fileSystem.chmod(executable, 0o755); + } + const colonProject = path.join(project, "build:2026"); + yield* fileSystem.makeDirectory(colonProject); + const file = `${path.join(project, "file.ts")}:3:7`; + const exactFile = path.join(project, "a:12"); + yield* fileSystem.writeFileString(exactFile, "exact"); + yield* fileSystem.makeDirectory(`${exactFile}:1:1`); + const positionedFile = path.join(project, "position.txt"); + yield* fileSystem.writeFileString(positionedFile, "position"); + yield* fileSystem.writeFileString(`${positionedFile}:7`, "collision"); + + const spawned: ChildProcess.StandardCommand[] = []; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher.launchEditor({ editor: "vscode", cwd: project }); + yield* launcher.launchEditor({ editor: "vscode", cwd: file }); + yield* launcher.launchEditor({ editor: "vscode", cwd: colonProject }); + for (const position of [{}, { line: 5 }]) { + yield* launcher.launchEditor({ editor: "vscode", cwd: exactFile, position }); + } + + yield* launcher.launchEditor({ editor: "zed", cwd: exactFile, position: {} }); + yield* launcher.launchEditor({ + editor: "zed", + cwd: positionedFile, + position: { line: 5, column: 3 }, + }); + yield* launcher.launchEditor({ editor: "zed", cwd: positionedFile, position: { line: 7 } }); + yield* launcher.launchEditor({ + editor: "vscode", + cwd: `${project}/exponent:1e3`, + position: { line: 5 }, + }); + yield* launcher.launchEditor({ + editor: "idea", + cwd: exactFile, + position: { line: 5, column: 3 }, + }); + }).pipe( + Effect.provide( + layerTest({ + platform: "linux", + env: { PATH: binDir, DISPLAY: ":0" }, + onSpawn: (command) => spawned.push(command), + }), + ), + Effect.provideService(HostProcess.Environment, { PATH: binDir, DISPLAY: ":0" }), + ); + + assert.deepEqual( + spawned.map((command) => command.args), + [ + ["--new-window", project], + ["--goto", file], + ["--new-window", colonProject], + [exactFile], + [exactFile], + [exactFile], + [`${positionedFile}:5:3`], + [positionedFile], + [`${project}/exponent:1e3`], + ["--line", "5", "--column", "2", exactFile], + ], + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + // Windows drive letters cannot resolve the POSIX editor stub. it.effect.skipIf(windowsHost)( "a Linux editor launch without a display takes the desktop session's display from the systemd user manager", @@ -247,6 +348,69 @@ it.effect.skipIf(windowsHost)( }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +// Windows drive letters cannot resolve the POSIX xdg stubs. +it.effect.skipIf(windowsHost)( + "a Linux server without a display offers and opens the file manager on the desktop session's display", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + for (const name of ["xdg-open", "xdg-mime"]) { + const filePath = path.join(binDir, name); + yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); + yield* fileSystem.chmod(filePath, 0o755); + } + + const fileManager = (sessionEnv: ReadonlyArray) => + Effect.gen(function* () { + const spawned: ChildProcess.StandardCommand[] = []; + const result = yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + const editors = yield* launcher.resolveAvailableEditors(); + const kind = yield* launcher.resolveFileManagerRevealKind(); + const opened = yield* launcher + .launchEditor({ editor: "file-manager", cwd: "/workspace" }) + .pipe(Effect.exit); + return { offered: editors.includes("file-manager"), kind, opened }; + }).pipe( + Effect.provide( + layerTest({ + platform: "linux", + env: { PATH: binDir }, + onSpawn: (command) => spawned.push(command), + spawnResult: (command) => + command.command === "busctl" + ? { stdout: JSON.stringify({ type: "as", data: sessionEnv }) } + : command.command === "xdg-mime" + ? { stdout: "org.kde.dolphin.desktop\n" } + : undefined, + }), + ), + Effect.provideService(HostProcess.Environment, { PATH: binDir }), + ); + const open = spawned.find((command) => command.command === "xdg-open"); + return { ...result, open: open && { args: open.args, env: open.options.env } }; + }); + + const session = yield* fileManager(["DISPLAY=:0", "HOME=/home/user"]); + assert.equal(session.offered, true); + assert.equal(session.kind, "files"); + assert.equal(Exit.isSuccess(session.opened), true); + assert.deepEqual(session.open, { + args: ["/workspace"], + env: { PATH: binDir, DISPLAY: ":0" }, + }); + + // No one is logged in to a desktop, so there is no screen to open it on. + const headless = yield* fileManager(["HOME=/home/user"]); + assert.equal(headless.offered, false); + assert.equal(headless.kind, undefined); + assert.equal(Exit.isFailure(headless.opened), true); + assert.equal(headless.open, undefined); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("launches an installed editor with platform-safe arguments", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -290,6 +454,144 @@ it.effect("launches an installed editor with platform-safe arguments", () => }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +const wslpathSpawner = (out: string | undefined) => + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.sync(() => { + if (!ChildProcess.isStandardCommand(command)) { + throw new Error("Expected a standard command"); + } + assert.equal(command.command, "wslpath"); + return makeMockDetachedHandle( + out === undefined ? { exitCode: 1 } : { exitCode: 0, stdout: `${out}\n` }, + ); + }), + ), + ); + +it.effect.each([ + // wslpath is mount-aware: a drive remapped in /etc/wsl.conf keeps its real letter. + { target: "/mnt/d/project", wslpath: "E:\\project", expected: "E:\\project" }, + // wslpath missing or failing falls back to the hand-built UNC path. + { + target: "/home/user/repo", + wslpath: undefined, + expected: "\\\\wsl.localhost\\Ubuntu-24.04\\home\\user\\repo", + }, + { target: "/", wslpath: undefined, expected: "\\\\wsl.localhost\\Ubuntu-24.04" }, +])("resolveWslFileManagerPath resolves $target to $expected", ({ target, wslpath, expected }) => + Effect.gen(function* () { + const result = yield* ExternalLauncher.resolveWslFileManagerPath(target, "Ubuntu-24.04"); + assert.equal(result, expected); + }).pipe(Effect.provide(wslpathSpawner(wslpath))), +); + +it.live.skipIf(!windowsHost)("opens Windows folders through the default shell handler", () => + Effect.gen(function* () { + let spawned: ChildProcess.StandardCommand | undefined; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher.launchEditor({ + editor: "file-manager", + cwd: "C:/workspace [draft]/author's ‘left’ ‚low‛ $media/’; Write-Output injected; #", + }); + }).pipe( + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + onSpawn: (command) => { + spawned = command; + }, + }), + ), + ); + assert.ok(spawned); + assert.equal(spawned.options.detached, false); + const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le"); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner.string( + ChildProcess.make(spawned.command, [ + ...spawned.args.slice(0, -1), + Buffer.from( + `[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); function Invoke-Item { param($LiteralPath) Write-Output $LiteralPath }; ${source}`, + "utf16le", + ).toString("base64"), + ]), + ); + assert.equal( + output.trim(), + "C:\\workspace [draft]\\author's ‘left’ ‚low‛ $media\\’; Write-Output injected; #", + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +for (const [replacement, verb, handler, target, expected] of [ + ["none", "none", "", "C:/repo/file.txt", 'explorer.exe /select,"C:\\repo\\file.txt"'], + ["Directory", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"], + ["Folder", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"], + [ + "Folder", + "open", + '"C:\\Windows\\explorer.exe"', + "C:/repo/file.txt", + 'explorer.exe /select,"C:\\repo\\file.txt"', + ], + [ + "Folder", + "open", + "ExplorerDelegate", + "C:/repo/file.txt", + 'explorer.exe /select,"C:\\repo\\file.txt"', + ], + [ + "Drive", + "openindopus", + "dopusrt.exe", + "C:/repo/file.txt", + 'explorer.exe /select,"C:\\repo\\file.txt"', + ], + ["Drive", "openindopus", "dopusrt.exe", "C:/file.txt", "shell:C:\\"], +] as const) { + it.live.skipIf(!windowsHost)( + `reveals ${target} with ${replacement}/${verb} handled by ${handler}`, + () => + Effect.gen(function* () { + let spawned: ChildProcess.StandardCommand | undefined; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher.launchEditor({ + editor: "file-manager", + cwd: target, + reveal: true, + }); + }).pipe( + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + onSpawn: (command) => { + spawned = command; + }, + }), + ), + ); + assert.ok(spawned); + const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le"); + const stubs = `function Get-ItemProperty { param($LiteralPath, $ErrorAction) @{ '(default)' = if ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell') { '${verb}' } elseif ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell\\${verb}\\command') { '${handler}' } else { 'none' }; DelegateExecute = if ('${handler}' -eq 'ExplorerDelegate') { '{11dbb47c-a525-400b-9e80-a54615a090c0}' } else { '' } } }; function Invoke-Item { param($LiteralPath) Write-Output "shell:$LiteralPath" }; function Start-Process { param($FilePath, $ArgumentList) Write-Output "$FilePath $ArgumentList" }; `; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner.string( + ChildProcess.make(spawned.command, [ + ...spawned.args.slice(0, -1), + Buffer.from(stubs + source, "utf16le").toString("base64"), + ]), + ); + assert.equal(output.trim(), expected); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +} + it.effect.skipIf(windowsHost)( "reveals a WSL file in Windows File Explorer through its UNC path", () => @@ -310,7 +612,7 @@ it.effect.skipIf(windowsHost)( const editors = yield* launcher.resolveAvailableEditors(); yield* launcher.launchEditor({ editor: "file-manager", - cwd: "/home/t3/workspace [draft]/author's $media/clip|draft.mp4", + cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4", reveal: true, }); return { kind, editors }; @@ -337,13 +639,85 @@ it.effect.skipIf(windowsHost)( assert.equal(spawned.options.detached, true); const encodedCommand = String(spawned.args[spawned.args.length - 1] ?? ""); const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); - assert.equal( + assert.include(decodedCommand, "'Directory', 'Folder'"); + assert.include( + decodedCommand, + "Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media'", + ); + assert.include( decodedCommand, - "$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media' } else { Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media\\clip|draft.mp4' + '\"') }", + "'\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media\\clip|draft.mp4'", ); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +const STOCK_FOLDER_VERB = + "\r\nHKEY_CLASSES_ROOT\\Directory\\shell\r\n (Default) REG_SZ none\r\n\r\n"; + +it.effect.each([ + ["selects the file with Explorer on stock Windows", { stdout: STOCK_FOLDER_VERB }, true], + [ + "keeps the PowerShell reveal for a replacement file manager", + { stdout: " (Default) REG_SZ open\r\n" }, + false, + ], + ["keeps the PowerShell reveal when the registry lookup fails", { exitCode: 1 }, false], +] as const)("%s", ([, registry, native]) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), ""); + const spawned: ChildProcess.StandardCommand[] = []; + const verbatim: Array]> = []; + const exit = yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + return yield* launcher + .launchEditor({ + editor: "file-manager", + cwd: "C:/Users/t3/my project/a,b.ts", + reveal: true, + }) + .pipe(Effect.exit); + }).pipe( + Effect.provideService(WindowsVerbatimSpawn, (command, args) => + Effect.sync(() => verbatim.push([command, args])), + ), + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + onSpawn: (command) => spawned.push(command), + spawnResult: (command) => (command.command.endsWith("reg.exe") ? registry : undefined), + }), + ), + ); + + assert.deepEqual( + spawned.map((command) => command.command), + ["C:\\Windows\\System32\\reg.exe"], + ); + if (native) { + assert.isTrue(Exit.isSuccess(exit)); + assert.deepEqual(verbatim, [ + ["C:\\Windows\\explorer.exe", ['/select,"C:\\Users\\t3\\my project\\a,b.ts"']], + ]); + } else { + assert.deepEqual(verbatim, []); + // The PowerShell launch is reached; this host has no powershell.exe to run it. + assert.isTrue(Exit.isFailure(exit)); + if (Exit.isFailure(exit)) { + const error = Cause.squash(exit.cause); + assert.instanceOf(error, ExternalLauncher.ExternalLauncherCommandNotFoundError); + assert.equal( + (error as ExternalLauncher.ExternalLauncherCommandNotFoundError).command, + "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", + ); + } + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + for (const wsl of [false, true]) { it.effect.skipIf(windowsHost)( "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"), @@ -504,6 +878,18 @@ for (const { layout, pathNames, fallbackNames, expected } of [ ); } +// Linux editor discovery also probes fixed system directories; tests point them at a temp +// directory so an editor installed on the host cannot satisfy the lookup. +const withSystemBin = (path: Path.Path, systemBin: string): Path.Path => ({ + ...path, + join: (...parts) => + path.join( + ...parts.map((part) => + ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, + ), + ), +}); + it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directory", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -523,15 +909,7 @@ it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directo const editor = EDITORS.find((editor) => editor.id === "zed")!; const resolve = resolveEditorCommand(editor, { HOME: home, PATH: "" }).pipe( Effect.provideService(HostProcess.Platform, "linux"), - Effect.provideService(Path.Path, { - ...path, - join: (...parts) => - path.join( - ...parts.map((part) => - ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, - ), - ), - }), + Effect.provideService(Path.Path, withSystemBin(path, systemBin)), ); assert.deepEqual( yield* resolve, @@ -562,25 +940,32 @@ it.effect.skipIf(windowsHost)("does not offer the OpenZFS zed daemon as Zed on L ); yield* fs.chmod(zfsZed, 0o755); const editor = EDITORS.find((editor) => editor.id === "zed")!; - const resolve = resolveEditorCommand(editor, { HOME: home, PATH: binDir }).pipe( - Effect.provideService(HostProcess.Platform, "linux"), - Effect.provideService(Path.Path, { - ...path, - join: (...parts) => - path.join( - ...parts.map((part) => - ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, - ), - ), - }), - ); - assert.deepEqual(yield* resolve, Option.none()); + const laterBin = path.join(home, "later-bin"); + const resolveOn = (platform: NodeJS.Platform) => + resolveEditorCommand(editor, { HOME: home, PATH: `${binDir}:${laterBin}` }).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(Path.Path, withSystemBin(path, systemBin)), + ); + assert.deepEqual(yield* resolveOn("linux"), Option.none()); + assert.deepEqual(yield* resolveOn("darwin"), Option.none()); const zedEditor = path.join(home, ".local/bin/zed"); yield* fs.makeDirectory(path.dirname(zedEditor), { recursive: true }); yield* fs.writeFileString(zedEditor, "#!/bin/sh\necho 'Zed 0.200.0'\n"); yield* fs.chmod(zedEditor, 0o755); - assert.deepEqual(yield* resolve, Option.some({ command: zedEditor, baseArgs: [] })); + assert.deepEqual(yield* resolveOn("linux"), Option.some({ command: zedEditor, baseArgs: [] })); + + yield* fs.remove(zedEditor); + const laterZed = path.join(laterBin, "zed"); + yield* fs.makeDirectory(laterBin, { recursive: true }); + yield* fs.writeFileString(laterZed, "#!/bin/sh\necho 'Zed 0.200.0'\n"); + yield* fs.chmod(laterZed, 0o755); + for (const platform of ["linux", "darwin"] as const) { + assert.deepEqual( + yield* resolveOn(platform), + Option.some({ command: laterZed, baseArgs: [] }), + ); + } }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -590,6 +975,7 @@ it.effect.skipIf(windowsHost)("does not open Zed with the OpenZFS zed daemon on const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-launch-" }); const binDir = path.join(home, "bin"); + const systemBin = path.join(home, "system-bin"); yield* fs.makeDirectory(binDir, { recursive: true }); yield* fs.writeFileString(path.join(binDir, "zed"), "#!/bin/sh\nexit 1\n"); yield* fs.chmod(path.join(binDir, "zed"), 0o755); @@ -602,7 +988,8 @@ it.effect.skipIf(windowsHost)("does not open Zed with the OpenZFS zed daemon on Effect.provide( layerTest({ platform: "linux", - env: { HOME: home, PATH: binDir }, + env: { HOME: home, PATH: binDir, DISPLAY: ":0" }, + path: withSystemBin(path, systemBin), onSpawn: (command) => spawned.push(command), spawnResult: (command) => (command.args[0] === "--version" ? { exitCode: 1 } : undefined), }), @@ -641,7 +1028,11 @@ it.effect.each([ yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; assert.include(yield* launcher.resolveAvailableEditors(), editor); - yield* launcher.launchEditor({ editor, cwd: "/workspace with spaces/file.ts:12:4" }); + yield* launcher.launchEditor({ + editor, + cwd: "/workspace with spaces/file.ts:12:4", + projectRoot: "/workspace with spaces", + }); }).pipe( Effect.provide( layerTest({ @@ -657,6 +1048,7 @@ it.effect.each([ assert.ok(spawned); assert.equal(spawned.command, executable); assert.deepEqual(spawned.args, [ + "/workspace with spaces", "--line", "12", "--column", @@ -741,6 +1133,62 @@ it.effect("keeps the macOS VS Code Insiders bundle out of stable VS Code", () => }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect.each([ + { + platform: "darwin", + scripts: "Library/Application Support/JetBrains/Toolbox/scripts", + suffix: "", + }, + { platform: "linux", scripts: ".local/share/JetBrains/Toolbox/scripts", suffix: "" }, + { platform: "win32", scripts: "JetBrains/Toolbox/scripts", suffix: ".cmd" }, + { + platform: "win32", + scripts: "JetBrains/Toolbox/scripts", + suffix: ".cmd", + install: "Programs/IntelliJ IDEA/bin/idea64.exe", + }, +] as const)( + "discovers a numbered JetBrains Toolbox script on $platform", + ({ platform, scripts, suffix, ...row }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-toolbox-numbered-" }); + const dir = path.join(home, scripts); + yield* fs.makeDirectory(dir, { recursive: true }); + for (const name of ["idea10", "idea2"]) { + yield* fs.writeFileString(path.join(dir, `${name}${suffix}`), "#!/bin/sh\n"); + yield* fs.chmod(path.join(dir, `${name}${suffix}`), 0o755); + } + const install = "install" in row ? path.join(home, row.install) : undefined; + if (install) { + yield* fs.makeDirectory(path.dirname(install), { recursive: true }); + yield* fs.writeFileString(install, ""); + } + + const editor = EDITORS.find((editor) => editor.id === "idea")!; + const resolved = yield* resolveEditorCommand(editor, { + HOME: home, + LOCALAPPDATA: home, + PATH: path.join(home, "empty"), + PATHEXT: ".COM;.EXE;.BAT;.CMD", + }).pipe( + Effect.provideService(HostProcess.Platform, platform), + // Keep IDEs installed on the host out of system locations such as /Applications. + Effect.provideService(FileSystem.FileSystem, { + ...fs, + stat: (file) => + fs.stat(file.startsWith(`${home}${path.sep}`) ? file : path.join(home, "missing")), + }), + ); + + assert.deepEqual( + resolved, + Option.some({ command: install ?? path.join(dir, `idea2${suffix}`), baseArgs: [] }), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + for (const { platform, installPath, onPath } of [ { platform: "darwin", installPath: ".local/bin/agy", onPath: true }, { platform: "linux", installPath: ".local/bin/agy", onPath: false }, @@ -898,63 +1346,56 @@ it.effect( }, ); -it.effect("keeps scanning after the caller is interrupted and shares that scan", () => { - const fileInfo = { type: "File" } as FileSystem.File.Info; - const release = Deferred.makeUnsafe(); - let parkedStats = 0; - const layerLauncher = ExternalLauncher.layer.pipe( - Layer.provide( - Layer.mergeAll( - FileSystem.layerNoop({ - stat: () => - Effect.gen(function* () { - if (!Deferred.isDoneUnsafe(release)) { - parkedStats += 1; - yield* Deferred.await(release); - } - return fileInfo; +it.effect.each(["Zed Nightly", "Zed Preview"])( + "launches stable Zed on Windows when %s comes first on PATH", + (channel) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-channels-" }); + // A user folder naming Zed and a channel does not mark either install. + const programs = path.join(root, "Users", "zedpreview", "Programs"); + const prereleaseBin = path.join(programs, channel, "bin"); + const stableBin = path.join(programs, "Zed", "bin"); + for (const dir of [prereleaseBin, stableBin]) { + yield* fs.makeDirectory(dir, { recursive: true }); + yield* fs.writeFileString(path.join(dir, "zed.EXE"), ""); + } + const env = { PATH: `${prereleaseBin};${stableBin}`, PATHEXT: ".COM;.EXE;.BAT;.CMD" }; + + const launchZed = Effect.gen(function* () { + let spawned: ChildProcess.StandardCommand | undefined; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher.launchEditor({ editor: "zed", cwd: "C:\\workspace" }); + }).pipe( + Effect.provide( + layerTest({ + platform: "win32", + env, + onSpawn: (command) => { + spawned = command; + }, }), - }), - Path.layer, - Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())), - ), - ), - ), - ); + ), + ); + assert.ok(spawned); + return spawned; + }); - return Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - - const interrupted = yield* Effect.forkChild(launcher.resolveAvailableEditors()); - yield* Effect.yieldNow; - yield* Fiber.interrupt(interrupted); - - const next = yield* Effect.forkChild(launcher.resolveAvailableEditors()); - yield* Effect.yieldNow; - assert.equal(parkedStats, 1); - - yield* Deferred.succeed(release, undefined); - const editors = yield* Fiber.join(next); - assert.equal(editors.includes("vscode"), true); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerLauncher, - Layer.succeed(HostProcess.Platform, "win32"), - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - PATH: "C:\\t3-editor-discovery-interrupt-test", - PATHEXT: ".COM;.EXE;.BAT;.CMD", - }, - }), - ), - ), - ), - ); -}); + const stable = yield* launchZed; + assert.equal(stable.command, path.join(stableBin, "zed.EXE")); + assert.deepEqual(stable.args, ["C:\\workspace"]); + + env.PATH = `${stableBin};${prereleaseBin}`; + assert.equal((yield* launchZed).command, "zed"); + + env.PATH = `${prereleaseBin};${stableBin}`; + // With only the prerelease install left, it still opens by name. + yield* fs.remove(path.join(stableBin, "zed.EXE")); + assert.equal((yield* launchZed).command, "zed"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); const launchWindowsShimEditor = (cwd: string) => Effect.gen(function* () { diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index b900823f16..caa6664a1b 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -34,6 +34,7 @@ import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { makeStaleWhileRevalidate } from "../environment/staleWhileRevalidate.ts"; +import { WindowsVerbatimSpawn } from "./windowsVerbatimSpawn.ts"; export { ExternalLauncherError, ExternalLauncherBrowserSpawnError, @@ -139,18 +140,45 @@ function parseTargetPathAndPosition(target: string): Option.Option { - const parsedTarget = parseTargetPathAndPosition(target); + const parsedTarget = + position === undefined + ? parseTargetPathAndPosition(target) + : Option.fromUndefinedOr(position.line).pipe( + Option.map((line) => ({ + path: target, + line: String(line), + column: Option.fromUndefinedOr(position.column).pipe(Option.map(String)), + })), + ); + const positionedTarget = Option.match(parsedTarget, { + onNone: () => target, + onSome: ({ path, line, column }) => [path, line, ...Option.toArray(column)].join(":"), + }); switch (editor.launchStyle) { case "direct-path": - return [target]; + return [positionedTarget]; case "goto": - return Option.isSome(parsedTarget) ? ["--goto", target] : [target]; + // An existing folder wins over a position: `build:2026` is a legal folder name. + // Without a window flag, VS Code's window settings may replace the user's last active window. + if (isDirectory) return ["--new-window", target]; + // VS Code splits every numeric colon segment, including ones inside the filename. + if ( + position !== undefined && + target.split(":").some((segment) => !Number.isNaN(Number(segment))) + ) + return [target]; + return Option.isSome(parsedTarget) ? ["--goto", positionedTarget] : [target]; case "line-column": return Option.match(parsedTarget, { onNone: () => [target], onSome: ({ path, line, column }) => [ + // Only positioned targets get the root: a folder target would open as a second project. + ...(projectRoot === undefined ? [] : [projectRoot]), "--line", line, // JetBrains IDEs count `--column` from 0; targets count columns from 1. @@ -175,11 +203,16 @@ function encodeUtf16LeBase64(input: string): string { } function escapePowerShellStringLiteral(input: string): string { - return `'${input.replaceAll("'", "''")}'`; + // PowerShell also recognises typographic apostrophes as single-quote delimiters. + return `'${input.replace(/['\u2018-\u201b]/g, "$&$&")}'`; +} + +function resolveWindowsRoot(env: NodeJS.ProcessEnv): string { + return env.SYSTEMROOT || env.windir || String.raw`C:\Windows`; } function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string { - return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; + return `${resolveWindowsRoot(env)}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; } function resolveWslPowerShellPath(): string { @@ -358,11 +391,41 @@ const fileManagerRevealKindForPlatform = Effect.fn( return hasGraphicalLinuxSession(env) ? "files" : undefined; }); -function resolveWslFileManagerPath(target: string, distroName: string): string { +function wslUncFallbackPath(target: string, distroName: string): string { const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\"); return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`; } +// wslpath -w is mount-aware, so a drive remapped in /etc/wsl.conf resolves to the +// real letter and a Linux path resolves to the \\wsl.localhost UNC path. Fall back +// to the UNC form by hand when wslpath is missing or fails. +export const resolveWslFileManagerPath = Effect.fn("externalLauncher.resolveWslFileManagerPath")( + function* ( + target: string, + distroName: string, + ): Effect.fn.Return { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + return yield* spawner + .spawn(ChildProcess.make("wslpath", ["-w", target], { stdin: "ignore", stderr: "ignore" })) + .pipe( + Effect.flatMap((handle) => + Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], { + concurrency: "unbounded", + }), + ), + Effect.map(([stdout, exitCode]) => { + const translated = stdout.trim(); + return exitCode === 0 && translated.length > 0 + ? translated + : wslUncFallbackPath(target, distroName); + }), + Effect.scoped, + Effect.timeout("2 seconds"), + Effect.orElseSucceed(() => wslUncFallbackPath(target, distroName)), + ); + }, +); + function buildBrowserLaunch( target: string, platform: NodeJS.Platform, @@ -430,16 +493,23 @@ const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")( return buildBrowserLaunch(target, platform, env); }); +// Editors and the file manager open on the desktop session, so a boot-started +// server discovers and launches them with that session's display. +const readEditorEnv = Effect.fn("externalLauncher.readEditorEnv")(function* () { + const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) }; + return hasGraphicalLinuxSession(env) ? env : { ...env, ...(yield* readGraphicalSessionEnv()) }; +}); + const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () { const platform = yield* HostProcess.Platform; - const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) }; + const env = yield* readEditorEnv(); return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings); }); const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")( function* () { const platform = yield* HostProcess.Platform; - const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) }; + const env = yield* readEditorEnv(); return yield* fileManagerRevealKindForPlatform(platform, env); }, ); @@ -465,7 +535,7 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner > { const platform = yield* HostProcess.Platform; - const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) }; + const env = yield* readEditorEnv(); yield* Effect.annotateCurrentSpan({ "externalLauncher.editor": input.editor, "externalLauncher.cwd": input.cwd, @@ -476,6 +546,18 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor }); } + const target = input.cwd; + let position = input.position; + if (editorDef.id === "zed" && position?.line !== undefined) { + // Zed resolves existing paths before positions, so ambiguous spellings must stay literal. + const collision = + /:\d+(?=:|$)/.test(target) || + (yield* (yield* FileSystem.FileSystem) + .exists(`${target}:${position.line}${position.column ? `:${position.column}` : ""}`) + .pipe(Effect.orElseSucceed(() => true))); + if (collision) position = {}; + } + if (editorDef.commands) { const resolved = yield* resolveEditorCommand(editorDef, env); if (Option.isNone(resolved)) { @@ -485,11 +567,20 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( }); } const { command, baseArgs } = resolved.value; + const isDirectory = + editorDef.launchStyle === "goto" && + (yield* (yield* FileSystem.FileSystem).stat(target).pipe( + Effect.map((info) => info.type === "Directory"), + Effect.orElseSucceed(() => false), + )); return { editor: editorDef.id, target: input.cwd, command, - args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd)], + args: [ + ...baseArgs, + ...resolveCommandEditorArgs(editorDef, target, isDirectory, input.projectRoot, position), + ], }; } @@ -502,31 +593,41 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor }); } - const target = expandHomePath(input.cwd, yield* HostProcess.HomeDirectory); if (input.reveal === true) { return yield* resolveFileManagerRevealLaunch(target, platform, env, command); } + if (platform === "win32") { + // ShellExecute honours replacement folder handlers that explorer.exe bypasses. + return { + ...powerShellFileManagerLaunch( + target, + `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(normalizeWindowsFileManagerPath(target))}`, + resolvePowerShellPath(env), + ), + detached: WINDOWS_POWERSHELL_DETACHED, + }; + } + return { editor: editorDef.id, target, command, args: command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined - ? [resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)] - : platform === "win32" - ? // Explorer interprets / as a switch and silently opens a fallback folder. - [normalizeWindowsFileManagerPath(target)] - : [target], + ? [yield* resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)] + : [target], }; }); -// A replacement manager registers a default Directory shell verb; stock Windows -// uses "none". Explorer needs its /select argument passed verbatim through -// PowerShell because Node's argument quoting changes how Explorer parses it. +// Replacement managers can register under Directory, Drive, or Folder. Explorer +// needs its /select argument passed verbatim through PowerShell because Node's +// argument quoting changes how Explorer parses it. function buildFileManagerRevealPowerShellSource(target: string, parent: string): string { const literal = escapePowerShellStringLiteral(target); - return `$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`; + const folderClass = /^[a-z]:\\$/i.test(parent) ? "Drive" : "Directory"; + // Explorer's ordinary open/explore handlers may also be explicit defaults. + return String.raw`$ProgressPreference = 'SilentlyContinue'; $folderVerb = '${folderClass}', 'Folder' | ForEach-Object { $key = "Registry::HKEY_CLASSES_ROOT\$_\shell"; $verb = (Get-ItemProperty -LiteralPath $key -ErrorAction SilentlyContinue).'(default)'; if ($verb -and $verb -ne 'none') { $handler = Get-ItemProperty -LiteralPath "$key\$verb\command" -ErrorAction SilentlyContinue; if ($handler.DelegateExecute -ne '{11dbb47c-a525-400b-9e80-a54615a090c0}' -and $handler.'(default)' -notmatch '^\s*"?(?:[^"]*[\\/])?explorer\.exe(?:["\s]|$)') { $verb } } }; if ($folderVerb) { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`; } function powerShellFileManagerLaunch( @@ -578,13 +679,18 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch shouldUseWindowsHostFromWsl(platform, env) && env.WSL_DISTRO_NAME !== undefined ) { - const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME); if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) { // WSL names may contain quotes that Explorer's /select cannot encode. // Open the parent through the shell so replacement managers still apply. const path = yield* Path.Path; // .NET path parsing rejects characters that are legal in WSL filenames. - const parent = resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME); + const [explorerTarget, parent] = yield* Effect.all( + [ + resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME), + resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME), + ], + { concurrency: "unbounded" }, + ); const source = explorerTarget.includes('"') ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}` : buildFileManagerRevealPowerShellSource(explorerTarget, parent); @@ -599,7 +705,7 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch editor: "file-manager", target, command: "explorer.exe", - args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)], + args: [yield* resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)], }; } @@ -650,18 +756,72 @@ const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")( }), ); +// Stock Windows answers "none"; any other verb may be a replacement file manager, which only +// the PowerShell reveal honors. Reading stdout is about 600 ms faster than spawner.string here. +const hasStockWindowsFolderVerb = Effect.fn("externalLauncher.hasStockWindowsFolderVerb")( + function* () { + const env = yield* readBrowserLaunchEnv; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make( + `${resolveWindowsRoot(env)}\\System32\\reg.exe`, + ["query", "HKCR\\Directory\\shell", "/ve"], + { stdin: "ignore", stderr: "ignore" }, + ), + ); + const [stdout, exitCode] = yield* Effect.all( + [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], + { concurrency: "unbounded" }, + ); + return exitCode === 0 && /REG_SZ\s+none\s*$/im.test(stdout); + }, + Effect.scoped, + Effect.timeout("2 seconds"), + Effect.orElseSucceed(() => false), +); + +// Explorer parses /select itself, so it needs the argument verbatim rather than Node's quoting. +const revealWindowsItem = Effect.fn("externalLauncher.revealWindowsItem")(function* ( + target: string, +) { + const command = `${resolveWindowsRoot(yield* readBrowserLaunchEnv)}\\explorer.exe`; + const args = [`/select,"${normalizeWindowsFileManagerPath(target)}"`]; + yield* (yield* WindowsVerbatimSpawn)(command, args).pipe( + Effect.mapError( + (cause) => + new ExternalLauncherEditorSpawnError({ + editor: "file-manager", + target, + command, + args, + cause, + }), + ), + ); +}); + const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* ( input: LaunchEditorInput, + hasStockFolderVerb: Effect.Effect, ) { - const launch = yield* resolveEditorLaunch(input); - if ( - input.editor === "file-manager" && - input.reveal === true && - launch.command === "xdg-open" && - (yield* HostProcess.Platform) === "linux" && - (yield* tryRevealLinuxItem(launch.target)) - ) { - return; + // Clients send `~/` host paths as written, and launches run without a shell to expand them. + const home = yield* HostProcess.HomeDirectory; + const cwd = expandHomePath(input.cwd, home); + const projectRoot = + input.projectRoot === undefined ? undefined : expandHomePath(input.projectRoot, home); + const launch = yield* resolveEditorLaunch({ ...input, cwd, projectRoot }); + if (input.editor === "file-manager" && input.reveal === true) { + const platform = yield* HostProcess.Platform; + if ( + platform === "linux" && + launch.command === "xdg-open" && + (yield* tryRevealLinuxItem(launch.target)) + ) { + return; + } + if (platform === "win32" && (yield* hasStockFolderVerb)) { + return yield* revealWindowsItem(launch.target); + } } yield* launchEditorProcess(launch); }); @@ -822,6 +982,12 @@ export const make = Effect.gen(function* () { ), EDITOR_DISCOVERY_CACHE_TTL, ); + const cachedStockWindowsFolderVerb = yield* makeStaleWhileRevalidate( + hasStockWindowsFolderVerb().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + EDITOR_DISCOVERY_CACHE_TTL, + ); // Forwarders retain the underlying launcher and discovery spans. return ExternalLauncher.of({ @@ -839,7 +1005,9 @@ export const make = Effect.gen(function* () { ), launchEditor: Effect.fnUntraced( function* (input) { - return yield* provideCommandResolutionServices(launchEditor(input)); + return yield* provideCommandResolutionServices( + launchEditor(input, cachedStockWindowsFolderVerb), + ); }, Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ), diff --git a/apps/server/src/process/providerProcesses.test.ts b/apps/server/src/process/providerProcesses.test.ts new file mode 100644 index 0000000000..26bad1cec9 --- /dev/null +++ b/apps/server/src/process/providerProcesses.test.ts @@ -0,0 +1,127 @@ +// @effect-diagnostics nodeBuiltinImport:off -- real processes stand in for servers and CLIs. +import * as NodeChildProcess from "node:child_process"; +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, expect, it } from "@effect/vitest"; +import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ServerConfig from "../config.ts"; +import * as ProviderProcesses from "./providerProcesses.ts"; + +// Real child processes stand in for servers and CLIs; only PIDs captured at spawn are signalled. +const ownedProcess = Effect.gen(function* () { + const ready = yield* Deferred.make(); + const exited = yield* Deferred.make(); + const child = yield* Effect.acquireRelease( + Effect.sync(() => { + const child = NodeChildProcess.spawn( + process.execPath, + ["-e", 'process.stdin.resume(); process.send("ready");'], + { stdio: ["pipe", "ignore", "ignore", "ipc"] }, + ); + child.once("message", () => Deferred.doneUnsafe(ready, Effect.void)); + child.once("error", (error) => Deferred.doneUnsafe(ready, Effect.die(error))); + child.once("exit", () => Deferred.doneUnsafe(exited, Effect.void)); + return child; + }), + (child) => + Effect.sync(() => child.kill("SIGKILL")).pipe(Effect.andThen(Deferred.await(exited))), + ); + yield* Deferred.await(ready); + const pid = child.pid; + assert(pid !== undefined); + const controller = AcpSessionRuntime.makePosixProcessTreeController("linux"); + const identity = controller.identity(pid); + assert(identity !== undefined); + const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); + return { + pid, + startTime: `${boot}:${identity.startTime}`, + pgid: 0, + running: () => { + const observed = controller.identity(pid); + return observed !== undefined && !AcpSessionRuntime.posixProcessIsZombie(observed); + }, + stop: Effect.sync(() => child.kill("SIGKILL")).pipe(Effect.andThen(Deferred.await(exited))), + }; +}); + +describe.runIf(HostProcess.Platform.defaultValue() === "linux")("ProviderProcesses", () => { + it.live("reaps only recorded CLIs of dead servers before startup completes", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const directory = NodePath.join(config.stateDir, "provider-processes"); + NodeFS.mkdirSync(directory, { recursive: true }); + type Identity = { readonly pid: number; readonly startTime: string }; + const record = (owner: Identity, processes: ReadonlyArray) => { + const instanceId = NodeCrypto.randomUUID(); + NodeFS.writeFileSync( + NodePath.join(directory, `${instanceId}.json`), + JSON.stringify({ + version: 1, + instanceId, + hostname: NodeOS.hostname(), + stateDir: config.stateDir, + owner: { pid: owner.pid, startTime: owner.startTime }, + processes: processes.map(({ pid, startTime }) => ({ pid, startTime, pgid: 0 })), + }), + ); + }; + const reused = (identity: Identity) => ({ + ...identity, + startTime: identity.startTime.replace(/:\d+$/, ":1"), + }); + const deadOwner = yield* ownedProcess; + const liveOwner = yield* ownedProcess; + const reusedOwner = yield* ownedProcess; + const liveProvider = yield* ownedProcess; + const reusedProvider = yield* ownedProcess; + const orphan = yield* ownedProcess; + const orphanOfReusedOwner = yield* ownedProcess; + const unrecorded = yield* ownedProcess; + record(liveOwner, [liveProvider]); + record(deadOwner, [reused(reusedProvider)]); + record(deadOwner, [orphan]); + record(reused(reusedOwner), [orphanOfReusedOwner]); + yield* deadOwner.stop; + + const context = yield* Layer.build(ProviderProcesses.layer); + expect(Context.get(context, ProviderProcesses.ProviderProcesses).hasOtherLiveOwner).toBe( + true, + ); + + expect({ + orphan: orphan.running(), + orphanOfReusedOwner: orphanOfReusedOwner.running(), + liveProvider: liveProvider.running(), + reusedProvider: reusedProvider.running(), + reusedOwner: reusedOwner.running(), + unrecorded: unrecorded.running(), + }).toEqual({ + orphan: false, + orphanOfReusedOwner: false, + liveProvider: true, + reusedProvider: true, + reusedOwner: true, + unrecorded: true, + }); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-restart-ownership-" }).pipe( + Layer.provideMerge(NodeServices.layer), + ), + ), + ), + ); +}); diff --git a/apps/server/src/process/providerProcesses.ts b/apps/server/src/process/providerProcesses.ts new file mode 100644 index 0000000000..4fe9a47637 --- /dev/null +++ b/apps/server/src/process/providerProcesses.ts @@ -0,0 +1,140 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the SDK's synchronous spawn callback must record ownership before releasing the child. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import * as ServerConfig from "../config.ts"; + +const ProcessIdentity = Schema.Struct({ + pid: Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: Number.MAX_SAFE_INTEGER })), + startTime: Schema.String, +}); +const OwnershipRecord = Schema.Struct({ + version: Schema.Literal(1), + instanceId: Schema.String, + hostname: Schema.String, + stateDir: Schema.String, + owner: ProcessIdentity, + processes: Schema.Array(Schema.Struct({ ...ProcessIdentity.fields, pgid: Schema.Int })), +}); +const decodeRecord = Schema.decodeUnknownSync(Schema.fromJsonString(OwnershipRecord)); + +// A concurrent exit can remove the record. Incomplete/unknown records never authorize a signal. +const readRecord = (recordPath: string) => { + try { + return decodeRecord(NodeFS.readFileSync(recordPath, "utf8")); + } catch { + return undefined; + } +}; + +export const ProviderProcesses = Context.Reference<{ + readonly register?: (pid: number) => () => void; + readonly hasOtherLiveOwner: boolean; +}>("t3/process/ProviderProcesses", { defaultValue: () => ({ hasOtherLiveOwner: false }) }); + +const make = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform !== "linux") return { hasOtherLiveOwner: false }; + const { stateDir } = yield* ServerConfig.ServerConfig; + const directory = NodePath.join(stateDir, "provider-processes"); + const hostname = NodeOS.hostname(); + const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); + const controller = AcpSessionRuntime.makePosixProcessTreeController(platform); + const identity = (pid: number) => { + const observed = controller.identity(pid); + if (observed === undefined || AcpSessionRuntime.posixProcessIsZombie(observed)) + return undefined; + return { ...observed, startTime: `${boot}:${observed.startTime}` }; + }; + const matches = (expected: typeof ProcessIdentity.Type) => + identity(expected.pid)?.startTime === expected.startTime; + const kill = (survivor: typeof ProcessIdentity.Type) => { + try { + controller.signalProcess(survivor.pid, "SIGKILL"); + } catch {} + }; + const owner = identity(process.pid); + if (owner === undefined) return yield* Effect.die(new Error("Cannot identify provider owner")); + NodeFS.mkdirSync(directory, { recursive: true }); + + const writeRecord = (processes: (typeof OwnershipRecord.Type)["processes"]) => { + const instanceId = NodeCrypto.randomUUID(); + const recordPath = NodePath.join(directory, `${instanceId}.json`); + const pendingPath = `${recordPath}.pending`; + NodeFS.writeFileSync( + pendingPath, + JSON.stringify({ + version: 1, + instanceId, + hostname, + stateDir, + owner: { pid: owner.pid, startTime: owner.startTime }, + processes, + } satisfies typeof OwnershipRecord.Type), + ); + NodeFS.renameSync(pendingPath, recordPath); + return () => NodeFS.rmSync(recordPath, { force: true }); + }; + // Publish the server identity even before its first provider. Another server + // using this home must not stop the shared systemd slice while we are alive. + const forgetOwner = writeRecord([]); + yield* Effect.addFinalizer(() => Effect.sync(forgetOwner)); + let hasOtherLiveOwner = false; + + // Only immutable per-launch records are shared between server instances. A + // live owner's records belong to that server, even when it uses this home. + for (const file of NodeFS.readdirSync(directory)) { + if (!file.endsWith(".json")) continue; + const recordPath = NodePath.join(directory, file); + const record = readRecord(recordPath); + if (record === undefined) continue; + if (record.hostname !== hostname || record.stateDir !== stateDir) continue; + if (matches(record.owner)) { + if (record.owner.pid !== process.pid) hasOtherLiveOwner = true; + continue; + } + let survived = false; + for (const survivor of record.processes) { + if (survivor.pid === process.pid || !matches(survivor)) continue; + // Never infer ownership from argv, executable names, or group membership. + // As in the ACP controller, starttime blocks reuse between observations. + // Node has no pidfd_send_signal, so the final read-to-signal race remains. + kill(survivor); + for (let attempt = 0; matches(survivor) && !survived; attempt++) { + survived = attempt === 100; + if (!survived) yield* Effect.sleep("10 millis"); + } + } + // Like a failed slice stop, an unkillable CLI must not keep the server down; + // its record stays so the next start retries. + if (survived) { + yield* Effect.logWarning("Could not stop a provider left by a previous server", { file }); + continue; + } + NodeFS.rmSync(recordPath, { force: true }); + } + + return { + hasOtherLiveOwner, + register: (pid: number) => { + const provider = identity(pid); + if (provider === undefined || provider.ppid !== process.pid) { + throw new Error("Cannot identify spawned provider"); + } + // A rename keeps startup from seeing a partial write. The child is gated + // until this returns, so an abrupt death cannot leave an unrecorded CLI. + return writeRecord([{ pid, startTime: provider.startTime, pgid: provider.pgid }]); + }, + }; +}); + +export const layer = Layer.effect(ProviderProcesses, make); diff --git a/apps/server/src/process/windowsVerbatimSpawn.ts b/apps/server/src/process/windowsVerbatimSpawn.ts new file mode 100644 index 0000000000..15075c2245 --- /dev/null +++ b/apps/server/src/process/windowsVerbatimSpawn.ts @@ -0,0 +1,29 @@ +// @effect-diagnostics nodeBuiltinImport:off - Effect's spawner has no windowsVerbatimArguments option. +import * as NodeChildProcess from "node:child_process"; + +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; + +export type WindowsVerbatimSpawner = ( + command: string, + args: ReadonlyArray, +) => Effect.Effect; + +const spawnDetachedVerbatim: WindowsVerbatimSpawner = (command, args) => + Effect.callback((resume) => { + const child = NodeChildProcess.spawn(command, args, { + detached: true, + stdio: "ignore", + windowsVerbatimArguments: true, + }); + child.once("error", (error) => resume(Effect.fail(error))); + child.once("spawn", () => { + child.unref(); + resume(Effect.void); + }); + }); + +export const WindowsVerbatimSpawn = Context.Reference( + "t3/process/WindowsVerbatimSpawn", + { defaultValue: () => spawnDetachedVerbatim }, +); diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 3754f25a4c..6768fa23c7 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -2,6 +2,8 @@ import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshot import { describe, expect, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Cause from "effect/Cause"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; @@ -143,6 +145,29 @@ describe("runProcess", () => { }), ); + it.effect("reports child startup before delivering cancellation during acquisition", () => + Effect.gen(function* () { + let started = false; + const spawner = makeSpawner(() => + Effect.withFiber((fiber) => + Effect.sync(() => { + fiber.interruptUnsafe(); + return makeHandle({}); + }), + ), + ); + const result = yield* runWith(spawner)({ + command: "git", + args: ["restore"], + onSpawn: () => { + started = true; + }, + }).pipe(Effect.exit); + expect(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)).toBe(true); + expect(started).toBe(true); + }).pipe(Effect.scoped), + ); + it.effect("fails when output exceeds max buffer in default mode", () => Effect.gen(function* () { const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) }))); diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index a345c67eca..4c7efd3cc9 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -26,6 +26,8 @@ export interface ProcessRunInput { readonly stdin?: string | undefined; /** Receives every stdout chunk, including bytes beyond the buffered output limit. */ readonly onStdoutChunk?: ((chunk: Uint8Array) => void) | undefined; + /** Runs after successful spawn, before cancellation can interrupt acquisition. */ + readonly onSpawn?: (() => void) | undefined; readonly maxOutputBytes?: number | undefined; readonly outputMode?: "error" | "truncate" | undefined; readonly truncatedMarker?: string | undefined; @@ -290,7 +292,7 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* ( cause, }); - const child = yield* spawner + const spawn = spawner .spawn( ChildProcess.make(spawnCommand.command, spawnCommand.args, { ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}), @@ -309,6 +311,12 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* ( // Synchronous spawn throws arrive as defects; recover them too so callers see typed spawn failures. Effect.catchDefect((cause) => Effect.fail(toSpawnError(cause))), ); + const child = yield* input.onSpawn === undefined + ? spawn + : spawn.pipe( + Effect.tap(() => Effect.sync(() => input.onSpawn?.())), + Effect.uninterruptible, + ); const stdin = input.stdin; const onStdoutChunk = input.onStdoutChunk; diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 140dff3148..18c0946144 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -1,3 +1,4 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { type AgentSessionSource, @@ -6,26 +7,38 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + MessageId, + RunId, ThreadId, type ApplicationStoredEvent, type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, type OrchestrationV2ProviderThread, } from "@t3tools/contracts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; 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 Path from "effect/Path"; import * as Stream from "effect/Stream"; import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; +import * as ServerConfig from "../config.ts"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as EventStore from "../orchestration-v2/EventStore.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import { CLAUDE_MODEL_SELECTION, CODEX_MODEL_SELECTION, @@ -83,6 +96,7 @@ function candidate( { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, ], }, + worktree: null as { path: string; branch: string | null } | null, } satisfies AgentSessionScanner.AgentSessionRecentThread; } @@ -170,12 +184,18 @@ const seedOwner = Effect.fn(function* ( }); const makeImporter = Effect.fn(function* ( - candidates: ReadonlyArray>, + candidates: ReadonlyArray, beforeTransaction: Effect.Effect = Effect.void, + getAdapter?: ProviderAdapterRegistry.ProviderAdapterRegistryV2Shape["get"], + threadCommands?: ThreadCommandExecutor.ThreadCommandExecutor["Service"], settings: Layer.Layer< ServerSettings.ServerSettingsService, ServerSettingsError > = ServerSettings.layerTest(), + realScan?: { + readonly workspaceRoot: string; + readonly scanner: AgentSessionScanner.AgentSessionScanner["Service"]; + }, ) { const sql = yield* SqlClient.SqlClient; const events = yield* EventStore.EventStoreV2; @@ -217,15 +237,17 @@ const makeImporter = Effect.fn(function* ( ProviderSessionRuntime.ProviderSessionRuntimeRepository, yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository, ), - Layer.mock(AgentSessionScanner.AgentSessionScanner)({ - recentThreads: () => Stream.fromIterable(candidates), - }), + realScan === undefined + ? Layer.mock(AgentSessionScanner.AgentSessionScanner)({ + recentThreads: () => Stream.fromIterable(candidates), + }) + : Layer.succeed(AgentSessionScanner.AgentSessionScanner, realScan.scanner), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ id: projectId, title: "Project", - workspaceRoot: "/workspace/project", + workspaceRoot: realScan?.workspaceRoot ?? "/workspace/project", defaultModelSelection: null, scripts: [], createdAt: timestamp, @@ -243,12 +265,23 @@ const makeImporter = Effect.fn(function* ( ), ), }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)( + getAdapter === undefined ? {} : { get: getAdapter }, + ), + Layer.succeed( + ThreadCommandExecutor.ThreadCommandExecutor, + threadCommands ?? (yield* ThreadCommandExecutor.make), + ), ), ), ), ); const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter); - return { run: importer.importRecentAgentThreads({ projectId }), published }; + return { + run: importer.importRecentAgentThreads({ projectId }), + importNativeHistory: importer.importNativeHistory, + published, + }; }); it.effect( @@ -282,6 +315,7 @@ it.effect( ); const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); unowned.thread.omittedMessageCount = 1; + unowned.worktree = { path: "/workspace/project/.claude/worktrees/feat", branch: "feat" }; const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); const importer = yield* makeImporter([ active, @@ -334,6 +368,8 @@ it.effect( expect(notices).toEqual([]); } expect(records.thread.historyOrigin).toBe("v1_import"); + expect(records.thread.worktreePath).toBe(source.worktree?.path ?? null); + expect(records.thread.branch).toBe(source.worktree?.branch ?? null); expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ @@ -342,12 +378,52 @@ it.effect( source.source.provider === "claudeAgent" ? { threadId, resume: source.source.providerSessionId } : { threadId: nativeId(source) }, - runtimePayload: { importedTranscripts: [source.source] }, + runtimePayload: { + cwd: source.worktree?.path ?? "/workspace/project", + importedTranscripts: [source.source], + }, }); } }).pipe(Effect.scoped, Effect.provide(persistence)), ); +it.effect("tolerates a missing transcript owner but propagates failed ownership reads", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const source = candidate(CODEX_MODEL_SELECTION, "ownership-read"); + const threadId = importId(source); + yield* runtimes.upsert({ + threadId: ThreadId.make("missing-owner"), + providerName: "codex", + providerInstanceId: source.source.providerInstanceId, + adapterKey: "codex", + runtimeMode: "full-access", + status: "stopped", + lastSeenAt: timestamp, + resumeCursor: null, + runtimePayload: { importedTranscripts: [source.source] }, + }); + yield* runtimes.recordImportedTranscript({ + threadId: ThreadId.make("missing-owner"), + source: source.source, + }); + const importer = yield* makeImporter([source]); + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + + yield* sql`UPDATE orchestration_v2_projection_threads SET payload_json = '{}' WHERE thread_id = ${threadId}`; + expect(yield* Effect.flip(importer.run)).toMatchObject({ + _tag: "AgentSessionScanError", + operation: "read-projects", + cause: { + _tag: "OrchestratorProjectionError", + threadId, + cause: { _tag: "ProjectionStoreReadError" }, + }, + }); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + it.effect("rechecks ownership after the import reaches the commit transaction", () => Effect.gen(function* () { const enteringTransaction = yield* Deferred.make(); @@ -407,8 +483,8 @@ it.effect( expect(yield* runtimes.list()).toEqual([]); yield* sql`DROP TRIGGER fail_runtime`; - expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); - expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual(committed); expect(importer.published).toHaveLength(6); expect( @@ -424,6 +500,438 @@ it.effect( }).pipe(Effect.scoped, Effect.provide(persistence)), ); +it.effect("counts only new threads when re-importing cached and recovered transcripts", () => + Effect.gen(function* () { + const events = yield* EventStore.EventStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const cached = candidate( + CLAUDE_MODEL_SELECTION, + "020e7f00-dce6-406b-8ec6-ed90498945d6", + "claudeAgent", + ); + const recovered = candidate(CODEX_MODEL_SELECTION, "recovered"); + const initial = yield* makeImporter([cached, recovered]); + expect(yield* initial.run).toEqual({ importedCount: 2, skippedCount: 0 }); + const before = yield* events.read({ threadId: importId(recovered) }).pipe(Stream.runCollect); + // The file changed on disk but still holds the imported messages. + recovered.source.size += 100; + recovered.source.mtimeMs += 1; + const duplicate = { ...recovered.source, filePath: "/tmp/duplicate.jsonl" }; + const fresh = candidate(CODEX_MODEL_SELECTION, "fresh"); + const repeated = yield* makeImporter([ + { _tag: "AlreadyImported", source: cached.source }, + recovered, + { _tag: "Duplicate", source: duplicate }, + fresh, + { _tag: "Skipped" }, + ]); + + expect(yield* repeated.run).toEqual({ importedCount: 1, skippedCount: 1 }); + expect(yield* events.read({ threadId: importId(recovered) }).pipe(Stream.runCollect)).toEqual( + before, + ); + expect( + new Set( + repeated.published.flatMap((stored) => ("event" in stored ? [stored.event.threadId] : [])), + ), + ).toEqual(new Set([importId(fresh)])); + expect( + Option.getOrThrow(yield* runtimes.getByThreadId({ threadId: importId(recovered) })), + ).toMatchObject({ + runtimePayload: { importedTranscripts: [recovered.source, duplicate] }, + }); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect("does not certify new native history after a partial import retry", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const original = candidate(CODEX_MODEL_SELECTION, "partial-retry"); + const threadId = importId(original); + const importer = yield* makeImporter([original]); + yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`; + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); + yield* sql`DROP TRIGGER fail_runtime`; + expect(yield* runtimes.list()).toEqual([]); + const continued = candidate(CODEX_MODEL_SELECTION, original.source.providerSessionId); + continued.source.size = 200; + continued.source.mtimeMs = 3; + continued.thread.messages.push( + { role: "user", text: "Continue outside T3", createdAt: timestamp }, + { role: "assistant", text: "Native continuation", createdAt: timestamp }, + ); + // The thread holds only the original messages, so the continued transcript stays unrecorded. + expect(yield* (yield* makeImporter([continued])).run).toEqual({ + importedCount: 0, + skippedCount: 1, + }); + expect(yield* runtimes.list()).toEqual([]); + expect( + (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( + (message) => message.text, + ), + ).toEqual(["Fix it", "Fixed"]); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect("does not record a changed transcript as imported without its new messages", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const first = candidate( + CLAUDE_MODEL_SELECTION, + "6f1c2a7e-3b4d-4e5f-9a8b-1c2d3e4f5a6b", + "claudeAgent", + ); + const threadId = importId(first); + expect(yield* (yield* makeImporter([first])).run).toEqual({ + importedCount: 1, + skippedCount: 0, + }); + + const continued = candidate( + CLAUDE_MODEL_SELECTION, + first.source.providerSessionId, + "claudeAgent", + ); + continued.source.size = 200; + continued.source.mtimeMs = 3; + continued.thread.messages.push( + { role: "user", text: "Continue", createdAt: timestamp }, + { role: "assistant", text: "Continued", createdAt: timestamp }, + ); + yield* (yield* makeImporter([continued])).run; + + const recorded = AgentSessionScanner.decodeImportedTranscriptPayload( + Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimePayload, + ).pipe(Option.getOrThrow).importedTranscripts; + const texts = (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( + (message) => message.text, + ); + expect({ + recordsChangedTranscript: recorded?.some((source) => source.size === 200) ?? false, + showsNewMessages: texts.includes("Continued"), + }).not.toEqual({ recordsChangedTranscript: true, showsNewMessages: false }); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect( + "copies native session history into the imported thread once, retrying a failed read", + () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const source = candidate(CODEX_MODEL_SELECTION, "native-history"); + const threadId = yield* seedOwner(source); + const resolved: Array = []; + const opened: Array = []; + let closed = false; + let failRead = true; + const replayed = (role: "user" | "assistant", text: string) => ({ + createdBy: role === "user" ? ("user" as const) : ("agent" as const), + creationSource: "provider" as const, + id: MessageId.make(`replayed:${text}`), + threadId, + runId: null, + nodeId: null, + role, + text, + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + }); + const adapter = { + openSession: (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) => + Effect.acquireRelease( + Effect.sync(() => { + opened.push(input); + return { + readThreadSnapshot: ({ providerThread }) => + failRead + ? Effect.fail( + new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({ + driver: providerThread.driver, + providerThreadId: providerThread.id, + }), + ) + : Effect.succeed({ + providerThread, + providerTurns: [], + runtimeRequests: [], + reasoningMessageIds: [MessageId.make("replayed:Check the build log")], + messages: [ + replayed("user", "Fix the build"), + replayed("assistant", "Check the build log"), + replayed("assistant", "Fixed it"), + replayed("assistant", " "), + ], + }), + } as Pick; + }), + () => + Effect.sync(() => { + closed = true; + }), + ), + } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; + const importer = yield* makeImporter([], Effect.void, (instanceId) => + Effect.sync(() => { + resolved.push(instanceId); + return adapter; + }), + ); + + const importHistory = importer.importNativeHistory({ + threadId, + workspaceRoot: "/workspace/project", + }); + + expect((yield* Effect.flip(importHistory))._tag).toBe( + "ProviderAdapterReadThreadSnapshotError", + ); + expect(closed).toBe(true); + expect( + (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin, + ).toBeUndefined(); + + failRead = false; + expect(yield* importHistory).toBe(3); + expect(resolved).toEqual([ + CODEX_MODEL_SELECTION.instanceId, + CODEX_MODEL_SELECTION.instanceId, + ]); + expect(opened[1]).toMatchObject({ + threadId, + initialNativeThreadId: source.source.providerSessionId, + runtimePolicy: { cwd: "/workspace/project" }, + }); + // Forks keep run-less history only for this origin. + expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe( + "v1_import", + ); + expect(yield* importHistory).toBe(0); + expect(opened).toHaveLength(2); + const page = yield* projections.getTimelinePage(threadId, { view: "activity", limit: 10 }); + expect( + page.items.map(({ item }) => [ + item.type, + item.runId, + "text" in item ? item.text : undefined, + ]), + ).toEqual([ + ["user_message", null, "Fix the build"], + ["reasoning", null, "Check the build log"], + ["assistant_message", null, "Fixed it"], + ]); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect("releases the ACP import lock when a native session never answers", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, "native-history-hang")); + const opened = yield* Deferred.make(); + let closed = false; + // An agent that only resumes sessions and never answers its first session/resume. + const adapter = { + openSession: () => + Effect.suspend(() => { + if (!closed) { + return Effect.addFinalizer(() => + Effect.sync(() => { + closed = true; + }), + ).pipe( + Effect.andThen(Deferred.succeed(opened, undefined)), + Effect.andThen(Effect.never), + ); + } + return Effect.succeed({ + readThreadSnapshot: ({ providerThread }) => + Effect.succeed({ + providerThread, + providerTurns: [], + runtimeRequests: [], + messages: [ + { + createdBy: "user", + creationSource: "provider", + id: MessageId.make("replayed:hang"), + threadId, + runId: null, + nodeId: null, + role: "user", + text: "Fix the build", + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + }), + } as Pick); + }), + } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; + const importer = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter)); + const importHistory = coordinator.withSessionMutation( + importer.importNativeHistory({ threadId, workspaceRoot: "/workspace/project" }), + ); + + const importing = yield* importHistory.pipe(Effect.flip, Effect.forkChild); + yield* Deferred.await(opened); + // Any other ACP import or delete waits for the same lock. + const next = yield* coordinator + .withSessionMutation(Effect.succeed("next")) + .pipe(Effect.forkChild); + yield* TestClock.adjust("2 minutes"); + + expect((yield* Fiber.join(importing))._tag).toBe("TimeoutError"); + expect(closed).toBe(true); + expect(yield* Fiber.join(next)).toBe("next"); + expect( + (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin, + ).toBeUndefined(); + expect(yield* importHistory).toBe(1); + expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe( + "v1_import", + ); + }).pipe( + Effect.scoped, + Effect.provide(Layer.merge(persistence, AcpRegistryRuntimeCoordinator.layer)), + ), +); + +/** + * Runs a thread command that read the thread before the history load ended and + * writes once the importer is about to commit, as an unserialized write would. + */ +const importDuringCommand = Effect.fn(function* ( + name: string, + command: (thread: OrchestrationV2AppThread) => ReadonlyArray, +) { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const sink = yield* EventSink.EventSinkV2; + const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, name)); + const lock = yield* ThreadCommandExecutor.make; + const loaded = yield* Deferred.make(); + const importerCommitting = yield* Deferred.make(); + const commandWritten = yield* Deferred.make(); + const committing = Deferred.succeed(importerCommitting, undefined); + const adapter = { + openSession: () => + Effect.succeed({ + readThreadSnapshot: ({ providerThread }) => + Deferred.await(loaded).pipe( + Effect.as({ + providerThread, + providerTurns: [], + runtimeRequests: [], + messages: [ + { + createdBy: "user" as const, + creationSource: "provider" as const, + id: MessageId.make(`replayed:${name}`), + threadId, + runId: null, + nodeId: null, + role: "user" as const, + text: "Fix the build", + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + }), + ), + } as Pick), + } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; + const importer = yield* makeImporter( + [], + committing.pipe(Effect.andThen(Deferred.await(commandWritten))), + () => Effect.succeed(adapter), + { + ...lock, + withLock: (key, effect) => committing.pipe(Effect.andThen(lock.withLock(key, effect))), + }, + ); + const commanding = yield* Effect.forkScoped( + lock.withLock( + threadId, + Effect.gen(function* () { + const { thread } = yield* projections.getThreadRecords(threadId, []); + yield* Deferred.succeed(loaded, undefined); + yield* Deferred.await(importerCommitting); + yield* sink.write({ events: command(thread) }); + yield* Deferred.succeed(commandWritten, undefined); + }), + ), + ); + const imported = yield* importer.importNativeHistory({ + threadId, + workspaceRoot: "/workspace/project", + }); + yield* Fiber.join(commanding); + const records = yield* projections.getThreadRecords(threadId, ["runs"]); + const page = yield* projections.getTimelinePage(threadId, { view: "messages", limit: 10 }); + return { imported, thread: records.thread, runs: records.runs, items: page.items }; +}); + +it.effect("keeps a thread edit made while the native history loads", () => + Effect.gen(function* () { + const result = yield* importDuringCommand("renamed-during-load", (thread) => [ + { + id: EventId.make(`${thread.id}:renamed`), + type: "thread.metadata-updated", + threadId: thread.id, + occurredAt: now, + payload: { ...thread, title: "Renamed" }, + }, + ]); + expect(result.imported).toBe(1); + expect(result.thread.title).toBe("Renamed"); + expect(result.thread.historyOrigin).toBe("v1_import"); + expect(result.items).toHaveLength(1); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect("skips the native history when a run starts while it loads", () => + Effect.gen(function* () { + const result = yield* importDuringCommand("run-during-load", (thread) => [ + { + id: EventId.make(`${thread.id}:run`), + type: "run.updated", + threadId: thread.id, + occurredAt: now, + payload: { + id: RunId.make(`${thread.id}:run`), + threadId: thread.id, + ordinal: 1, + providerInstanceId: thread.providerInstanceId, + modelSelection: thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make(`${thread.id}:prompt`), + rootNodeId: null, + activeAttemptId: null, + status: "queued", + requestedAt: now, + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }, + ]); + expect(result.imported).toBe(0); + expect(result.runs).toHaveLength(1); + expect(result.thread.historyOrigin).toBeUndefined(); + expect(result.items).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + it.effect("imports under a policy ceiling in the project's default, kept under the ceiling", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -433,6 +941,8 @@ it.effect("imports under a policy ceiling in the project's default, kept under t const importer = yield* makeImporter( [source], Effect.void, + undefined, + undefined, ServerSettings.layerTest( { defaultRuntimeMode: "full-access" }, { @@ -449,3 +959,95 @@ it.effect("imports under a policy ceiling in the project's default, kept under t ); }).pipe(Effect.scoped, Effect.provide(persistence)), ); + +it.effect("repeated imports reach linked-worktree sessions behind the scan budget", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-import-worktree-budget-" }); + const repo = path.join(root, "repo"); + const worktree = path.join(root, "feature"); + const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature"); + yield* fs.makeDirectory(worktreeGitDir, { recursive: true }); + yield* fs.makeDirectory(worktree); + yield* fs.writeFileString(path.join(repo, ".git", "config"), "[core]\n"); + yield* fs.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n"); + yield* fs.writeFileString(path.join(worktreeGitDir, "HEAD"), "ref: refs/heads/feature\n"); + yield* fs.writeFileString(path.join(worktree, ".git"), `gitdir: ${worktreeGitDir}\n`); + + const claudeHome = path.join(root, "claude"); + const codexHome = path.join(root, "codex"); + const sessions = path.join(codexHome, "sessions", "2026", "09", "01"); + yield* fs.makeDirectory(sessions, { recursive: true }); + const nowMs = DateTime.toEpochMillis(now); + yield* TestClock.setTime(nowMs); + // One more session than the 100-transcript scan budget, all run in the linked worktree. + for (let index = 0; index < 101; index++) { + const file = path.join(sessions, `rollout-${String(index).padStart(3, "0")}.jsonl`); + const records = [ + { type: "session_meta", payload: { id: `session-${index}`, cwd: worktree } }, + { type: "event_msg", payload: { type: "user_message", message: `Request ${index}` } }, + { + type: "response_item", + payload: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "Done" }], + }, + }, + ]; + yield* fs.writeFileString( + file, + records.map((record) => JSON.stringify(record) + "\n").join(""), + ); + const modifiedAtSeconds = nowMs / 1000 - (index + 1); + yield* fs.utimes(file, modifiedAtSeconds, modifiedAtSeconds); + } + + const scannerContext = yield* Layer.build( + AgentSessionScanner.layer.pipe( + Layer.provide( + Layer.mergeAll( + ServerConfig.layerTest(claudeHome, { prefix: "t3-import-budget-config-" }), + ServerSettings.layerTest({ + providerInstances: { + [ProviderInstanceId.make("claudeAgent")]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { homePath: claudeHome }, + }, + [ProviderInstanceId.make("codex")]: { + driver: ProviderDriverKind.make("codex"), + config: { homePath: codexHome }, + }, + // Keeps the default Pi instance off the developer's real ~/.pi. + [ProviderInstanceId.make("pi")]: { + driver: ProviderDriverKind.make("pi"), + enabled: false, + config: {}, + }, + }, + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Effect.succeed([]) }), + Layer.succeed( + ProviderSessionRuntime.ProviderSessionRuntimeRepository, + yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository, + ), + ), + ), + ), + ); + const importer = yield* makeImporter([], Effect.void, undefined, undefined, undefined, { + workspaceRoot: repo, + scanner: Context.get(scannerContext, AgentSessionScanner.AgentSessionScanner), + }); + + expect(yield* importer.run).toEqual({ importedCount: 100, skippedCount: 1 }); + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + const oldest = yield* ProjectionStore.ProjectionStoreV2.pipe( + Effect.flatMap((projections) => + projections.getThread(ThreadId.make("import:codex:session-100")), + ), + ); + expect(oldest.worktreePath).toBe(worktree); + }).pipe(Effect.scoped, Effect.provide(Layer.merge(persistence, NodeServices.layer))), +); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 211ad06fc2..0f8736986a 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -6,7 +6,6 @@ import { isRuntimeModeAbove, AgentSessionImportProjectChangedError, AgentSessionImportProjectNotFoundError, - AgentSessionImportSource, AgentSessionScanError, AgentSessionSource, EventId, @@ -36,20 +35,21 @@ import * as Stream from "effect/Stream"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as AgentSessionScanner from "./AgentSessionScanner.ts"; import * as ProjectService from "./ProjectService.ts"; +const isProjectionStoreThreadNotFoundError = Schema.is( + ProjectionStore.ProjectionStoreThreadNotFoundError, +); + const IMPORT_EVENT_PREFIX = "agent-session-import:v2"; const CLAUDE_SESSION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; -const decodeImportedTranscriptPayload = Schema.decodeUnknownOption( - Schema.Struct({ - cwd: Schema.optional(Schema.String), - importedTranscripts: Schema.optional(Schema.Array(AgentSessionImportSource)), - }), -); class AgentSessionUnresumableSessionError extends Schema.TaggedError()( "AgentSessionUnresumableSessionError", @@ -85,14 +85,34 @@ class AgentSessionThreadModifiedError extends Schema.TaggedError & { + readonly role: AgentSessionScanner.AgentSessionThreadMessage["role"] | "reasoning"; +}; + function messageEvents(input: { readonly threadId: ThreadId; readonly index: number; - readonly message: AgentSessionScanner.AgentSessionThreadMessage; + readonly message: HistoryMessage; }): ReadonlyArray { const ordinal = input.index + 1; const suffix = String(input.index).padStart(6, "0"); @@ -101,20 +121,6 @@ function messageEvents(input: { `${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`, ); const at = dateTime(input.message.createdAt); - const message: OrchestrationV2ConversationMessage = { - createdBy: input.message.role === "user" ? "user" : "agent", - creationSource: "server", - id: messageId, - threadId: input.threadId, - runId: null, - nodeId: null, - role: input.message.role, - text: input.message.text, - attachments: [], - streaming: false, - createdAt: at, - updatedAt: at, - }; const common = { id: turnItemId, threadId: input.threadId, @@ -131,6 +137,32 @@ function messageEvents(input: { completedAt: at, updatedAt: at, }; + const turnItemEvent = (payload: OrchestrationV2TurnItem): OrchestrationV2DomainEvent => ({ + id: EventId.make(turnItemId), + type: "turn-item.updated", + threadId: input.threadId, + occurredAt: at, + payload, + }); + if (input.message.role === "reasoning") { + return [ + turnItemEvent({ ...common, type: "reasoning", text: input.message.text, streaming: false }), + ]; + } + const message: OrchestrationV2ConversationMessage = { + createdBy: input.message.role === "user" ? "user" : "agent", + creationSource: "server", + id: messageId, + threadId: input.threadId, + runId: null, + nodeId: null, + role: input.message.role, + text: input.message.text, + attachments: [], + streaming: false, + createdAt: at, + updatedAt: at, + }; const turnItem: OrchestrationV2TurnItem = input.message.role === "user" ? { @@ -158,13 +190,7 @@ function messageEvents(input: { occurredAt: at, payload: message, }, - { - id: EventId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`), - type: "turn-item.updated", - threadId: input.threadId, - occurredAt: at, - payload: turnItem, - }, + turnItemEvent(turnItem), ]; } @@ -175,6 +201,8 @@ const make = Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; + const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; const settingsService = yield* ServerSettings.ServerSettingsService; const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode; const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* ( @@ -219,18 +247,21 @@ const make = Effect.gen(function* () { (cause) => new AgentSessionScanError({ operation: "read-projects", cause }), ), ); - const completedSources = runtimeRows.flatMap((runtime) => { - const payload = decodeImportedTranscriptPayload(runtime.runtimePayload); - if ( - Option.isNone(payload) || - payload.value.cwd === undefined || - normalizeProjectPathForComparison(payload.value.cwd) !== - normalizeProjectPathForComparison(project.workspaceRoot) - ) { - return []; - } - return payload.value.importedTranscripts ?? []; - }); + // The thread's project owns its transcripts: a linked worktree import records the worktree as cwd. + const completedSources = (yield* Effect.forEach(runtimeRows, (runtime) => { + const imported = AgentSessionScanner.decodeImportedTranscriptPayload( + runtime.runtimePayload, + ).pipe(Option.flatMapNullishOr((payload) => payload.importedTranscripts)); + if (Option.isNone(imported) || imported.value.length === 0) return Effect.succeed([]); + return orchestrator.getThreadRecords(runtime.threadId, []).pipe( + Effect.map(({ thread }) => (thread.projectId === input.projectId ? imported.value : [])), + Effect.catch((cause) => + isProjectionStoreThreadNotFoundError(cause.cause) + ? Effect.succeed([]) + : Effect.fail(new AgentSessionScanError({ operation: "read-projects", cause })), + ), + ); + })).flat(); const outcomes = scanner.recentThreads(project.workspaceRoot, completedSources); const importedThreadIds = new Set(); let importedCount = 0; @@ -248,7 +279,6 @@ const make = Effect.gen(function* () { ); if (outcome._tag === "AlreadyImported") { importedThreadIds.add(threadId); - importedCount += 1; return; } if (outcome._tag === "Duplicate") { @@ -286,11 +316,13 @@ const make = Effect.gen(function* () { thread.source === "claudeAgent" ? { threadId, resume: thread.providerSessionId } : { threadId: nativeThreadId }, - runtimePayload: { cwd: project.workspaceRoot }, + runtimePayload: { cwd: outcome.worktree?.path ?? project.workspaceRoot }, }, { onConflict: "ignore" }, ); - const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, [])); + const existing = yield* Effect.option( + orchestrator.getThreadRecords(threadId, ["messages"]), + ); if (Option.isSome(existing)) { if (existing.value.thread.projectId !== input.projectId) { return yield* new AgentSessionThreadProjectConflictError({ @@ -302,9 +334,23 @@ const make = Effect.gen(function* () { if (existing.value.thread.historyOrigin !== "v1_import") { return yield* new AgentSessionThreadModifiedError({ threadId }); } + // A transcript can change after the import, so record it only when the + // thread already holds exactly its messages. + const stored = existing.value.messages; + if ( + stored.length !== thread.messages.length || + stored.some( + (message, index) => + message.role !== thread.messages[index]?.role || + message.text !== thread.messages[index]?.text, + ) + ) { + return false; + } yield* persistRuntime; yield* runtimes.recordImportedTranscript({ threadId, source }); - return true; + importedThreadIds.add(threadId); + return null; } const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL; @@ -325,8 +371,8 @@ const make = Effect.gen(function* () { modelSelection: { instanceId: thread.providerInstanceId, model }, runtimeMode, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - branch: null, - worktreePath: null, + branch: outcome.worktree?.branch ?? null, + worktreePath: outcome.worktree?.path ?? null, linkedPullRequest: null, branchPullRequest: null, activeProviderThreadId: providerThreadId, @@ -452,7 +498,105 @@ const make = Effect.gen(function* () { return { importedCount, skippedCount } satisfies AgentSessionImportResult; }); - return { importRecentAgentThreads }; + /** + * Loading a native session replays its history only into the adapter's own + * snapshot, so copy that snapshot into the thread as run-less history. The + * `v1_import` origin keeps it in forks and marks the import done, so a call + * after a failed read repairs the thread and any later call does nothing. + */ + const importNativeHistory = Effect.fn("importNativeHistoryV2")(function* (input: { + readonly threadId: ThreadId; + readonly workspaceRoot: string; + }) { + const pendingThread = Effect.map( + orchestrator.getThreadRecords(input.threadId, ["providerThreads", "runs"]), + (records) => + isNativeHistoryPending({ + historyOrigin: records.thread.historyOrigin, + hasRun: records.runs.length > 0, + }) + ? records + : null, + ); + // Thread commands write whole thread rows, so hold their lock from the + // re-read through the write to keep both this marker and their changes. + const commit = (messages: ReadonlyArray) => + threadCommands.withLock( + input.threadId, + Effect.gen(function* () { + const current = yield* pendingThread; + if (current === null) return 0; + yield* eventSink.write({ + events: [ + ...messages.flatMap((message, index) => + messageEvents({ threadId: input.threadId, index, message }), + ), + { + id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${input.threadId}:native-history`), + type: "thread.metadata-updated", + threadId: input.threadId, + providerInstanceId: current.thread.providerInstanceId, + occurredAt: yield* DateTime.now, + payload: { ...current.thread, historyOrigin: "v1_import" }, + }, + ], + }); + return messages.length; + }), + ); + const records = yield* pendingThread; + if (records === null) return 0; + const { thread, providerThreads } = records; + const providerThread = providerThreads.find( + (candidate) => candidate.appThreadId === input.threadId && candidate.nativeThreadRef !== null, + ); + const nativeThreadId = providerThread?.nativeThreadRef?.nativeId; + if (providerThread === undefined || nativeThreadId == null) return 0; + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: providerThread.providerInstanceId, + threadId: input.threadId, + }); + // The registry admits this open against sign-in changes, like any other open. + const adapter = yield* registry.get(thread.modelSelection.instanceId); + const snapshot = yield* adapter + .openSession({ + threadId: input.threadId, + providerSessionId, + modelSelection: thread.modelSelection, + runtimePolicy: { + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + cwd: thread.worktreePath ?? input.workspaceRoot, + }, + initialNativeThreadId: nativeThreadId, + ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined + ? {} + : { + initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion, + }), + }) + .pipe( + Effect.flatMap((session) => session.readThreadSnapshot({ providerThread })), + Effect.timeout(NATIVE_HISTORY_READ_TIMEOUT), + Effect.scoped, + ); + const reasoningIds = new Set(snapshot.reasoningMessageIds); + const messages = snapshot.messages.flatMap((message) => + (message.role === "user" || message.role === "assistant") && message.text.trim() !== "" + ? [ + { + role: reasoningIds.has(message.id) ? ("reasoning" as const) : message.role, + text: message.text, + createdAt: DateTime.formatIso(message.createdAt), + }, + ] + : [], + ); + // Loading the session can take a while, and the thread is usable meanwhile. + return yield* commit(messages); + }); + + return { importRecentAgentThreads, importNativeHistory }; }); type AgentSessionImporterShape = Effect.Success; diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 6ab04f7e30..97a2e97e78 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -5,6 +5,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodeSqlite from "node:sqlite"; +import * as NodeZlib from "node:zlib"; import { describe, expect, it } from "@effect/vitest"; import { AgentSessionImportSource, @@ -13,6 +14,7 @@ import { ProviderDriverKind, ProviderInstanceId, type ServerSettings as ContractServerSettings, + ThreadId, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; @@ -31,6 +33,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as AgentSessionScanner from "./AgentSessionScanner.ts"; @@ -59,9 +62,33 @@ interface ScannerTestInput { readonly importedWorkspaceRoots?: ReadonlyArray; readonly configBaseDir?: string; readonly providerInstances?: ContractServerSettings["providerInstances"]; + readonly importedTranscripts?: { + readonly cwd: string; + readonly sources: ReadonlyArray; + }; readonly processRunner?: Layer.Layer; } +const layerRuntimeRepository = (imported: ScannerTestInput["importedTranscripts"]) => + Layer.mock(ProviderSessionRuntime.ProviderSessionRuntimeRepository)({ + list: () => + Effect.sync(() => + (imported?.sources ?? []).map((source): ProviderSessionRuntime.ProviderSessionRuntime => ({ + threadId: ThreadId.make( + `import:${source.providerInstanceId}:${source.providerSessionId}`, + ), + providerName: source.provider, + providerInstanceId: source.providerInstanceId, + adapterKey: source.provider, + runtimeMode: "full-access", + status: "stopped", + lastSeenAt: "2026-01-01T00:00:00.000Z", + resumeCursor: null, + runtimePayload: { cwd: imported?.cwd, importedTranscripts: [source] }, + })), + ), + }); + const layerScannerTest = (input: ScannerTestInput) => (input.processRunner === undefined ? AgentSessionScanner.layer @@ -103,6 +130,7 @@ const layerScannerTest = (input: ScannerTestInput) => input.configBaseDir ?? { prefix: "t3code-scanner-config-" }, ), layerProjectStore(input.importedWorkspaceRoots ?? []), + layerRuntimeRepository(input.importedTranscripts), ), ), ); @@ -147,6 +175,21 @@ const writeTranscript = Effect.fn("AgentSessionScanner.test.writeTranscript")(fu yield* fileSystem.utimes(input.filePath, seconds, seconds); }); +const writeCompressedTranscript = Effect.fn("AgentSessionScanner.test.writeCompressedTranscript")( + function* (input: { + readonly filePath: string; + readonly contents: string; + readonly mtimeMs: number; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fileSystem.makeDirectory(path.dirname(input.filePath), { recursive: true }); + yield* fileSystem.writeFile(input.filePath, NodeZlib.zstdCompressSync(input.contents)); + const seconds = input.mtimeMs / 1000; + yield* fileSystem.utimes(input.filePath, seconds, seconds); + }, +); + const claudeSessionLine = (cwd: string) => `${JSON.stringify({ type: "user", cwd, sessionId: "s1" })}\n${JSON.stringify({ type: "assistant" })}\n`; @@ -299,6 +342,30 @@ const awaitGateReader = (gatePath: string) => (handle) => Effect.promise(() => handle.close()), ); +/** + * Offers each of `filePaths` to `finished` once its `cat` child has exited. A + * deadline fires for every read still in flight, so a test must wait for the + * unblocked reads before it moves the clock. + */ +const layerReportingProcessRunner = ( + filePaths: ReadonlySet, + finished: Queue.Queue, +) => + Layer.effect( + ProcessRunner.ProcessRunner, + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + return ProcessRunner.ProcessRunner.of({ + run: (input) => { + const filePath = input.args.at(-1) ?? ""; + return filePaths.has(filePath) + ? runner.run(input).pipe(Effect.ensuring(Queue.offer(finished, filePath))) + : runner.run(input); + }, + }); + }), + ).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(NodeServices.layer)); + it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { describe("scan", () => { it.effect("reads Claude project cwds from transcripts, newest first", () => @@ -620,6 +687,118 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("finds the newest Claude sessions in a large home beside empty ones", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-large-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const recentWorkspace = yield* makeTempDir("t3code-workspace-recent-"); + const olderWorkspace = yield* makeTempDir("t3code-workspace-older-"); + // More project folders than the discovery budget reads, in an order unrelated to age. + const folderCount = 12_000; + const recentCount = 40; + const newestMs = Date.parse("2026-03-01T00:00:00.000Z"); + yield* Effect.sync(() => { + for (let index = 0; index < folderCount; index++) { + const age = (index * 7_919) % folderCount; + const directory = path.join(claudeHomePath, "projects", `-slug-${index}`); + const filePath = path.join(directory, `session-${index}.jsonl`); + const seconds = (newestMs - age * 60_000) / 1000; + NodeFS.mkdirSync(directory, { recursive: true }); + NodeFS.writeFileSync( + filePath, + claudeSessionLine(age < recentCount ? recentWorkspace : olderWorkspace), + ); + NodeFS.utimesSync(filePath, seconds, seconds); + NodeFS.utimesSync(directory, seconds, seconds); + } + }); + const emptyHomes = []; + for (let index = 0; index < 40; index++) { + emptyHomes.push([ + ProviderInstanceId.make(`claude-empty-${index}`), + { + driver: ProviderDriverKind.make("claudeAgent"), + config: { homePath: yield* makeTempDir(`t3code-claude-empty-${index}-`) }, + }, + ] as const); + } + + const result = yield* runScan({ + claudeHomePath, + codexHomePath, + providerInstances: Object.fromEntries(emptyHomes), + }); + + expect( + result.candidates.find((candidate) => candidate.path === recentWorkspace)?.threadCount, + ).toBe(recentCount); + }), + ); + + it.effect("passes budget a home frees while rescanning to the homes still short", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-empty-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const mediumHomePath = yield* makeTempDir("t3code-claude-medium-home-"); + const largeHomePath = yield* makeTempDir("t3code-claude-large-home-"); + const olderWorkspace = yield* makeTempDir("t3code-workspace-older-"); + const lastWorkspace = yield* makeTempDir("t3code-workspace-last-"); + const newestMs = Date.parse("2026-03-01T00:00:00.000Z"); + // Both homes outgrow their first share; together they fit the source's budget, but only + // when what the medium home leaves over on its rescan reaches the large one, which is + // listed first and so needs a second pass. + yield* Effect.sync(() => { + const writeSessions = (directory: string, count: number, cwd: string, ageMs: number) => { + NodeFS.mkdirSync(directory, { recursive: true }); + const seconds = (newestMs - ageMs) / 1000; + for (let index = 0; index < count; index++) { + const filePath = path.join(directory, `session-${index}.jsonl`); + NodeFS.writeFileSync(filePath, claudeSessionLine(cwd)); + NodeFS.utimesSync(filePath, seconds, seconds); + } + }; + writeSessions( + path.join(mediumHomePath, "projects", "-medium"), + 8_000, + olderWorkspace, + 60_000, + ); + writeSessions( + path.join(largeHomePath, "projects", "-bulk"), + 11_000, + olderWorkspace, + 60_000, + ); + // Read last because its folder is oldest, yet it holds the newest session. + const lastDirectory = path.join(largeHomePath, "projects", "-last"); + writeSessions(lastDirectory, 1, lastWorkspace, 0); + const oldSeconds = (newestMs - 3_600_000) / 1000; + NodeFS.utimesSync(lastDirectory, oldSeconds, oldSeconds); + }); + + const result = yield* runScan({ + claudeHomePath, + codexHomePath, + providerInstances: { + [ProviderInstanceId.make("claude-large")]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { homePath: largeHomePath }, + }, + [ProviderInstanceId.make("claude-medium")]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { homePath: mediumHomePath }, + }, + }, + }); + + expect( + result.candidates.find((candidate) => candidate.path === lastWorkspace)?.threadCount, + ).toBe(1); + }), + ); + it.effect("honors provider instance home directory environment variables", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -633,6 +812,8 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const codexWorkspace = yield* makeTempDir("t3code-workspace-codex-"); const piWorkspace = yield* makeTempDir("t3code-workspace-pi-"); const piFlatWorkspace = yield* makeTempDir("t3code-workspace-pi-flat-"); + const piInstanceHome = yield* makeTempDir("t3code-pi-instance-home-"); + const piHomeWorkspace = yield* makeTempDir("t3code-workspace-pi-home-"); // Pi nests sessions per cwd by default and keeps a custom session directory flat. for (const [filePath, cwd, mtime] of [ @@ -646,6 +827,11 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { piFlatWorkspace, "2026-01-04T00:00:00.000Z", ], + [ + path.join(piInstanceHome, "custom-pi", "sessions", "--slug--", "2026-01-05_pi.jsonl"), + piHomeWorkspace, + "2026-01-05T00:00:00.000Z", + ], ] as const) { yield* writeTranscript({ filePath, @@ -704,10 +890,22 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { ], config: {}, }, + [ProviderInstanceId.make("pi-home")]: { + driver: ProviderDriverKind.make("pi"), + enabled: true, + environment: [ + { name: "HOME", value: piInstanceHome, sensitive: false }, + { name: "USERPROFILE", value: piInstanceHome, sensitive: false }, + { name: "PI_CODING_AGENT_DIR", value: "~/custom-pi", sensitive: false }, + { name: "PI_CODING_AGENT_SESSION_DIR", value: "", sensitive: false }, + ], + config: {}, + }, }, }); expect(result.candidates.map((candidate) => [candidate.path, candidate.sources])).toEqual([ + [piHomeWorkspace, ["pi"]], [piFlatWorkspace, ["pi"]], [piWorkspace, ["pi"]], [codexWorkspace, ["codex"]], @@ -823,7 +1021,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("skips linked git worktrees and reports the origin of real checkouts", () => + it.effect("folds linked git worktrees into their checkout and reports real origins", () => Effect.gen(function* () { const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; @@ -859,8 +1057,56 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { path.join(submodule, ".git"), `gitdir: ${submoduleGitDir}\n`, ); + // A repository whose sessions all ran in a linked worktree is still offered. + const worktreeOnly = yield* makeTempDir("t3code-workspace-worktree-only-"); + const worktreeOnlyCheckout = yield* makeTempDir("t3code-workspace-worktree-only-wt-"); + const worktreeOnlyGitDir = path.join(worktreeOnly, ".git", "worktrees", "wt"); + yield* fileSystem.makeDirectory(worktreeOnlyGitDir, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(worktreeOnly, ".git", "config"), + '[remote "origin"]\n\turl = git@github.com:pingdotgg/other.git\n', + ); + yield* fileSystem.writeFileString(path.join(worktreeOnlyGitDir, "commondir"), "../..\n"); + yield* fileSystem.writeFileString( + path.join(worktreeOnlyCheckout, ".git"), + `gitdir: ${worktreeOnlyGitDir}\n`, + ); - for (const [index, cwd] of [repo, worktree, plain, noRemote, submodule].entries()) { + // Not offered: the config is unreadable, so the repository could be bare; and + // the main checkout is reached through a symlink into T3's own state. + const configBaseDir = yield* fileSystem.realPath( + yield* makeTempDir("t3code-scanner-base-"), + ); + const links = yield* makeTempDir("t3code-workspace-links-"); + const unknown = yield* makeTempDir("t3code-workspace-unknown-"); + yield* fileSystem.makeDirectory(path.join(configBaseDir, "state-repo")); + yield* fileSystem.symlink(path.join(configBaseDir, "state-repo"), path.join(links, "repo")); + const hiddenCheckouts: Array = []; + for (const [main, config] of [ + [unknown, null], + [path.join(links, "repo"), "[core]\n"], + ] as const) { + const gitDir = path.join(main, ".git", "worktrees", "wt"); + yield* fileSystem.makeDirectory(gitDir, { recursive: true }); + if (config !== null) { + yield* fileSystem.writeFileString(path.join(main, ".git", "config"), config); + } + yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n"); + const checkout = yield* makeTempDir("t3code-workspace-hidden-wt-"); + yield* fileSystem.writeFileString(path.join(checkout, ".git"), `gitdir: ${gitDir}\n`); + hiddenCheckouts.push(checkout); + } + + const sessionDirectories = [ + repo, + worktree, + plain, + noRemote, + submodule, + worktreeOnlyCheckout, + ...hiddenCheckouts, + ]; + for (const [index, cwd] of sessionDirectories.entries()) { yield* writeTranscript({ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"), contents: claudeSessionLine(cwd), @@ -868,23 +1114,34 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); } - const result = yield* runScan({ claudeHomePath, codexHomePath }); + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); expect( - result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })), + result.candidates.map((candidate) => ({ + path: candidate.path, + git: candidate.git, + threadCount: candidate.threadCount, + })), ).toEqual([ + { + path: worktreeOnly, + git: { remoteKey: "github.com/pingdotgg/other", repository: "pingdotgg/other" }, + threadCount: 1, + }, { path: submodule, git: { remoteKey: "gitlab.com/pingdotgg/libs/vendor", repository: "pingdotgg/libs/vendor", }, + threadCount: 1, }, - { path: noRemote, git: { remoteKey: null, repository: null } }, - { path: plain, git: null }, + { path: noRemote, git: { remoteKey: null, repository: null }, threadCount: 1 }, + { path: plain, git: null, threadCount: 1 }, { path: repo, git: { remoteKey: "github.com/pingdotgg/t3code", repository: "pingdotgg/t3code" }, + threadCount: 2, }, ]); }), @@ -959,6 +1216,70 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports a checkout's sessions from the linked worktrees the scan counts", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const repo = yield* makeTempDir("t3code-workspace-repo-"); + yield* fileSystem.makeDirectory(path.join(repo, ".git")); + yield* fileSystem.writeFileString(path.join(repo, ".git", "config"), "[core]\n"); + const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature"); + yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n"); + yield* fileSystem.writeFileString( + path.join(worktreeGitDir, "HEAD"), + "ref: refs/heads/feature\n", + ); + const worktree = path.join(repo, ".claude", "worktrees", "feature"); + yield* fileSystem.makeDirectory(worktree, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(worktree, ".git"), + `gitdir: ${worktreeGitDir}\n`, + ); + + for (const [index, [cwd, sessionId]] of [ + [repo, "at-root"], + [worktree, "in-worktree"], + ].entries()) { + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, `${sessionId}.jsonl`), + contents: `${JSON.stringify({ + type: "user", + cwd, + sessionId, + message: { role: "user", content: "Fix the project" }, + })}\n${JSON.stringify({ + type: "assistant", + sessionId, + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + })}\n`, + mtimeMs: nowMs - (index + 1) * 60 * 60 * 1000, + }); + } + + const input = { claudeHomePath, codexHomePath }; + const { candidates } = yield* runScan(input); + expect(candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: repo, threadCount: 2 }, + ]); + const outcomes = yield* runRecentThreadOutcomes({ ...input, workspaceRoot: repo }); + expect( + outcomes.flatMap((outcome) => + outcome._tag === "Importable" + ? [{ sessionId: outcome.thread.providerSessionId, worktree: outcome.worktree }] + : [], + ), + ).toEqual([ + { sessionId: "at-root", worktree: null }, + { sessionId: "in-worktree", worktree: { path: worktree, branch: "feature" } }, + ]); + }), + ); + it.effect("excludes sandboxes under the configured worktrees dir without .t3 in the path", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1115,6 +1436,32 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const result = yield* runScan({ claudeHomePath, codexHomePath }); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: workspace, threadCount: 1 }, + ]); + }), + ); + it.effect("discovers projects whose Codex rollouts are zstd-compressed", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + yield* writeCompressedTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "05", + "03", + "rollout-2026-05-03T00-00-00-019a5f00-0000-7000-8000-00000000000b.jsonl.zst", + ), + contents: codexRolloutLine(workspace), + mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath }); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ { path: workspace, threadCount: 1 }, ]); @@ -1123,6 +1470,66 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); describe("recentThreads", () => { + it.effect("imports Codex conversations stored only as zstd-compressed rollouts", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + yield* writeCompressedTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "20", + "rollout-2026-08-20T10-00-00-019a5f00-0000-7000-8000-00000000000c.jsonl.zst", + ), + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: "019a5f00-0000-7000-8000-00000000000c", cwd: workspace }, + }), + encodeTranscriptRecord({ + type: "event_msg", + timestamp: "2026-08-20T10:00:00.000Z", + payload: { type: "user_message", message: "Compressed prompt" }, + }), + encodeTranscriptRecord({ + type: "response_item", + timestamp: "2026-08-20T10:01:00.000Z", + payload: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "Compressed answer" }], + }, + }), + ].join("\n"), + mtimeMs: nowMs - 4 * 24 * 60 * 60 * 1000, + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect( + threads.map((thread) => ({ + id: thread.providerSessionId, + messages: thread.messages.map((message) => message.text), + })), + ).toEqual([ + { + id: "019a5f00-0000-7000-8000-00000000000c", + messages: ["Compressed prompt", "Compressed answer"], + }, + ]); + }), + ); + it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1619,16 +2026,20 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { null, { custom: "launcher" }, ]; + const fileSystem = yield* FileSystem.FileSystem; + // Rollouts imported before subagents were excluded still have import records. + const legacyImports: Array = []; for (const [index, source] of sources.entries()) { + const filePath = path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + `rollout-${index}.jsonl`, + ); yield* writeTranscript({ - filePath: path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - `rollout-${index}.jsonl`, - ), + filePath, contents: [ { type: "session_meta", payload: { id: `session-${index}`, cwd: workspace, source } }, // A later cwd must not make an excluded rollout eligible again. @@ -1642,6 +2053,21 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { .join("\n"), mtimeMs: nowMs - index * 60_000, }); + if (index >= 100) continue; + const stats = yield* fileSystem.stat(filePath); + legacyImports.push( + decodeImportSource({ + provider: "codex", + providerInstanceId: "codex", + providerSessionId: `session-${index}`, + filePath, + size: Number(stats.size), + mtimeMs: Option.getOrNull(Option.map(stats.mtime, (date) => date.getTime())), + device: Number(stats.dev), + inode: Option.getOrNull(Option.map(stats.ino, String)), + birthtimeMs: Option.getOrNull(Option.map(stats.birthtime, (date) => date.getTime())), + }), + ); } yield* Effect.gen(function* () { @@ -1654,7 +2080,15 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag, ), ).toEqual(["session-100", "session-101", "session-102", "session-103"]); - }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); + }).pipe( + Effect.provide( + layerScannerTest({ + claudeHomePath, + codexHomePath, + importedTranscripts: { cwd: workspace, sources: legacyImports }, + }), + ), + ); }), ); @@ -1702,6 +2136,144 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("ignores sessions without visible messages without spending the import budget", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const codexRollout = (name: string) => + path.join(codexHomePath, "sessions", "2026", "08", "24", `rollout-${name}.jsonl`); + // Newer empty sessions would exhaust the 100-transcript import budget before any real one. + const emptySessions = Array.from({ length: 100 }, (_, index) => + index % 2 === 0 + ? { + filePath: codexRollout(`empty-${index}`), + records: [ + { + type: "session_meta", + payload: { id: `codex-empty-${index}`, cwd: workspace, source: "vscode" }, + }, + { + type: "event_msg", + payload: { + type: "thread_settings_applied", + thread_settings: { cwd: workspace }, + }, + }, + ], + } + : { + filePath: path.join( + claudeHomePath, + "projects", + "-slug", + `claude-empty-${index}.jsonl`, + ), + records: [ + { type: "system", subtype: "informational", content: "Status", cwd: workspace }, + { + type: "user", + isMeta: true, + message: { + role: "user", + content: "Caveat", + }, + cwd: workspace, + }, + ], + }, + ); + const transcripts = [ + ...emptySessions, + { + // Without session_meta there is no resumable session ID. + filePath: codexRollout("unusable"), + records: [ + { type: "turn_context", payload: { cwd: workspace } }, + { + type: "event_msg", + payload: { type: "user_message", message: "Import this prompt" }, + }, + ], + }, + { + filePath: codexRollout("real"), + records: [ + { type: "session_meta", payload: { id: "real-session", cwd: workspace } }, + { + type: "event_msg", + payload: { type: "user_message", message: "Import this prompt" }, + }, + ], + }, + ]; + for (const [index, { filePath, records }] of transcripts.entries()) { + yield* writeTranscript({ + filePath, + contents: records.map((record) => encodeTranscriptRecord(record)).join("\n"), + mtimeMs: nowMs - index * 60_000, + }); + } + + const outcomes = yield* runRecentThreadOutcomes({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect( + outcomes.map((outcome) => + outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag, + ), + ).toEqual(["Skipped", "real-session"]); + }), + ); + + it.effect("skips a rewound Codex rollout whose inherited history is unavailable", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const threadId = "019a0000-0000-7000-8000-000000000001"; + const rolloutId = "019a0000-0000-7000-8000-000000000002"; + // The ancestor rollout is missing, and this rollout added no messages of its own. + yield* writeTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + `rollout-2026-08-24T11-00-00-${threadId}_${rolloutId}.jsonl`, + ), + contents: encodeTranscriptRecord({ + type: "session_meta", + payload: { + id: threadId, + cwd: workspace, + history_mode: "paginated", + history_base: { thread_id: threadId, end_ordinal_exclusive: 3, end_byte_offset: 512 }, + }, + }), + mtimeMs: nowMs, + }); + + const outcomes = yield* runRecentThreadOutcomes({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect(outcomes).toEqual([{ _tag: "Skipped" }]); + }), + ); + it.effect("skips excessive records without blocking an older valid transcript", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1790,6 +2362,123 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("repeated imports reach older transcripts behind already-imported ones", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-repeat-import-claude-"); + const codexHomePath = yield* makeTempDir("t3code-repeat-import-codex-"); + const workspace = yield* makeTempDir("t3code-repeat-import-workspace-"); + const sessionIds = Array.from( + { length: 102 }, + (_, index) => `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`, + ); + for (const [index, sessionId] of sessionIds.entries()) { + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "p", `${sessionId}.jsonl`), + // 999 cwd-less records cost 1,000 metadata records, so 100 newer transcripts + // exhaust MAX_METADATA_RECORDS_PER_SOURCE. + contents: + "{}\n".repeat(999) + + `${encodeTranscriptRecord({ + type: "user", + cwd: workspace, + sessionId, + timestamp: "2026-08-23T12:00:00.000Z", + message: { role: "user", content: `Prompt ${index}` }, + })}\n`, + mtimeMs: nowMs - (index + 1) * 60_000, + }); + } + + const completed: Array = []; + const imported = yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + while (true) { + const outcomes = yield* scanner + .recentThreads(workspace, completed) + .pipe(Stream.runCollect); + const added = Array.from(outcomes).flatMap((outcome) => + outcome._tag === "Importable" ? [outcome.source] : [], + ); + if (added.length === 0) return completed; + completed.push(...added); + } + }).pipe( + Effect.provide( + layerScannerTest({ + claudeHomePath, + codexHomePath, + importedTranscripts: { cwd: workspace, sources: completed }, + }), + ), + ); + + expect(imported.map((source) => source.providerSessionId).toSorted()).toEqual(sessionIds); + }), + ); + + it.effect("lists projects whose transcripts sit behind already-imported ones", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-hidden-project-claude-"); + const codexHomePath = yield* makeTempDir("t3code-hidden-project-codex-"); + const imported = yield* makeTempDir("t3code-hidden-project-imported-"); + const hidden = yield* makeTempDir("t3code-hidden-project-hidden-"); + const hiddenSessionId = "00000000-0000-4000-8000-000000000100"; + for (const index of Array.from({ length: 101 }, (_, value) => value)) { + const sessionId = `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`; + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "p", `${sessionId}.jsonl`), + contents: + "{}\n".repeat(999) + + `${encodeTranscriptRecord({ + type: "user", + cwd: index === 100 ? hidden : imported, + sessionId, + message: { role: "user", content: `Prompt ${index}` }, + })}\n`, + mtimeMs: nowMs - (index + 1) * 60_000, + }); + } + + const completed: Array = []; + const scans = yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const before = yield* scanner.scan; + const outcomes = yield* scanner.recentThreads(imported).pipe(Stream.runCollect); + const sources = Array.from(outcomes).flatMap((outcome) => + outcome._tag === "Importable" ? [outcome.source] : [], + ); + // A record whose file identity no longer matches must not lend its cwd. + const newest = sources[0]!; + completed.push(...sources, { + ...newest, + providerSessionId: hiddenSessionId, + filePath: path.join(claudeHomePath, "projects", "p", `${hiddenSessionId}.jsonl`), + }); + return { before, after: yield* scanner.scan }; + }).pipe( + Effect.provide( + layerScannerTest({ + claudeHomePath, + codexHomePath, + importedTranscripts: { cwd: imported, sources: completed }, + }), + ), + ); + + expect(scans.before.candidates.map((candidate) => candidate.path)).toEqual([imported]); + expect(scans.after.candidates.map((candidate) => candidate.path)).toEqual([ + imported, + hidden, + ]); + }), + ); + for (const source of ["claudeAgent", "codex"] as const) { for (const replacement of [ "same root", @@ -2034,6 +2723,95 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports long Claude history beyond the selected-history and record limits", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-long-conversation-claude-"); + const codexHomePath = yield* makeTempDir("t3code-long-conversation-codex-"); + const workspace = yield* makeTempDir("t3code-long-conversation-workspace-"); + const record = (fields: Record) => + encodeTranscriptRecord({ sessionId: "claude-long", ...fields }); + const longText = "x".repeat(64 * 1024); + const middleCount = 600; + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "claude-long.jsonl"), + contents: [ + record({ + type: "user", + cwd: workspace, + message: { role: "user", content: "First prompt" }, + }), + // 600 x 64 KiB exceeds the 32 MiB selected-history budget; the shown window fits. + ...Array.from({ length: middleCount }, (_, index) => { + const role = index % 2 === 0 ? "assistant" : "user"; + return record({ type: role, message: { role, content: longText } }); + }), + // Tool and progress records push the file past the 100,000-record limit. + ...Array.from({ length: 100_000 }, () => "{}"), + record({ type: "user", message: { role: "user", content: "Latest prompt" } }), + ].join("\n"), + mtimeMs: nowMs - 60_000, + }); + + const outcomes = yield* runRecentThreadOutcomes({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Importable"]); + const thread = outcomes[0]?._tag === "Importable" ? outcomes[0].thread : undefined; + expect(thread?.messages[0]).toMatchObject({ role: "user", text: "First prompt" }); + expect(thread?.messages.at(-1)).toMatchObject({ role: "user", text: "Latest prompt" }); + expect(thread?.messages).toHaveLength(200); + expect(thread?.omittedMessageCount).toBe(middleCount + 2 - 200); + }), + ); + + it.effect("imports a late first Claude prompt once when older replies are dropped", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-late-prompt-claude-"); + const codexHomePath = yield* makeTempDir("t3code-late-prompt-codex-"); + const workspace = yield* makeTempDir("t3code-late-prompt-workspace-"); + const contents = [ + encodeTranscriptRecord({ type: "attachment", sessionId: "late-prompt", cwd: workspace }), + // The first prompt is still among the latest 200 messages after older replies drop out. + ...Array.from({ length: 250 }, (_, index) => { + const role = index < 60 || index % 2 === 1 ? "assistant" : "user"; + return encodeTranscriptRecord({ + type: role, + sessionId: "late-prompt", + message: { role, content: `${role} ${index}` }, + }); + }), + ].join("\n"); + const filePath = path.join(claudeHomePath, "projects", "-slug", "late-prompt.jsonl"); + yield* writeTranscript({ filePath, contents, mtimeMs: nowMs - 60_000 }); + + const [thread] = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect(thread?.messages[0]).toMatchObject({ role: "assistant", text: "assistant 50" }); + expect(thread).toEqual( + AgentSessionScanner.parseAgentSessionTranscript({ + source: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + fallbackSessionId: "late-prompt", + lastActiveAtMs: nowMs - 60_000, + contents, + }), + ); + }), + ); + it.effect("skips growth during reading without exceeding the reserved bytes", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -2219,28 +2997,11 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( }); } - // The deadline fires for every read still in flight, so on a slow runner the - // neighbours' `cat` children must have exited before the clock moves. - const neighbourConfigs = new Set( - [repos[0], repos[2]].map((repo) => path.join(repo, ".git", "config")), - ); const finishedNeighbourReads = yield* Queue.unbounded(); - const processRunner = Layer.effect( - ProcessRunner.ProcessRunner, - Effect.gen(function* () { - const runner = yield* ProcessRunner.ProcessRunner; - return ProcessRunner.ProcessRunner.of({ - run: (input) => { - const filePath = input.args.at(-1) ?? ""; - return neighbourConfigs.has(filePath) - ? runner - .run(input) - .pipe(Effect.ensuring(Queue.offer(finishedNeighbourReads, filePath))) - : runner.run(input); - }, - }); - }), - ).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(NodeServices.layer)); + const processRunner = layerReportingProcessRunner( + new Set([repos[0], repos[2]].map((repo) => path.join(repo, ".git", "config"))), + finishedNeighbourReads, + ); for (let attempt = 1; attempt <= 2; attempt++) { const scan = yield* Effect.forkChild( @@ -2349,6 +3110,12 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( }); } + const finishedPointerReads = yield* Queue.unbounded(); + const processRunner = layerReportingProcessRunner( + new Set([path.join(worktree, ".git")]), + finishedPointerReads, + ); + // One scanner across scans: later scans skip the files that blocked. yield* Effect.gen(function* () { const scanner = yield* AgentSessionScanner.AgentSessionScanner; @@ -2357,22 +3124,24 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( ); const first = yield* Effect.forkChild(scanPaths); // Pointer files are read first, then the commondir files they lead to. - for (const gatePath of [ - path.join(pointerCheckout, ".git"), - path.join(worktreeGitDir, "commondir"), - ]) { - yield* Effect.scoped( - Effect.gen(function* () { - yield* awaitGateReader(gatePath); - yield* TestClock.adjust("2 seconds"); - }), - ); - } + yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(path.join(pointerCheckout, ".git")); + yield* Queue.take(finishedPointerReads); + yield* TestClock.adjust("2 seconds"); + }), + ); + yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(path.join(worktreeGitDir, "commondir")); + yield* TestClock.adjust("2 seconds"); + }), + ); expect(yield* Fiber.join(first)).toEqual([pointerCheckout]); for (let attempt = 2; attempt <= LIBUV_POOL_SIZE + 1; attempt++) { expect(yield* scanPaths, `scan ${attempt}`).toEqual([pointerCheckout]); } - }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); + }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath, processRunner }))); // Hangs if the scans left libuv pool threads stuck in open(). yield* fileSystem.readFileString(path.join(worktree, ".git")); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), @@ -2585,58 +3354,6 @@ describe("parseAgentSessionTranscript", () => { expect(thread?.title).toBe(expected); }); - it("drops injected Codex instructions while keeping the visible user event", () => { - const thread = AgentSessionScanner.parseAgentSessionTranscript({ - contents: [ - JSON.stringify({ type: "session_meta", payload: { id: "codex-session" } }), - JSON.stringify({ - type: "response_item", - payload: { - type: "message", - role: "user", - internal_chat_message_metadata_passthrough: { turn_id: "turn-1" }, - content: [ - { - type: "input_text", - text: "\nInternal setup instructions\n", - }, - ], - }, - }), - JSON.stringify({ - type: "event_msg", - payload: { type: "user_message", message: "Fix the actual bug" }, - }), - JSON.stringify({ - type: "response_item", - payload: { - type: "message", - role: "user", - internal_chat_message_metadata_passthrough: { turn_id: "turn-1" }, - content: [{ type: "input_text", text: "Fix the actual bug" }], - }, - }), - JSON.stringify({ - type: "response_item", - payload: { - type: "message", - role: "assistant", - content: [{ type: "output_text", text: "Fixed" }], - }, - }), - ].join("\n"), - source: "codex", - providerInstanceId: ProviderInstanceId.make("codex"), - fallbackSessionId: "fallback", - lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), - }); - - expect(thread?.messages.map((message) => message.text)).toEqual([ - "Fix the actual bug", - "Fixed", - ]); - }); - it.each([199, 200])("keeps the canonical first prompt with %s later Codex messages", (count) => { const canonicalPrompt = "\n Keep the canonical prompt \n"; const canonicalTimestamp = "2026-08-24T10:01:00.000Z"; @@ -3008,6 +3725,7 @@ describe("parseAgentSessionTranscript", () => { "\nGitHub\n", "# AGENTS.md instructions for /tmp/project\n\n\nRules\n", '\nTab\n', + '{"page_id":null}', "Fix the import titles", ].join("\n"); const thread = AgentSessionScanner.parseAgentSessionTranscript({ @@ -3028,6 +3746,48 @@ describe("parseAgentSessionTranscript", () => { expect(thread?.messages.map((message) => message.text)).toEqual([prompt]); }); + it("titles a Claude session after the prompt inside a wake envelope", () => { + const thread = AgentSessionScanner.parseAgentSessionTranscript({ + contents: JSON.stringify({ + type: "user", + sessionId: "claude-session", + timestamp: "2026-08-25T08:00:00.000Z", + message: { + role: "user", + content: + '\nFix the flaky login test\n', + }, + }), + source: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + fallbackSessionId: "fallback", + lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"), + }); + + expect(thread?.title).toBe("Fix the flaky login test"); + }); + + it.each([ + "Explain in this transcript", + "Keep this incomplete example", + ])("keeps Codex page markup that is not a complete leading block: %s", (prompt) => { + const thread = AgentSessionScanner.parseAgentSessionTranscript({ + contents: [ + encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: prompt }, + }), + ].join("\n"), + source: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), + fallbackSessionId: "fallback", + lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"), + }); + + expect(thread?.title).toBe(prompt); + }); + it("skips sessions without a visible user message", () => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ contents: JSON.stringify({ diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 1b32de22a8..c1f42586b2 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1,14 +1,15 @@ import * as NodeOS from "node:os"; import * as NodeSqlite from "node:sqlite"; +import * as NodeZlib from "node:zlib"; import { + AgentSessionImportSource, AgentSessionScanError, ClaudeSettings, CodexSettings, ProviderDriverKind, ProviderInstanceId, resolveProviderInstanceEnabled, - type AgentSessionImportSource, type AgentSessionProjectCandidate, type AgentSessionProjectGit, type AgentSessionScanResult, @@ -17,11 +18,13 @@ import { import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as NodeStream from "@effect/platform-node/NodeStream"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Pull from "effect/Pull"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -34,10 +37,11 @@ import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; -import { resolvePiSessionsDir } from "@t3tools/provider-pi/server/usage"; +import { piHome, resolvePiSessionsDir } from "@t3tools/provider-pi/server/usage"; import * as ServerSettings from "../serverSettings.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { @@ -165,12 +169,22 @@ const decodePiEntryLinks = Schema.decodeUnknownOption( ); const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord); const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata); +export const decodeImportedTranscriptPayload = Schema.decodeUnknownOption( + Schema.Struct({ + cwd: Schema.optional(Schema.String), + importedTranscripts: Schema.optional(Schema.Array(AgentSessionImportSource)), + }), +); const decodeCodexHistoryBase = Schema.decodeUnknownOption( Schema.Struct({ thread_id: Schema.String, end_byte_offset: Schema.Number }), ); // Original rollouts end in their thread ID, rewound ones in `_`. const CODEX_ROLLOUT_ID_PATTERN = - /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl$/i; + /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl(?:\.zst)?$/i; +// Codex zstd-compresses older rollouts; their byte limits and offsets count decompressed bytes. +const COMPRESSED_TRANSCRIPT_SUFFIX = ".jsonl.zst"; +const isCompressedTranscript = (filePath: string) => + filePath.endsWith(COMPRESSED_TRANSCRIPT_SUFFIX); // Codex records a chat's project only here; moving a chat leaves its rollout cwd unchanged. const CODEX_STATE_DATABASE = "state_5.sqlite"; const decodeCodexSessionIndexEntry = Schema.decodeUnknownOption( @@ -209,6 +223,8 @@ export type AgentSessionRecentThread = readonly _tag: "Importable"; readonly thread: AgentSessionThread; readonly source: AgentSessionImportSource; + /** The root's linked worktree the session ran in, or null when it ran in the root. */ + readonly worktree: { readonly path: string; readonly branch: string | null } | null; } | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource } | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource } @@ -246,7 +262,7 @@ interface TranscriptCandidate { readonly mtimeMs: number; readonly providerInstanceId: ProviderInstanceId; readonly homePath: string; - readonly size: number; + readonly identity: TranscriptIdentity; readonly projectRoots?: ReadonlyArray | undefined; } @@ -257,6 +273,13 @@ interface MetadataReadBudget { truncated: boolean; } +function splitOperationBudget(budget: number, count: number): Array { + return Array.from( + { length: count }, + (_, index) => Math.floor(budget / count) + (index < budget % count ? 1 : 0), + ); +} + function selectMetadataTranscripts(transcripts: ReadonlyArray) { const selected: Array = []; let pending = Array.from( @@ -353,7 +376,7 @@ function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord) // Codex records setup context as user text ahead of the real request. Skip // these leading blocks when deriving a title; imported messages keep them. const CODEX_TITLE_PREAMBLE = - /^(?:\s*(?:<(recommended_plugins|environment_context|user_instructions|INSTRUCTIONS|in-app-browser-context)(?:\s[^>]*)?>[\s\S]*?<\/\1>|# AGENTS\.md instructions\b[^\n]*|## My request for Codex:))+/; + /^(?:\s*(?:<(recommended_plugins|environment_context|user_instructions|INSTRUCTIONS|in-app-browser-context|external_codex_apps_open_page)(?:\s[^>]*)?>[\s\S]*?<\/\1>|# AGENTS\.md instructions\b[^\n]*|## My request for Codex:))+/; // Codex appends an entry per rename; like Codex, the newest nonempty name wins. function parseCodexThreadNames(contents: string): ReadonlyMap { @@ -381,8 +404,15 @@ function codexHistoryBase(records: ReadonlyArray) { : undefined; } +// Agent-started sessions wrap the prompt in a `` +// envelope; title them after the prompt inside it. +const WAKE_ENVELOPE = /^\s*]*)?>([\s\S]*?)(?:<\/wake>|$)/; + function deriveTitle(source: AgentSessionSource, text: string): string | undefined { - const request = source === "codex" ? text.replace(CODEX_TITLE_PREAMBLE, "") : text; + const request = (source === "codex" ? text.replace(CODEX_TITLE_PREAMBLE, "") : text).replace( + WAKE_ENVELOPE, + "$1", + ); return request.trim().split("\n")[0]?.slice(0, 100).trim() || undefined; } @@ -431,14 +461,16 @@ export function parseAgentSessionTranscript( input.source === "claudeAgent" ? records.reduce(foldClaudeFields, emptyClaudeFields) : emptyClaudeFields; - return parseAgentSessionRecords(input, records, claudeFields); + const thread = parseAgentSessionRecords(input, records, claudeFields, 0); + return thread === "empty" ? null : thread; } function parseAgentSessionRecords( input: AgentSessionTranscriptMetadata, records: ReadonlyArray, claudeFields: ClaudeFields, -): AgentSessionThread | null { + droppedMessageCount: number, +): AgentSessionThread | "empty" | null { const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs)); // Claude filenames are session IDs. Codex rollout filenames include extra // timestamp text, so only transcript metadata can provide a resumable ID. @@ -631,6 +663,7 @@ function parseAgentSessionRecords( }); } + if (messages.length === 0 && droppedMessageCount === 0) return "empty"; const visibleMessages = messages.map( ({ codexResponseUser: _codexResponseUser, ...message }) => message, ); @@ -650,7 +683,7 @@ function parseAgentSessionRecords( createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp, updatedAt: fallbackTimestamp, messages: retainedMessages, - omittedMessageCount: conversationMessageCount - retainedMessages.length, + omittedMessageCount: conversationMessageCount + droppedMessageCount - retainedMessages.length, }; } @@ -687,6 +720,31 @@ function shouldRetainDecodedRecord( ); } +// The import shows only the first user message and the latest messages, so a +// long Claude session holds just those and counts the rest as dropped. +function createClaudeHistoryWindow() { + const recent: Array<{ readonly record: DecodedTranscriptRecord; readonly bytes: number }> = []; + let firstUser: DecodedTranscriptRecord | undefined; + let droppedMessageCount = 0; + return { + // Takes a record shouldRetainDecodedRecord kept; returns the bytes it released. + push: (record: DecodedTranscriptRecord, bytes: number): number => { + if (firstUser === undefined && record.type === "user") firstUser = record; + recent.push({ record, bytes }); + if (recent.length <= MAX_IMPORTED_MESSAGES) return 0; + const evicted = recent.shift(); + if (evicted === undefined || evicted.record === firstUser) return 0; + droppedMessageCount += 1; + return evicted.bytes; + }, + records: () => { + const held = recent.map((entry) => entry.record); + return firstUser === undefined || held.includes(firstUser) ? held : [firstUser, ...held]; + }, + droppedMessageCount: () => droppedMessageCount, + }; +} + function normalizeForWorktreeMatch(value: string, caseFold: boolean): string { const normalized = `${value.replaceAll("\\", "/")}/`; return caseFold ? normalized.toLowerCase() : normalized; @@ -788,9 +846,11 @@ export const make = Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; const serverSettings = yield* ServerSettings.ServerSettingsService; const projectStore = yield* ProjectStore.ProjectStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; const baseDir = path.resolve(serverConfig.baseDir); const worktreesDir = path.resolve(serverConfig.worktreesDir); - const isWindows = (yield* HostProcess.Platform) === "win32"; + const platform = yield* HostProcess.Platform; + const isWindows = platform === "win32"; const foldWorktreeCase = isWindows; const hostEnvironment = yield* HostProcess.Environment; const homeDir = yield* HostProcess.HomeDirectory; @@ -823,6 +883,33 @@ export const make = Effect.gen(function* () { const statOption = (target: string) => fileSystem.stat(target).pipe(Effect.asSome, Effect.orElseSucceed(Option.none)); + const transcriptChunkReader = Effect.fn("AgentSessionScanner.transcriptChunkReader")(function* ( + file: FileSystem.File, + filePath: string, + ) { + if (!isCompressedTranscript(filePath)) return (size: number) => file.readAlloc(size); + const pull = yield* Stream.toPull( + fileSystem + .stream(filePath) + .pipe(NodeStream.pipeThroughSimple(() => NodeZlib.createZstdDecompress())), + ); + let pending: Array = []; + let done = false; + // Untraced: called once per chunk inside the caller's traced read. + return Effect.fnUntraced(function* (size: number) { + while (pending.length === 0) { + if (done) return Option.none(); + const next = yield* pull.pipe(Pull.catchDone(() => Effect.undefined)); + if (next === undefined) done = true; + else pending = [...next]; + } + const chunk = pending.shift(); + if (chunk === undefined) return Option.none(); + if (chunk.byteLength > size) pending.unshift(chunk.subarray(size)); + return Option.some(chunk.subarray(0, size)); + }); + }); + const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* ( target: string, knownStats?: FileSystem.File.Info, @@ -838,6 +925,20 @@ export const make = Effect.gen(function* () { return `path:${normalizeProjectPathForComparison(realPath)}`; }); + /** Stats a directory that may be offered as a project, or none when it is missing or excluded. */ + const projectDirectoryStats = Effect.fn("AgentSessionScanner.projectDirectoryStats")(function* ( + directory: string, + ) { + if (isExcludedProjectPath(directory)) return Option.none(); + const stats = yield* statOption(directory); + if (Option.isNone(stats) || stats.value.type !== "Directory") return Option.none(); + const realPath = yield* fileSystem + .realPath(directory) + .pipe(Effect.orElseSucceed(() => directory)); + // Symlinks can disguise excluded worktree paths; re-check their targets. + return isExcludedProjectPath(realPath) ? Option.none() : stats; + }); + // Paths whose own read outlived the deadline, mapped to when they may be read // again. Without this every later scan would wait out the deadline again for // each phase that touches them. @@ -891,17 +992,26 @@ export const make = Effect.gen(function* () { ) { type GitIdentity = | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null } - | { readonly _tag: "Worktree" } + | { + readonly _tag: "Worktree"; + readonly gitDir: string; + readonly mainCheckout: string | null; + readonly git: AgentSessionProjectGit | null; + } | { readonly _tag: "NotGit" }; const identities = new Map(); - const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = []; + const repositories: Array<{ + directory: string; + gitDir: string; + worktreeGitDir: string | null; + }> = []; const pointers: Array<{ directory: string; gitPath: string }> = []; for (const directory of directories) { const gitPath = path.join(directory, ".git"); const gitStats = yield* statOption(gitPath); if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" }); else if (gitStats.value.type === "Directory") { - repositories.push({ directory, gitDir: gitPath, linkedWorktree: false }); + repositories.push({ directory, gitDir: gitPath, worktreeGitDir: null }); } else pointers.push({ directory, gitPath }); } @@ -916,7 +1026,7 @@ export const make = Effect.gen(function* () { const gitDir = path.resolve(directory, target); if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) { linkedWorktrees.push({ directory, gitDir }); - } else repositories.push({ directory, gitDir, linkedWorktree: false }); + } else repositories.push({ directory, gitDir, worktreeGitDir: null }); } const commonDirTexts = yield* readGitFiles( @@ -924,44 +1034,106 @@ export const make = Effect.gen(function* () { ); for (const { directory, gitDir } of linkedWorktrees) { const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim(); - if (commonDir.length === 0) identities.set(directory, { _tag: "Worktree" }); - else + if (commonDir.length === 0) { + identities.set(directory, { _tag: "Worktree", gitDir, mainCheckout: null, git: null }); + } else repositories.push({ directory, gitDir: path.resolve(gitDir, commonDir), - linkedWorktree: true, + worktreeGitDir: gitDir, }); } const configTexts = yield* readGitFiles( repositories.map(({ gitDir }) => path.join(gitDir, "config")), ); - for (const { directory, gitDir, linkedWorktree } of repositories) { + for (const { directory, gitDir, worktreeGitDir } of repositories) { const configText = configTexts.get(path.join(gitDir, "config")) ?? ""; + const originUrl = parseOriginUrlFromGitConfig(configText); + const git: AgentSessionProjectGit = { + remoteKey: + originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl), + repository: repositoryPathFromRemoteUrl(originUrl), + }; // Bare repositories have no main checkout, so offer their linked worktrees independently. - if (linkedWorktree && !isBareGitConfig(configText)) { - identities.set(directory, { _tag: "Worktree" }); + if (worktreeGitDir !== null && !isBareGitConfig(configText)) { + identities.set(directory, { + _tag: "Worktree", + gitDir: worktreeGitDir, + // Only a common dir named .git sits inside its main checkout, and an + // unreadable config can't rule out a bare repository. + mainCheckout: + configText.length > 0 && path.basename(gitDir) === ".git" ? path.dirname(gitDir) : null, + git, + }); continue; } - const originUrl = parseOriginUrlFromGitConfig(configText); - identities.set(directory, { - _tag: "Repository", - git: { - remoteKey: - originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl), - repository: repositoryPathFromRemoteUrl(originUrl), - }, - }); + identities.set(directory, { _tag: "Repository", git }); } return identities; }); + /** Maps each directory to the project it counts toward: a linked worktree counts toward its main checkout. */ + const resolveDirectoryProjects = Effect.fn("AgentSessionScanner.resolveDirectoryProjects")( + function* (resolvedDirectories: ReadonlyArray) { + // Stat every directory first so one batch reads all git identities. + const directories = new Map>(); + for (const resolved of resolvedDirectories) { + if (directories.has(resolved)) continue; + directories.set(resolved, yield* projectDirectoryStats(resolved)); + } + const directoryGitIdentities = yield* readGitIdentities( + Array.from(directories).flatMap(([directory, stats]) => + Option.isSome(stats) ? [directory] : [], + ), + ); + const projects = new Map< + string, + { + readonly key: string; + readonly path: string; + readonly git: AgentSessionProjectGit | null; + readonly worktreeGitDir: string | null; + } | null + >(); + for (const [resolved, stats] of directories) { + const gitIdentity = directoryGitIdentities.get(resolved); + if (Option.isNone(stats) || gitIdentity === undefined) { + projects.set(resolved, null); + } else if (gitIdentity._tag === "Worktree") { + const { mainCheckout } = gitIdentity; + const mainStats = + mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout); + projects.set( + resolved, + mainCheckout !== null && Option.isSome(mainStats) + ? { + key: yield* directoryIdentity(mainCheckout, mainStats.value), + path: mainCheckout, + git: gitIdentity.git, + worktreeGitDir: gitIdentity.gitDir, + } + : null, + ); + } else { + projects.set(resolved, { + key: yield* directoryIdentity(resolved, stats.value), + path: resolved, + git: gitIdentity._tag === "Repository" ? gitIdentity.git : null, + worktreeGitDir: null, + }); + } + } + return projects; + }, + ); + const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* ( source: AgentSessionSource, transcript: TranscriptCandidate, budget: MetadataReadBudget, ) { - if (transcript.size === 0) return null; + if (transcript.identity.size === 0) return null; if ( budget.bytesRemaining === 0 || budget.operationsRemaining < 2 || @@ -975,11 +1147,15 @@ export const make = Effect.gen(function* () { fileSystem.open(transcript.filePath, { flag: "r" }).pipe( Effect.flatMap((file) => Effect.gen(function* () { + const readChunk = yield* transcriptChunkReader(file, transcript.filePath); + const size = isCompressedTranscript(transcript.filePath) + ? Number.POSITIVE_INFINITY + : transcript.identity.size; const decoder = new TextDecoder(); let remaining = ""; let bytesRead = 0; let recordsRead = 0; - const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, transcript.size); + const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); const reserveRecord = () => { if ( recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT || @@ -1011,7 +1187,7 @@ export const make = Effect.gen(function* () { ); budget.operationsRemaining -= 1; budget.bytesRemaining -= readSize; - const next = yield* file.readAlloc(readSize); + const next = yield* readChunk(readSize); if (Option.isNone(next)) { return readLastRecord(); } @@ -1028,7 +1204,7 @@ export const make = Effect.gen(function* () { } } - if (bytesRead < transcript.size) { + if (bytesRead < size) { budget.truncated = true; return null; } @@ -1045,8 +1221,12 @@ export const make = Effect.gen(function* () { source: AgentSessionSource, prefix?: { readonly endByteOffset: number; readonly historyBytes: number }, ) { - const readBytes = prefix?.endByteOffset ?? expected.size; - if (readBytes > expected.size || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) return null; + const compressed = isCompressedTranscript(filePath); + const readBytes = + prefix?.endByteOffset ?? (compressed ? MAX_IMPORTED_TRANSCRIPT_BYTES : expected.size); + if ((!compressed && readBytes > expected.size) || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) { + return null; + } return yield* Effect.scoped( fileSystem.open(filePath, { flag: "r" }).pipe( @@ -1055,7 +1235,9 @@ export const make = Effect.gen(function* () { if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) { return null; } + const readChunk = yield* transcriptChunkReader(file, filePath); const records: Array = []; + const claudeHistory = createClaudeHistoryWindow(); let cwd = Option.none(); let claudeFields = emptyClaudeFields; let historyBytes = prefix?.historyBytes ?? 0; @@ -1077,7 +1259,8 @@ export const make = Effect.gen(function* () { const finishRecord = () => { reader.write(decoder.decode()); recordCount += 1; - if (recordCount > MAX_IMPORT_RECORDS) return false; + // Claude keeps a bounded window, so only the byte budgets limit its length. + if (recordCount > MAX_IMPORT_RECORDS && source !== "claudeAgent") return false; const value = reader.finish(); const decoded = decodeTranscriptValue(value); if (Option.isNone(decoded) && source === "pi") { @@ -1089,7 +1272,9 @@ export const make = Effect.gen(function* () { claudeFields = foldClaudeFields(claudeFields, decoded.value); } if (shouldRetainDecodedRecord(source, decoded.value)) { - if ( + if (source === "claudeAgent") { + historyBytes += recordBytes - claudeHistory.push(decoded.value, recordBytes); + } else if ( source === "pi" && decoded.value.type === "message" && !isPiConversationRecord(decoded.value) @@ -1111,10 +1296,12 @@ export const make = Effect.gen(function* () { }; while (bytesRead < readBytes) { - const next = yield* file.readAlloc( + const next = yield* readChunk( Math.min(TRANSCRIPT_PREFIX_BYTES, readBytes - bytesRead), ); if (Option.isNone(next)) { + // A compressed rollout's decompressed length is only known at its end. + if (compressed && prefix === undefined) break; return null; } @@ -1147,7 +1334,13 @@ export const make = Effect.gen(function* () { ) return null; return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat)) - ? { records, cwd, claudeFields, historyBytes } + ? { + records: source === "claudeAgent" ? claudeHistory.records() : records, + droppedMessageCount: claudeHistory.droppedMessageCount(), + cwd, + claudeFields, + historyBytes, + } : null; }), ), @@ -1209,7 +1402,35 @@ export const make = Effect.gen(function* () { operationsRemaining -= 1; return listDirectory(directory); }; - const projectDirectories = yield* readDirectory(projectsDir); + // Folder names carry no date, so read the newest folders first: a budget that runs out + // then drops the oldest sessions. Dating has its own allowance, apart from the reads. + let datesRemaining = operationBudget; + const dated: Array<{ readonly name: string; readonly mtimeMs: number }> = []; + const undated: Array = []; + for (const name of yield* readDirectory(projectsDir)) { + if (datesRemaining <= 0) { + undated.push(name); + continue; + } + datesRemaining -= 1; + const stats = yield* statOption(path.join(projectsDir, name)); + if (Option.isNone(stats) || stats.value.type !== "Directory") continue; + dated.push({ + name, + mtimeMs: Option.match(stats.value.mtime, { + onNone: () => 0, + onSome: (mtime) => mtime.getTime(), + }), + }); + } + const projectDirectories = [ + ...dated + .toSorted( + (left, right) => right.mtimeMs - left.mtimeMs || left.name.localeCompare(right.name), + ) + .map((entry) => entry.name), + ...undated, + ]; const transcripts: Array = []; for (const projectDirectory of projectDirectories) { @@ -1241,11 +1462,11 @@ export const make = Effect.gen(function* () { mtimeMs: stats.value.mtime.value.getTime(), providerInstanceId, homePath, - size: Number(stats.value.size), + identity: transcriptIdentity(filePath, stats.value), }); } } - return { transcripts, truncated }; + return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining }; }, ); @@ -1326,7 +1547,12 @@ export const make = Effect.gen(function* () { } const directory = path.join(sessionsDir, year, month, day); for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) { - if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue; + if ( + !entry.startsWith("rollout-") || + !(entry.endsWith(".jsonl") || isCompressedTranscript(entry)) + ) { + continue; + } if (operationsRemaining <= 0) { truncated = true; break; @@ -1344,7 +1570,7 @@ export const make = Effect.gen(function* () { mtimeMs: stats.value.mtime.value.getTime(), providerInstanceId, homePath, - size: Number(stats.value.size), + identity: transcriptIdentity(filePath, stats.value), }); } } @@ -1359,6 +1585,7 @@ export const make = Effect.gen(function* () { return roots === undefined ? transcript : { ...transcript, projectRoots: roots }; }), truncated, + operationsUsed: operationBudget - operationsRemaining, }; }, ); @@ -1409,18 +1636,22 @@ export const make = Effect.gen(function* () { mtimeMs: stats.value.mtime.value.getTime(), providerInstanceId, homePath: sessionsDir, - size: Number(stats.value.size), + identity: transcriptIdentity(filePath, stats.value), }); } } } - return { transcripts, truncated }; + return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining }; }); const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* ( source: AgentSessionSource, transcripts: ReadonlyArray, budget: MetadataReadBudget, + importedByFile: ReadonlyMap< + string, + ReadonlyArray<{ readonly cwd: string; readonly source: AgentSessionImportSource }> + >, ) { const byOwnerAndCwd = new Map< string, @@ -1434,7 +1665,18 @@ export const make = Effect.gen(function* () { >(); for (const transcript of transcripts) { - const rolloutCwd = yield* readCwd(source, transcript, budget); + // Unchanged imported transcripts keep their import cwd, so they never spend the read budget. + // Codex is excluded: its first record carries the cwd and the subagent marker, and + // rollouts imported before subagents were skipped must still be excluded by it. + const rolloutCwd = + (source === "codex" + ? undefined + : importedByFile.get(`${transcript.providerInstanceId}\0${transcript.filePath}`) + )?.find( + (imported) => + imported.source.provider === source && + sameTranscriptIdentity(imported.source, transcript.identity), + )?.cwd ?? (yield* readCwd(source, transcript, budget)); if (rolloutCwd === null || rolloutCwd === false) continue; const cwd = projectCwd(rolloutCwd, transcript.projectRoots); const key = `${transcript.providerInstanceId}\0${cwd}`; @@ -1469,8 +1711,25 @@ export const make = Effect.gen(function* () { Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-settings", cause })), ); + const runtimeRows = yield* runtimes + .list() + .pipe( + Effect.mapError( + (cause) => new AgentSessionScanError({ operation: "read-projects", cause }), + ), + ); + const importedByFile = Map.groupBy( + runtimeRows.flatMap((runtime) => { + const payload = decodeImportedTranscriptPayload(runtime.runtimePayload); + if (Option.isNone(payload) || payload.value.cwd === undefined) return []; + const cwd = payload.value.cwd; + return (payload.value.importedTranscripts ?? []).map((source) => ({ cwd, source })); + }), + ({ source }) => `${source.providerInstanceId}\0${source.filePath}`, + ); const raw: Array = []; let truncated = false; + let metadataTruncated = false; for (const source of ["claudeAgent", "codex", "pi"] as const) { const instances: Array<{ @@ -1515,7 +1774,11 @@ export const make = Effect.gen(function* () { instance.environment, hostEnvironment, ).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir)); - homePath = resolvePiSessionsDir(environment, homeDir, path); + homePath = resolvePiSessionsDir( + environment, + piHome(environment, homeDir, platform), + path, + ); } else if (source === "claudeAgent") { const config = decodeClaudeSettings(instance.config ?? {}); if (Option.isNone(config)) continue; @@ -1546,25 +1809,48 @@ export const make = Effect.gen(function* () { } const transcriptCandidates: Array = []; - const baseOperationBudget = Math.floor( - MAX_DISCOVERY_OPERATIONS_PER_SOURCE / Math.max(1, homes.length), - ); - const extraOperationBudgets = MAX_DISCOVERY_OPERATIONS_PER_SOURCE % Math.max(1, homes.length); + const discover = + source === "claudeAgent" + ? discoverClaudeTranscripts + : source === "codex" + ? discoverCodexTranscripts + : discoverPiTranscripts; + const shares = splitOperationBudget(MAX_DISCOVERY_OPERATIONS_PER_SOURCE, homes.length); + const discovered: Array<{ + readonly transcripts: ReadonlyArray; + readonly truncated: boolean; + readonly operationsUsed: number; + }> = []; for (const [index, home] of homes.entries()) { - const operationBudget = baseOperationBudget + (index < extraOperationBudgets ? 1 : 0); - if (operationBudget === 0) { - truncated = true; - continue; + const operationBudget = shares[index] ?? 0; + discovered.push( + operationBudget === 0 + ? { transcripts: [], truncated: true, operationsUsed: 0 } + : yield* discover(home.homePath, home.providerInstanceId, operationBudget), + ); + } + // Budget that small homes left unused goes to the homes that ran out, which rescan with it. + // Each takes an even split of what is still unused; a pass in which no home finishes spends + // it all, so every repeat has fewer starved homes. + let unused = + MAX_DISCOVERY_OPERATIONS_PER_SOURCE - + discovered.reduce((total, result) => total + result.operationsUsed, 0); + let starved = discovered.flatMap((result, index) => (result.truncated ? [index] : [])); + while (unused > 0 && starved.length > 0) { + for (const [position, index] of starved.entries()) { + if (unused <= 0) break; + const home = homes[index]!; + const before = discovered[index]!.operationsUsed; + const extra = Math.ceil(unused / (starved.length - position)); + const result = yield* discover(home.homePath, home.providerInstanceId, before + extra); + discovered[index] = result; + unused -= result.operationsUsed - before; } - const discover = - source === "claudeAgent" - ? discoverClaudeTranscripts - : source === "codex" - ? discoverCodexTranscripts - : discoverPiTranscripts; - const discovered = yield* discover(home.homePath, home.providerInstanceId, operationBudget); - truncated ||= discovered.truncated; - transcriptCandidates.push(...discovered.transcripts); + starved = starved.filter((index) => discovered[index]!.truncated); + } + for (const result of discovered) { + truncated ||= result.truncated; + transcriptCandidates.push(...result.transcripts); } transcriptCandidates.sort( @@ -1581,18 +1867,25 @@ export const make = Effect.gen(function* () { recordsRemaining: MAX_METADATA_RECORDS_PER_SOURCE, truncated: false, }; - raw.push(...(yield* groupTranscriptsByCwd(source, selectedTranscripts, metadataBudget))); - truncated ||= metadataBudget.truncated; + raw.push( + ...(yield* groupTranscriptsByCwd( + source, + selectedTranscripts, + metadataBudget, + importedByFile, + )), + ); + metadataTruncated ||= metadataBudget.truncated; } - return { candidates: raw, truncated }; + return { candidates: raw, truncated: truncated || metadataTruncated, metadataTruncated }; }); - let cachedCandidates: ReadonlyArray | null = null; + let cachedCandidates: Effect.Success> | null = null; const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () { - const { candidates: raw, truncated } = yield* collectCandidates(); - cachedCandidates = raw; + cachedCandidates = yield* collectCandidates(); + const { candidates: raw, truncated } = cachedCandidates; const merged = new Map< string, @@ -1604,60 +1897,27 @@ export const make = Effect.gen(function* () { git: AgentSessionProjectGit | null; } >(); - // Resolve every candidate directory first so one batch reads all git identities. - const directories = new Map>(); - for (const candidate of raw) { - const expanded = expandHomePath(candidate.cwd.trim(), homeDir); - if (!path.isAbsolute(expanded)) continue; - const resolved = path.resolve(expanded); - if (directories.has(resolved) || isExcludedProjectPath(resolved)) continue; - const stats = yield* statOption(resolved); - if (Option.isNone(stats) || stats.value.type !== "Directory") { - directories.set(resolved, Option.none()); - continue; - } - const realPath = yield* fileSystem - .realPath(resolved) - .pipe(Effect.orElseSucceed(() => resolved)); - // Symlinks can disguise excluded worktree paths; re-check their targets. - directories.set(resolved, isExcludedProjectPath(realPath) ? Option.none() : stats); - } - const directoryGitIdentities = yield* readGitIdentities( - Array.from(directories).flatMap(([directory, stats]) => - Option.isSome(stats) ? [directory] : [], - ), + const directoryProjects = yield* resolveDirectoryProjects( + raw.flatMap((candidate) => { + const expanded = expandHomePath(candidate.cwd.trim(), homeDir); + return path.isAbsolute(expanded) ? [path.resolve(expanded)] : []; + }), ); - const directoryKeys = new Map(); - const gitIdentities = new Map(); - for (const candidate of raw) { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; - const resolved = path.resolve(expanded); - const stats = directories.get(resolved); - if (stats === undefined || Option.isNone(stats)) continue; - let key = directoryKeys.get(resolved); - if (key === undefined) { - const gitIdentity = directoryGitIdentities.get(resolved); - if (gitIdentity === undefined || gitIdentity._tag === "Worktree") { - key = ""; - } else { - key = yield* directoryIdentity(resolved, stats.value); - gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null); - } - directoryKeys.set(resolved, key); - } - if (key === "") continue; + const project = directoryProjects.get(path.resolve(expanded)); + if (project === undefined || project === null) continue; - const existing = merged.get(key); + const existing = merged.get(project.key); if (!existing) { - merged.set(key, { - path: resolved, + merged.set(project.key, { + path: project.path, sources: [candidate.source], threadCount: candidate.threadCount, lastActiveAtMs: candidate.lastActiveAtMs, - git: gitIdentities.get(key) ?? null, + git: project.git, }); continue; } @@ -1732,8 +1992,50 @@ export const make = Effect.gen(function* () { const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS; - const candidates = cachedCandidates ?? (yield* collectCandidates()).candidates; - cachedCandidates = candidates; + // Imports recorded since a budget-truncated collection can free budget for transcripts it cut off. + if (cachedCandidates === null || cachedCandidates.metadataTruncated) { + cachedCandidates = yield* collectCandidates(); + } + const { candidates } = cachedCandidates; + + // The scan counts a linked worktree's sessions toward its main checkout, so import them with it. + const candidateDirectories = candidates.flatMap((candidate) => { + const expanded = expandHomePath(candidate.cwd.trim(), homeDir); + return path.isAbsolute(expanded) ? [path.resolve(expanded)] : []; + }); + const directoryProjects = yield* resolveDirectoryProjects(candidateDirectories); + const belongsToRoot = Effect.fn("AgentSessionScanner.belongsToRoot")(function* ( + resolved: string, + ) { + if ((yield* directoryIdentity(resolved)) === rootIdentity) return true; + if (!directoryProjects.has(resolved)) { + const project = (yield* resolveDirectoryProjects([resolved])).get(resolved) ?? null; + directoryProjects.set(resolved, project); + } + return directoryProjects.get(resolved)?.key === rootIdentity; + }); + const worktreesByDirectory = new Map(); + const rootWorktree = Effect.fn("AgentSessionScanner.rootWorktree")(function* ( + resolved: string, + ) { + const known = worktreesByDirectory.get(resolved); + if (known !== undefined) return known; + const gitDir = + (yield* directoryIdentity(resolved)) === rootIdentity + ? null + : (directoryProjects.get(resolved)?.worktreeGitDir ?? null); + let worktree: { path: string; branch: string | null } | null = null; + if (gitDir !== null) { + const headPath = path.join(gitDir, "HEAD"); + const head = (yield* readGitFiles([headPath])).get(headPath) ?? ""; + worktree = { + path: resolved, + branch: /^ref: refs\/heads\/(.+)$/.exec(head.trim())?.[1] ?? null, + }; + } + worktreesByDirectory.set(resolved, worktree); + return worktree; + }); const eligibleTranscripts: Array<{ readonly candidate: RawCandidate; @@ -1743,7 +2045,7 @@ export const make = Effect.gen(function* () { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; const resolved = path.resolve(expanded); - if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue; + if (!(yield* belongsToRoot(resolved))) continue; for (const transcript of candidate.transcripts) { if ( @@ -1874,12 +2176,10 @@ export const make = Effect.gen(function* () { projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(), homeDir, ); - if ( - !path.isAbsolute(expandedCwd) || - (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity - ) { + if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) { return Option.some({ _tag: "Skipped" }); } + const worktree = yield* rootWorktree(path.resolve(expandedCwd)); const inheritedRecords = candidate.source === "codex" @@ -1893,14 +2193,29 @@ export const make = Effect.gen(function* () { { source: candidate.source, providerInstanceId: candidate.providerInstanceId, - fallbackSessionId: path.basename(transcript.filePath, ".jsonl"), + fallbackSessionId: path.basename( + transcript.filePath, + isCompressedTranscript(transcript.filePath) + ? COMPRESSED_TRANSCRIPT_SUFFIX + : ".jsonl", + ), lastActiveAtMs: transcript.mtimeMs, }, inheritedRecords === null ? snapshot.records : [...inheritedRecords, ...snapshot.records], snapshot.claudeFields, + snapshot.droppedMessageCount, ); + if (parsedThread === "empty") { + // null means an unreadable history base, which may hold the conversation. + if (candidate.source === "codex" && inheritedRecords === null) { + return Option.some({ _tag: "Skipped" }); + } + // Never recorded as imported, so charging them would starve real sessions every run. + transcriptsRemaining += 1; + return Option.none(); + } if (parsedThread === null) { return Option.some({ _tag: "Skipped" }); } @@ -1929,6 +2244,7 @@ export const make = Effect.gen(function* () { thread: savedTitle === undefined ? parsedThread : { ...parsedThread, title: savedTitle }, source, + worktree, }); }).pipe(importReadLock.withPermits(1)), ), diff --git a/apps/server/src/project/ManagedProjectFolders.test.ts b/apps/server/src/project/ManagedProjectFolders.test.ts index f289a3ebe6..07da49c732 100644 --- a/apps/server/src/project/ManagedProjectFolders.test.ts +++ b/apps/server/src/project/ManagedProjectFolders.test.ts @@ -1,7 +1,13 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { CommandId, ProjectId, ThreadId, VcsProcessSpawnError } from "@t3tools/contracts"; +import { + CommandId, + ProjectId, + ThreadId, + VcsProcessSpawnError, + VcsProcessTimeoutError, +} from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -12,6 +18,7 @@ import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; +import { ChildProcessSpawner } from "effect/process"; import * as Scope from "effect/Scope"; import * as ServerConfig from "../config.ts"; @@ -55,7 +62,7 @@ const layerRealGit = GitVcsDriver.layer.pipe(Layer.provide(VcsProcess.layer)); interface HarnessOptions { readonly vcsProcess?: Layer.Layer; - readonly git?: Layer.Layer; + readonly git?: typeof layerRealGit; readonly projects?: ( real: ProjectService.ProjectService["Service"], ) => ProjectService.ProjectService["Service"]; @@ -173,6 +180,44 @@ it.effect("offers a Scratch folder when Git is not installed", () => ), ); +it.effect("offers the Scratch folder once a Git check that timed out is asked again", () => + withScratch( + ({ baseDir }) => + Effect.gen(function* () { + const path = yield* Path.Path; + const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; + assert.isTrue(Option.isNone(yield* scratch.scratchRoot)); + assert.equal(yield* requireRoot, path.resolve(baseDir, "scratch")); + }), + { + vcsProcess: Layer.effect( + VcsProcess.VcsProcess, + Effect.map(VcsProcess.make, (real) => { + let timedOut = false; + return VcsProcess.VcsProcess.of({ + run: (input) => + Effect.suspend(() => { + if (timedOut) return real.run(input); + timedOut = true; + return Effect.fail( + new VcsProcessTimeoutError({ + operation: input.operation, + command: input.command, + cwd: input.cwd, + timeoutMs: 5_000, + }), + ); + }), + }); + }), + ).pipe( + Layer.provide(ProcessRunner.layer), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + }, + ), +); + it.effect("creates one Scratch project, even for concurrent first requests", () => withScratch(() => Effect.gen(function* () { @@ -273,6 +318,15 @@ it.effect("gives each Scratch thread its own folder, named from its message", () ); assert.equal(path.dirname(pasted), root); assert.isAtMost(path.basename(pasted).length, 80); + + const accented = Option.getOrThrow( + yield* scratch.folderForThread({ + projectId, + threadId: ThreadId.make("thread-diacritics"), + text: "tìm kiếm skill", + }), + ); + assert.match(path.basename(accented), /^\d{4}-\d{2}-\d{2}-tim-kiem-skill-/); }), ), ); @@ -306,6 +360,31 @@ it.effect("leaves threads in other projects alone", () => ), ); +it.effect("still knows No project when its folder is the target of a symlinked Scratch", () => + withScratch(({ baseDir }) => + Effect.gen(function* () { + const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; + const projects = yield* ProjectService.ProjectService; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* requireRoot; + const target = path.join(baseDir, "visible-chats"); + yield* fileSystem.makeDirectory(target); + yield* fileSystem.symlink(target, root); + const { projectId } = yield* scratch.ensureScratchProject; + yield* projects.update({ + commandId: CommandId.make("command:point-at-target"), + projectId, + workspaceRoot: target, + }); + + assert.isTrue(yield* scratch.isScratchProject(projectId)); + assert.equal((yield* scratch.ensureScratchProject).projectId, projectId); + assert.deepStrictEqual(yield* scratch.scratchRoot, Option.some(target)); + }), + ), +); + const GIT_IDENTITY_KEYS = [ "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", @@ -450,6 +529,41 @@ it.effect("keeps a named project and reports why when Git cannot commit", () => ), ); +it.effect("says Git is not installed when a named project cannot start Git", () => + withScratch( + () => + Effect.gen(function* () { + const folders = yield* ManagedProjectFolders.ManagedProjectFolders; + + const failure = yield* Effect.flip(folders.createNamedProject({ name: "T3Code Test" })); + + assert.strictEqual( + failure.message, + "Git isn't installed on this machine. Install Git to create a project.", + ); + }), + { + git: GitVcsDriver.layer.pipe( + Layer.provide( + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "ChildProcess", + method: "spawn", + syscall: "spawn git", + }), + ), + ), + ), + ), + ), + }, + ), +); + it.effect("keeps a folder that another project owns when the create conflicts", () => withScratch(({ baseDir }) => withGitEnv( diff --git a/apps/server/src/project/ManagedProjectFolders.ts b/apps/server/src/project/ManagedProjectFolders.ts index 8adc49aa16..4d86aa0e04 100644 --- a/apps/server/src/project/ManagedProjectFolders.ts +++ b/apps/server/src/project/ManagedProjectFolders.ts @@ -1,11 +1,12 @@ import { CommandId, + GitCommandError, type GitManagerServiceError, ProjectId, type ThreadId, VcsProcessSpawnError, } from "@t3tools/contracts"; -import { newProjectFolderName } from "@t3tools/shared/path"; +import { foldLatinDiacritics, newProjectFolderName } from "@t3tools/shared/path"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -65,8 +66,20 @@ export class ScratchProjectError extends Schema.TaggedError } } +/** Where No project threads keep their folders, whether or not this T3 home allows them. */ +export const scratchFolderRoot = (baseDir: string, path: Path.Path) => + path.resolve(baseDir, "scratch"); + export type ScratchError = ScratchUnavailableError | ScratchFolderError | ScratchProjectError; +// The spawner checks cwd before spawning, so NotFound from spawn itself means a missing executable. +const isMissingExecutable = (cause: unknown) => + PlatformError.isPlatformError(cause) && + cause.reason._tag === "NotFound" && + cause.reason.method === "spawn"; + +const isGitCommandError = Schema.is(GitCommandError); + export class NamedProjectFolderError extends Schema.TaggedError()( "NamedProjectFolderError", { @@ -75,7 +88,9 @@ export class NamedProjectFolderError extends Schema.TaggedError()("t3/project/ManagedProjectFolders") {} const folderWords = (text: string) => - text + foldLatinDiacritics(text) .toLowerCase() .split(/[^a-z0-9]+/) .filter(Boolean) @@ -244,7 +259,7 @@ const make = Effect.gen(function* () { Effect.flatMap( (repositoryRoot): Effect.Effect> => { if (repositoryRoot === null) { - return Effect.succeed(Result.succeed(path.resolve(config.baseDir, "scratch"))); + return Effect.succeed(Result.succeed(scratchFolderRoot(config.baseDir, path))); } const unavailable = new ScratchUnavailableError({ baseDir: config.baseDir, @@ -253,16 +268,37 @@ const make = Effect.gen(function* () { return Effect.logWarning(unavailable.message).pipe(Effect.as(Result.fail(unavailable))); }, ), - Effect.catchCause((cause) => - Cause.hasInterrupts(cause) - ? Effect.interrupt - : Effect.succeed(Result.fail(new ScratchUnavailableError({ baseDir: config.baseDir }))), + ), + // A failed git check (say, a timeout on a busy machine) is not an answer; ask again next time. + Exit.match({ onSuccess: () => Duration.infinity, onFailure: () => Duration.zero }), + ); + const scratchProbe = probe.pipe( + Effect.catchCause((cause) => + Cause.hasInterrupts(cause) + ? Effect.interrupt + : Effect.succeed(Result.fail(new ScratchUnavailableError({ baseDir: config.baseDir }))), + ), + Effect.onInterrupt(() => invalidate), + ); + // A symlinked scratch folder lets the No project live at either the link or its target. + const scratchProjectRoot = (root: string) => + fileSystem.realPath(root).pipe( + Effect.flatMap((target) => + target === root + ? Effect.succeed(root) + : projects + .getByWorkspaceRoot(target) + .pipe(Effect.map((project) => (Option.isSome(project) ? target : root))), ), + Effect.orElseSucceed(() => root), + ); + const scratchRoot = scratchProbe.pipe( + Effect.flatMap((probed) => + Result.isSuccess(probed) + ? scratchProjectRoot(probed.success).pipe(Effect.asSome) + : Effect.succeedNone, ), - Duration.infinity, ); - const scratchProbe = probe.pipe(Effect.onInterrupt(() => invalidate)); - const scratchRoot = scratchProbe.pipe(Effect.map(Result.getSuccess)); const makeScratchFolder = (folder: string) => fileSystem @@ -271,8 +307,9 @@ const make = Effect.gen(function* () { const ensureScratchProject: ManagedProjectFolders["Service"]["ensureScratchProject"] = Effect.gen( function* () { - const workspaceRoot = yield* scratchProbe.pipe(Effect.flatMap(Effect.fromResult)); - yield* makeScratchFolder(workspaceRoot); + const probedRoot = yield* scratchProbe.pipe(Effect.flatMap(Effect.fromResult)); + yield* makeScratchFolder(probedRoot); + const workspaceRoot = yield* scratchProjectRoot(probedRoot); const id = yield* random .uuidV4() .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause }))); diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index 0d0a614e46..77abcf87a8 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -343,6 +343,9 @@ describe("parseGitCloneProgressLine", () => { expect( parseGitCloneProgressLine("Receiving objects: 45% (4500/10000), 12.30 MiB | 5.00 MiB/s"), ).toEqual({ stage: "receiving", percent: 45, detail: "12.30 MiB | 5.00 MiB/s" }); + expect( + parseGitCloneProgressLine("Receiving objects: 100% (5/5), 40.00 MiB | 1.40 MiB/s, done."), + ).toEqual({ stage: "receiving", percent: 100, detail: "40.00 MiB | 1.40 MiB/s" }); expect(parseGitCloneProgressLine("Resolving deltas: 100% (700/700), done.")).toEqual({ stage: "resolving", percent: 100, diff --git a/apps/server/src/project/ProjectEnrichmentService.ts b/apps/server/src/project/ProjectEnrichmentService.ts index f609bc53fa..c08bba24bc 100644 --- a/apps/server/src/project/ProjectEnrichmentService.ts +++ b/apps/server/src/project/ProjectEnrichmentService.ts @@ -51,6 +51,8 @@ export class ProjectEnrichmentService extends Context.Service< workspaceRoot: string, ) => Effect.Effect; readonly invalidate: (workspaceRoots: Iterable) => Effect.Effect; + /** Re-resolves past both identity caches and publishes a found identity, leaving the favicon alone. */ + readonly refreshRepositoryIdentity: (workspaceRoot: string) => Effect.Effect; readonly subscribeChanges: Effect.Effect< PubSub.Subscription, never, @@ -340,12 +342,24 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( ); }); + const refreshRepositoryIdentity: ProjectEnrichmentService["Service"]["refreshRepositoryIdentity"] = + Effect.fn("ProjectEnrichmentService.refreshRepositoryIdentity")(function* (workspaceRoot) { + // Remote-less folders hit this after every turn; publishing their unchanged null would + // push a shell frame to every subscriber. + if ((yield* repositoryIdentityResolver.resolve(workspaceRoot, { refresh: true })) === null) { + return; + } + yield* Cache.invalidate(repositoryIdentityCache, workspaceRoot); + yield* resolveRepositoryIdentity(workspaceRoot); + }); + return ProjectEnrichmentService.of({ peek, request, getAvailable, readRepositoryIdentity, invalidate, + refreshRepositoryIdentity, subscribeChanges: PubSub.subscribe(changes), }); }); diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 5877662f46..143db2a866 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -43,7 +43,7 @@ const writeTextFile = Effect.fn("writeTextFile")(function* ( const makeResolverWithFileSystem = (fileSystem: FileSystem.FileSystem) => ProjectFaviconResolver.make.pipe( - Effect.provide([WorkspacePaths.layer, T3ProjectFileLoader.layer]), + Effect.provide([Layer.fresh(WorkspacePaths.layer), T3ProjectFileLoader.layer]), Effect.provideService(FileSystem.FileSystem, fileSystem), ); @@ -81,6 +81,28 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }).pipe(Effect.provide(TestClock.layer())), ); + it.effect("looks up a missing workspace root once within the negative cache window", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = path.join(yield* makeTempDir, "deleted-project"); + let rootStats = 0; + const resolver = yield* makeResolverWithFileSystem( + FileSystem.FileSystem.of({ + ...fileSystem, + stat: (filePath) => { + if (filePath === cwd) rootStats += 1; + return fileSystem.stat(filePath); + }, + }), + ); + + yield* Effect.exit(resolver.resolvePath(cwd)); + yield* Effect.exit(resolver.resolvePath(cwd)); + expect(rootStats).toBe(1); + }), + ); + it.effect("prefers a t3.json iconPath over well-known files", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; @@ -179,6 +201,17 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(resolved).not.toBeNull(); expect(resolved).toBe((yield* Path.Path).join(cwd, "public", "brand", "logo.svg")); + + const paddedCwd = yield* makeTempDir; + yield* writeTextFile( + paddedCwd, + "index.html", + '', + ); + yield* writeTextFile(paddedCwd, "brand/custom.svg", "custom"); + expect(yield* resolver.resolvePath(paddedCwd)).toBe( + (yield* Path.Path).join(paddedCwd, "brand", "custom.svg"), + ); }), ); diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 51b20d9ed0..e09d4aad36 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -1,4 +1,5 @@ import * as Cache from "effect/Cache"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -143,7 +144,8 @@ export const make = Effect.gen(function* () { const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader; const resolveIconHref = (href: string): ReadonlyArray => { - const clean = href.replace(/^\//, ""); + // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs. + const clean = href.trim().replace(/^\//, ""); return [path.join("public", clean), clean]; }; @@ -304,7 +306,10 @@ export const make = Effect.gen(function* () { timeToLive: Exit.match({ onSuccess: (value: string | null) => value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL, - onFailure: () => Duration.zero, + onFailure: (cause) => + Option.exists(Cause.findErrorOption(cause), isMissingWorkspaceRoot) + ? FAVICON_NEGATIVE_CACHE_TTL + : Duration.zero, }), }, ); diff --git a/apps/server/src/project/ProjectService.deletion.test.ts b/apps/server/src/project/ProjectService.deletion.test.ts index 28b1c40541..25e5ee54a2 100644 --- a/apps/server/src/project/ProjectService.deletion.test.ts +++ b/apps/server/src/project/ProjectService.deletion.test.ts @@ -28,6 +28,7 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ProjectSettingsOverrideSweep from "../provider/ProjectSettingsOverrideSweep.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; @@ -501,9 +502,13 @@ it.effect("deletes a project without force once its imported threads were delete }).pipe(Effect.provide(layerDatabase)), ); -it.effect( - "clears a deleted project's settings overrides so a machine-disabled instance cannot stay alive", - () => +it.effect.each([ + { policy: "no", worktreeCleanup: undefined }, + { policy: "its off", worktreeCleanup: { mode: "off" } as const }, + { policy: "its legacy", worktreeCleanup: null }, +])( + "clears a deleted project's settings overrides, keeping $policy worktree cleanup policy, so a machine-disabled instance cannot stay alive", + ({ worktreeCleanup }) => Effect.gen(function* () { const projectId = ProjectId.make("project:overrides-cleanup"); const instanceId = ProviderInstanceId.make("codex_work"); @@ -514,7 +519,11 @@ it.effect( const serverSettings = yield* ServerSettings.ServerSettingsService; yield* serverSettings.updateSettings({ projectSettingsOverrides: { - [projectId]: { providerInstances: { [instanceId]: { enabled: true } } }, + [projectId]: { + providerInstances: { [instanceId]: { enabled: true } }, + defaultAutoPull: true, + ...(worktreeCleanup === undefined ? {} : { worktreeCleanup }), + }, }, }); @@ -523,8 +532,35 @@ it.effect( projectId, }); - const settingsAfterDelete = yield* serverSettings.getSettings; - assert.isUndefined(settingsAfterDelete.projectSettingsOverrides[projectId]); + const entry = (yield* serverSettings.getSettings).projectSettingsOverrides[projectId]; + if (worktreeCleanup === undefined) { + assert.isUndefined(entry); + } else { + assert.deepStrictEqual(entry, { worktreeCleanup, providerInstances: {} }); + } + + const liveProjectId = ProjectId.make("project:still-live"); + const missingProjectId = ProjectId.make("project:missing"); + yield* seedProject(liveProjectId); + // Older deletions or interrupted best-effort cleanup can leave the original overrides on restart. + yield* serverSettings.updateSettings({ + projectSettingsOverrides: { + [projectId]: { + providerInstances: { [instanceId]: { enabled: true } }, + defaultAutoPull: true, + ...(worktreeCleanup === undefined ? {} : { worktreeCleanup }), + }, + [liveProjectId]: { defaultAutoPull: true }, + [missingProjectId]: { worktreeCleanup: { mode: "off" } }, + }, + }); + yield* ProjectSettingsOverrideSweep.sweep; + assert.deepStrictEqual((yield* serverSettings.getSettings).projectSettingsOverrides, { + [liveProjectId]: { defaultAutoPull: true }, + ...(worktreeCleanup === undefined + ? {} + : { [projectId]: { worktreeCleanup, providerInstances: {} } }), + }); }).pipe(Effect.provide(layerServices)); }).pipe(Effect.provide(layerDatabase)), ); diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index 1517bed31b..492379beec 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -9,6 +9,7 @@ import { CommandId, type Project, ProjectId, ProviderInstanceId } from "@t3tools import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Metric from "effect/Metric"; import * as Option from "effect/Option"; @@ -30,12 +31,14 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts"; import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; import * as ProjectService from "./ProjectService.ts"; import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; +import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts"; const layerWorkspacePaths = Layer.succeed(WorkspacePaths.WorkspacePaths, { normalizeWorkspaceRoot: (workspaceRoot) => Effect.succeed(workspaceRoot.replace(/\/$/, "")), @@ -300,7 +303,14 @@ it.layer(layerTest)("ProjectService", (it) => { }); assert.isFalse(reset.autoPull); assert.isNull(reset.projectIcon); - assert.equal(reset.faviconPath, hydratedCreated.faviconPath); + assert.equal( + (yield* waitForProject( + service, + projectId, + (project) => project.faviconPath === hydratedCreated.faviconPath, + )).faviconPath, + hydratedCreated.faviconPath, + ); assert.isNull(reset.defaultThreadEnvMode); assert.deepEqual( (yield* service.snapshot).projects.map((project) => project.id), @@ -543,6 +553,12 @@ it.layer(layerTest)("ProjectService", (it) => { title: "Delete retry", workspaceRoot: "/work/delete-retry", }); + // Enrichment landing between the two deletes would change the project the retry reads. + yield* waitForProject( + service, + projectId, + (project) => project.faviconPath !== null && project.repositoryIdentity !== null, + ); const input = { commandId: CommandId.make("command:delete-retry:delete"), projectId }; const deleted = yield* service.delete(input); assert.deepEqual(yield* service.delete(input), deleted); @@ -725,6 +741,112 @@ it.effect("invalidates workspace-derived metadata when a project moves", () => }), ); +it.effect("resolves a restored icon immediately after reselecting its saved path", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "project-icon-reselect-" }); + const iconPath = `${cwd}/icon.svg`; + const metadata = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: () => Effect.succeed(null), + }), + ProjectFaviconResolver.layer.pipe( + Layer.provide(layerWorkspacePaths), + Layer.provide(T3ProjectFileLoader.layer), + Layer.provide(NodeServices.layer), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; + const projectId = ProjectId.make("project:icon-reselect"); + yield* service.create({ + commandId: CommandId.make("command:icon-reselect:create"), + projectId, + title: "Icon reselection", + workspaceRoot: cwd, + }); + yield* service.update({ + commandId: CommandId.make("command:icon-reselect:missing"), + projectId, + faviconPath: "icon.svg", + }); + assert.isNull(yield* resolver.resolvePath(cwd, "icon.svg")); + yield* fileSystem.writeFileString(iconPath, ''); + assert.isNull(yield* resolver.resolvePath(cwd, "icon.svg")); + yield* service.update({ + commandId: CommandId.make("command:icon-reselect:restored"), + projectId, + faviconPath: "icon.svg", + }); + assert.equal(yield* resolver.resolvePath(cwd, "icon.svg"), iconPath); + }).pipe(Effect.provide(layerTestFor(metadata))); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("refuses a worktree container as a new project and as a new workspace root", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const processRunner = yield* ProcessRunner.ProcessRunner; + const fixture = yield* fileSystem.makeTempDirectoryScoped({ prefix: "project-container-" }); + const git = (cwd: string, ...args: ReadonlyArray) => + processRunner.run({ + command: "git", + args: ["-C", cwd, "-c", "user.email=t@t", "-c", "user.name=t", ...args], + }); + const source = `${fixture}/source`; + const container = `${fixture}/container`; + yield* fileSystem.makeDirectory(source); + yield* fileSystem.makeDirectory(container); + yield* git(source, "init", "-b", "develop"); + yield* fileSystem.writeFileString(`${source}/README.md`, "readme\n"); + yield* git(source, "add", "README.md"); + yield* git(source, "commit", "-m", "init"); + yield* git(fixture, "clone", "--bare", source, `${container}/.bare`); + yield* fileSystem.writeFileString(`${container}/.git`, "gitdir: ./.bare\n"); + yield* git(container, "worktree", "add", "develop", "develop"); + + yield* Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + // As cloned the container is bare; Initialize Git or a config edit clears core.bare. + for (const coreBare of ["true", "false"]) { + yield* git(container, "config", "core.bare", coreBare); + const rejected = yield* service + .create({ + commandId: CommandId.make(`command:container:create:${coreBare}`), + projectId: ProjectId.make(`project:container:${coreBare}`), + title: "Container", + workspaceRoot: container, + }) + .pipe(Effect.flip); + assert.equal(rejected._tag, "ProjectInvalidError", `core.bare=${coreBare}`); + assert.include(rejected.message, "Add one of its worktrees"); + assert.isTrue(Option.isNone(yield* service.getByWorkspaceRoot(container))); + } + + const projectId = ProjectId.make("project:container:worktree"); + const worktree = yield* service.create({ + commandId: CommandId.make("command:container:worktree"), + projectId, + title: "Worktree", + workspaceRoot: `${container}/develop`, + }); + const moved = yield* service + .update({ + commandId: CommandId.make("command:container:move"), + projectId, + workspaceRoot: container, + }) + .pipe(Effect.flip); + assert.equal(moved._tag, "ProjectInvalidError"); + assert.equal( + Option.getOrThrow(yield* service.getById(projectId)).workspaceRoot, + worktree.workspaceRoot, + ); + }).pipe(Effect.provide(layerTest)); + }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))), +); + it.effect("serializes two projects claiming the same workspace root", () => Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 70f12adf05..1db031456f 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -33,8 +33,11 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts"; import * as ServerSettings from "../serverSettings.ts"; +import { deletedProjectOverridePatch } from "../provider/ProjectSettingsOverrideSweep.ts"; import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; +import * as ProcessRunner from "../processRunner.ts"; import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; +import { makeIsWorktreeContainer } from "./worktreeContainer.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; export interface ProjectCreateInput extends ProjectCreatePayload { @@ -182,6 +185,9 @@ export const make = Effect.gen(function* () { const serverSettings = yield* ServerSettings.ServerSettingsService; const fileSystem = yield* FileSystem.FileSystem; const isManagedWorktreePath = yield* makeIsManagedWorktreePath; + const isWorktreeContainer = yield* makeIsWorktreeContainer.pipe( + Effect.provide(ProcessRunner.layer), + ); const projectLocks = yield* KeyedLock.make(); const workspaceLocks = yield* KeyedLock.make(); @@ -244,6 +250,17 @@ export const make = Effect.gen(function* () { ), ); + const rejectWorktreeContainer = Effect.fn("ProjectService.rejectWorktreeContainer")(function* ( + projectId: ProjectId, + workspaceRoot: string, + ) { + if (!(yield* isWorktreeContainer(workspaceRoot))) return; + return yield* new ProjectInvalidError({ + projectId, + detail: `${workspaceRoot} holds a repository's worktrees but is not a checkout itself. Add one of its worktrees as the project instead.`, + }); + }); + const commit = Effect.fn("ProjectService.commit")(function* (command: ProjectCommand) { const { projectId } = command; const dispatchError = (cause: unknown) => @@ -383,6 +400,7 @@ export const make = Effect.gen(function* () { workspaceRoot: input.workspaceRoot, createIfMissing: input.createWorkspaceRootIfMissing ?? false, }); + yield* rejectWorktreeContainer(input.projectId, workspaceRoot); yield* commit({ type: "project.create", commandId: input.commandId, @@ -410,6 +428,9 @@ export const make = Effect.gen(function* () { projectId: input.projectId, workspaceRoot: input.workspaceRoot, }); + if (workspaceRoot !== previousRoot) { + yield* rejectWorktreeContainer(input.projectId, workspaceRoot); + } yield* commit({ type: "project.meta.update", commandId: input.commandId, @@ -429,7 +450,7 @@ export const make = Effect.gen(function* () { ...(input.pinned === undefined ? {} : { pinned: input.pinned }), ...(input.archived === undefined ? {} : { archived: input.archived }), }); - if (workspaceRoot !== previousRoot) { + if (workspaceRoot !== previousRoot || input.faviconPath !== undefined) { yield* projectEnrichment.invalidate([previousRoot, workspaceRoot]); } return yield* readCommitted(input.projectId); @@ -505,7 +526,10 @@ export const make = Effect.gen(function* () { (cause) => new ProjectOperationError({ operation: "list-threads", projectId, cause }), ), ); - const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads]; + // Newest first: a source deleted while its fork lives keeps the pages that fork shows. + const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].sort( + (a, b) => DateTime.toEpochMillis(b.createdAt) - DateTime.toEpochMillis(a.createdAt), + ); if (projectThreads.length > 0 && input.force !== true) { return yield* new ProjectNotEmptyError({ projectId }); } @@ -514,7 +538,7 @@ export const make = Effect.gen(function* () { projectThreads, (thread) => threadCommands - .withLock(thread.id, deleteChildThread(input, thread.id)) + .withDeletionLock(threadCommands.withLock(thread.id, deleteChildThread(input, thread.id))) .pipe( Effect.mapError( (cause) => @@ -527,7 +551,14 @@ export const make = Effect.gen(function* () { // Best-effort cleanup releases disabled instances kept alive by overrides; crashes have no replay to revisit deletion. const clearProjectSettingsOverrides = (projectId: ProjectId) => - serverSettings.updateSettings({ projectSettingsOverrides: { [projectId]: null } }).pipe( + serverSettings.getSettings.pipe( + Effect.flatMap(({ projectSettingsOverrides }) => + serverSettings.updateSettings({ + projectSettingsOverrides: { + [projectId]: deletedProjectOverridePatch(projectSettingsOverrides[projectId]), + }, + }), + ), Effect.asVoid, Effect.catchCause((cause) => Effect.logWarning( diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 4eb466200b..fd40f24d5a 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -1,16 +1,20 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import { describe, expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, expect, it } from "@effect/vitest"; import { ProjectId, TerminalNotRunningError, type TerminalEvent, type TerminalSessionSnapshot, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { TestClock } from "effect/testing"; import * as ServerSettings from "../serverSettings.ts"; @@ -38,6 +42,7 @@ const openSnapshot = (history: string): TerminalSessionSnapshot => ({ }); const makeHarness = Effect.fn(function* (options: { + readonly command?: string; readonly history?: string; readonly opening?: Deferred.Deferred; readonly shell?: string | null; @@ -88,7 +93,7 @@ const makeHarness = Effect.fn(function* (options: { { id: "setup", name: "Setup", - command: "vp i", + command: options.command ?? "vp i", icon: "configure", runOnWorktreeCreate: true, }, @@ -102,6 +107,7 @@ const makeHarness = Effect.fn(function* (options: { const setup = Effect.fn(function* ( options: { + readonly command?: string; readonly history?: string; readonly shell?: string | null; } = {}, @@ -123,6 +129,32 @@ describe("ProjectSetupScriptRunner", () => { }), ); + it.effect("types an escaped Nushell wrapper once its line editor starts", () => + Effect.gen(function* () { + const command = + 'print "quoted"; print \'C:\\tools\'; print "$env.PATH"\nexit 7 # comment\r\n\t'; + const escaped = + 'print \\"quoted\\"; print \'C:\\\\tools\'; print \\"$env.PATH\\"\\u{a}exit 7 # comment\\u{d}\\u{a}\\u{9}'; + const { writes, emit } = yield* setup({ shell: "/opt/homebrew/bin/nu", command }); + yield* TestClock.adjust("1 second"); + expect(yield* Queue.size(writes)).toBe(0); + yield* emit({ ...event, type: "output", data: "> \x1b[?2004h" }); + const written = yield* Queue.take(writes); + const sentinel = written.match(/__T3_SETUP_DONE___[0-9a-f]{32}:/)?.[0]; + expect(sentinel).toBeDefined(); + expect(written).toBe( + ` ${[ + "$env.LAST_EXIT_CODE = 0", + "let __t3f = try { mktemp --tmpdir-path $env.T3CODE_WORKTREE_PATH --suffix .nu .t3-setup-XXXXXXXX } catch {|e| print -e $e.msg; null }", + `if $__t3f == null { $env.LAST_EXIT_CODE = 1 } else { try { [$"rm --permanent ($__t3f | to nuon)" "${escaped}"] | str join (char newline) | save --force --raw $__t3f; ^$nu.current-exe --login --commands $"cd $env.T3CODE_WORKTREE_PATH; source ($__t3f | to nuon)" } catch {|e| if $e != null and $e.exit_code? == null { print -e $e.msg }; if $env.LAST_EXIT_CODE == 0 { $env.LAST_EXIT_CODE = 1 } } }`, + "let __t3c = $env.LAST_EXIT_CODE", + "try { if $__t3f != null and ($__t3f | path exists) { rm --permanent $__t3f } } catch {|e| print -e $e.msg }", + `print $"\\n${sentinel}($__t3c)"`, + ].join("; ")}\r`, + ); + }), + ); + it.effect("shows a startup prompt and types only once the line editor starts", () => Effect.gen(function* () { const { result, writes, outputLines, emit } = yield* setup(); @@ -136,7 +168,19 @@ describe("ProjectSetupScriptRunner", () => { yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" }); yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" }); - expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/); + expect(yield* Queue.take(writes)).toContain("vp i"); + }), + ); + + it.effect("drops whole escape sequences from output lines", () => + Effect.gen(function* () { + const { outputLines, emit } = yield* setup(); + yield* emit({ + ...event, + type: "output", + data: "\x1b7\x1b[24;0fProgress: [ 40%]\x1b8\r\n\x1b%G\x1b#8\x1b[4:3mdone\x1bM\r\n", + }); + expect(yield* Queue.takeAll(outputLines)).toEqual(["Progress: [ 40%]", "done"]); }), ); @@ -144,7 +188,7 @@ describe("ProjectSetupScriptRunner", () => { Effect.gen(function* () { const { writes } = yield* setup(); yield* TestClock.adjust("3 seconds"); - expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/); + expect(yield* Queue.take(writes)).toContain("vp i"); }), ); @@ -166,7 +210,7 @@ describe("ProjectSetupScriptRunner", () => { yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") }); // The restart lands inside a quiet window, so the next full window decides. yield* TestClock.adjust("6 seconds"); - expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/); + expect(yield* Queue.take(writes)).toContain("vp i"); }), ); @@ -199,3 +243,110 @@ describe("ProjectSetupScriptRunner", () => { }), ); }); + +const runObservedSetup = Effect.fnUntraced(function* (command: string) { + const { writes, outputLines, emit, completion } = yield* setup({ command }); + yield* emit({ ...event, type: "output", data: "\x1b[?2004h" }); + const submitted = yield* Queue.take(writes); + const cwd = yield* HostProcess.WorkingDirectory; + const env = yield* HostProcess.Environment; + + // Enter becomes a newline at the terminal boundary; transport assertions below + // cover line-editor submissions and canonical TTY limits that bash -c bypasses. + const child = yield* Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make( + "/bin/bash", + ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")], + { + cwd, + env: { PATH: env.PATH }, + }, + ), + ); + return yield* Effect.all( + { + stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString), + stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString), + exitCode: handle.exitCode, + }, + { concurrency: "unbounded" }, + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); + yield* emit({ ...event, type: "output", data: submitted + "\n" }); + yield* emit({ ...event, type: "output", data: child.stdout + child.stderr }); + yield* emit({ ...event, type: "closed" }); + return { + submitted, + lines: yield* Queue.clear(outputLines), + exitCode: (yield* completion).exitCode, + }; +}); + +describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => { + it.live("submits one line while preserving multiline shell syntax and literal text", () => + Effect.gen(function* () { + const result = yield* runObservedSetup( + [ + "printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'", + "cat <<'END'", + "$literal \\path 雪", + "END", + "printf '%s\\n' done # trailing comment", + ].join("\r\n"), + ); + assert.equal(result.submitted.at(-1), "\r"); + assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/); + assert.deepEqual(result.lines, [ + "it's ready", + "literal \\n $(printf wrong) `printf wrong` café", + "$literal \\path 雪", + "done", + ]); + assert.equal(result.exitCode, 0); + }), + ); + + it.live("completes long scripts without exceeding canonical terminal line limits", () => + Effect.gen(function* () { + const expected = Array.from( + { length: 120 }, + (_, index) => `line-${index}: café 雪 'quoted' \\path`, + ); + const command = expected + .map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`) + .join("\n"); + const utf8 = new TextEncoder(); + assert.isAbove(utf8.encode(command).byteLength, 4_096); + + const result = yield* runObservedSetup(command); + assert.deepEqual(result.lines, expected); + assert.equal(result.exitCode, 0); + assert.equal(result.submitted.at(-1), "\r"); + assert.notInclude(result.submitted, "\n"); + // The runner can write before the shell switches the terminal out of canonical mode. + for (const line of result.submitted.slice(0, -1).split("\r")) { + assert.isBelow(utf8.encode(line).byteLength, 1_024); + } + }), + ); + + it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () => + Effect.gen(function* () { + const result = yield* runObservedSetup("printf '%s\\n' direct\\\n"); + assert.deepEqual(result.lines, ["direct"]); + assert.equal(result.exitCode, 0); + }), + ); + + it.live.each([ + { name: "an explicit exit", command: "exit 7", exitCode: 7 }, + { name: "a syntax error", command: "if then", exitCode: 2 }, + ])("reports a nonzero completion for $name", ({ command, exitCode }) => + Effect.gen(function* () { + const result = yield* runObservedSetup(command); + assert.equal(result.exitCode, exitCode); + }), + ); +}); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 8e7c3105b3..60084f648a 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -145,16 +145,14 @@ function completionSentinelPattern(token: string): RegExp { return new RegExp(`${COMPLETION_SENTINEL_PREFIX}_${token}:(-?\\d+)`); } +// ECMA-48: CSI, OSC, then any other escape as intermediates (0x20-0x2F) and one final byte. function stripTerminalControl(text: string): string { return text - .replace( - /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g, - "", - ) + .replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[ -/]*[0-~]/g, "") .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ""); } -// Line editors (zsh, fish, bash 5.1+) enable bracketed paste when they start reading a command. +// Line editors (zsh, fish, nu, bash 5.1+) enable bracketed paste when they start reading a command. const BRACKETED_PASTE_ON = "\x1b[?2004h"; const BRACKETED_PASTE_OFF = "\x1b[?2004l"; // Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first. @@ -166,17 +164,68 @@ function lineEditorReading(text: string, previous: boolean): boolean { return on === off ? previous : on > off; } -type CompletionShell = "posix" | "fish" | "powershell"; +type CompletionShell = "posix" | "fish" | "nushell" | "powershell"; function resolveCompletionShell(shell: string): CompletionShell | null { const name = (shell.split(/[/\\]/).at(-1) ?? shell).toLowerCase().replace(/\.exe$/, ""); if (name === "cmd") return null; if (name === "fish") return "fish"; + if (name === "nu") return "nushell"; if (name === "pwsh" || name === "powershell") return "powershell"; return "posix"; } -// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin. +const utf8 = new TextEncoder(); +// Canonical TTY input (before a line editor starts reading) caps a line below 1 KiB on Linux. +const POSIX_MAX_LINE_BYTES = 1_023; +const POSIX_APPEND = '__t3_command="$__t3_command"'; + +function encodePosixScript(text: string): string { + let encoded = ""; + for (const character of text) { + const code = character.charCodeAt(0); + if (character === "'") { + encoded += "'\\''"; + } else if (character === "\\" || code <= 0x1f || code === 0x7f) { + encoded += `\\0${code.toString(8).padStart(3, "0")}`; + } else { + encoded += character; + } + } + return encoded; +} + +// Line editors run each submitted line on its own, so every line must be a complete command. +function wrapPosixCommand(command: string, sentinel: string): string { + const normalized = command.replace(/\r\n/g, "\n"); + // The `_` suffix keeps trailing newlines; the subshell contains exits and syntax errors. + const evaluate = (payload: string) => + `( __t3_command=$(printf '%b_' ${payload}); eval "\${__t3_command%_}" ); printf '\\n${sentinel}%s\\n' "$?"`; + const inline = evaluate(`'${encodePosixScript(normalized)}'`); + if (utf8.encode(` ${inline}\r`).byteLength <= POSIX_MAX_LINE_BYTES) return inline; + + const maxChunkBytes = POSIX_MAX_LINE_BYTES - utf8.encode(` ${POSIX_APPEND}''\r`).byteLength; + const lines: string[] = []; + let prefix = "__t3_command="; + let chunk = ""; + let chunkBytes = 0; + for (const character of normalized) { + const encoded = encodePosixScript(character); + const bytes = utf8.encode(encoded).byteLength; + if (chunkBytes + bytes > maxChunkBytes) { + lines.push(`${prefix}'${chunk}'`); + prefix = POSIX_APPEND; + chunk = ""; + chunkBytes = 0; + } + chunk += encoded; + chunkBytes += bytes; + } + lines.push(`${prefix}'${chunk}'`, `${evaluate('"$__t3_command"')}; unset __t3_command`); + // The leading space gives every line the history suppression a short command gets. + return lines.join("\r "); +} + function wrapCommandForCompletion( command: string, shell: CompletionShell, @@ -188,8 +237,22 @@ function wrapCommandForCompletion( return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${sentinel}$__t3c"`; case "fish": return `begin\r${body}\rend; printf '\\n${sentinel}%s\\n' $status`; + case "nushell": { + const escaped = command.replace(/["\\\x00-\x1f]/g, (char) => + char === '"' || char === "\\" ? `\\${char}` : `\\u{${char.charCodeAt(0).toString(16)}}`, + ); + // Nu resolves imports before running cd; source a file rooted in the worktree. + return [ + "$env.LAST_EXIT_CODE = 0", + "let __t3f = try { mktemp --tmpdir-path $env.T3CODE_WORKTREE_PATH --suffix .nu .t3-setup-XXXXXXXX } catch {|e| print -e $e.msg; null }", + `if $__t3f == null { $env.LAST_EXIT_CODE = 1 } else { try { [$"rm --permanent ($__t3f | to nuon)" "${escaped}"] | str join (char newline) | save --force --raw $__t3f; ^$nu.current-exe --login --commands $"cd $env.T3CODE_WORKTREE_PATH; source ($__t3f | to nuon)" } catch {|e| if $e != null and $e.exit_code? == null { print -e $e.msg }; if $env.LAST_EXIT_CODE == 0 { $env.LAST_EXIT_CODE = 1 } } }`, + "let __t3c = $env.LAST_EXIT_CODE", + "try { if $__t3f != null and ($__t3f | path exists) { rm --permanent $__t3f } } catch {|e| print -e $e.msg }", + `print $"\\n${sentinel}($__t3c)"`, + ].join("; "); + } case "posix": - return `( ${body}\r); printf '\\n${sentinel}%s\\n' "$?"`; + return wrapPosixCommand(command, sentinel); } } @@ -517,9 +580,9 @@ export const make = Effect.gen(function* () { // Return once the terminal exists so callers can show it while a startup prompt waits. // PowerShell and cmd have no line-editor signal. yield* ( - completionShell === "posix" || completionShell === "fish" - ? readiness.wait - : Effect.succeed("ready" as const) + completionShell === "powershell" || completionShell === null + ? Effect.succeed("ready" as const) + : readiness.wait ).pipe( Effect.flatMap((shell) => shell === "exited" || commandLine === null diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 4604da894a..50d749c3fb 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -5,8 +5,10 @@ import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import { vi } from "vite-plus/test"; import * as ProcessRunner from "../processRunner.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/"); @@ -70,6 +72,30 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); + it.effect("keeps a literal .git in an Azure DevOps repository name", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-azure-git-suffix-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, [ + "remote", + "add", + "origin", + "https://dev.azure.com/Acme/Platform/_git/Tool.git", + ]); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity?.displayName).toBe("Acme/Platform/_git/Tool.git"); + expect(identity?.name).toBe("Tool.git"); + expect(sourceControlDefinitions.repositorySelector(identity)).toBe("Tool.git"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect("resolves the fetch remote of a partial clone", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -94,33 +120,53 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); - it.effect("returns the git top-level root path when resolving from a nested workspace", () => + it.effect("resolves a remote whose URL contains a space", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const repoRoot = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-repository-identity-nested-root-test-", + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-spaced-url-test-", }); - const nestedWorkspace = path.join(repoRoot, "packages", "web"); - yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true }); - yield* git(repoRoot, ["init"]); - yield* git(repoRoot, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "ssh://git@git.example.test/team repos/app.git"]); const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; - const identity = yield* resolver.resolve(nestedWorkspace); - const resolvedIdentityRoot = - identity?.rootPath === undefined ? "" : NodeFS.realpathSync.native(identity.rootPath); - const resolvedRepoRoot = NodeFS.realpathSync.native(repoRoot); - - expect(identity).not.toBeNull(); - expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code"); - expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe( - normalizeResolvedPath(resolvedRepoRoot), - ); + const identity = yield* resolver.resolve(cwd); + expect(identity?.locator.remoteUrl).toBe("ssh://git@git.example.test/team repos/app.git"); + expect(identity?.locator.remoteName).toBe("origin"); }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); + it.effect.each(["repo", "repo "] as const)( + "returns the git top-level root path when resolving from a nested workspace in %j", + (rootName) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-nested-root-test-", + }); + const repoRoot = path.join(tempDir, rootName); + const nestedWorkspace = path.join(repoRoot, "packages", "web"); + + yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true }); + yield* git(repoRoot, ["init"]); + yield* git(repoRoot, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(nestedWorkspace); + const resolvedIdentityRoot = + identity?.rootPath === undefined ? "" : NodeFS.realpathSync.native(identity.rootPath); + const resolvedRepoRoot = NodeFS.realpathSync.native(repoRoot); + + expect(identity).not.toBeNull(); + expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe( + normalizeResolvedPath(resolvedRepoRoot), + ); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect.each(["bare clone", "dot-bare"] as const)( "resolves a %s to its Git directory and the same identity as a checkout", (layout) => @@ -303,6 +349,95 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); + it.effect("uses the fork as the identity when gh repo set-default points at it", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-gh-default-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "git@github.com:julius/t3code-fork.git"]); + yield* git(cwd, ["remote", "add", "upstream", "git@github.com:T3Tools/t3code.git"]); + yield* git(cwd, ["config", "remote.origin.gh-resolved", "base"]); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity?.canonicalKey).toBe("github.com/julius/t3code-fork"); + expect(identity?.locator.remoteName).toBe("origin"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + + it.effect("follows an OWNER/REPO mark only to a remote that fetches that repository", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-gh-parent-test-", + }); + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const resolveFresh = () => resolver.resolve(cwd, { refresh: true }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "fork", "https://github.com/julius/t3code-fork.git"]); + yield* git(cwd, ["remote", "add", "main", "https://github.com/T3Tools/t3code.git"]); + yield* git(cwd, ["remote", "add", "upstream", "https://github.com/other/t3code.git"]); + yield* git(cwd, ["config", "remote.fork.gh-resolved", "t3tools/t3code"]); + const parent = yield* resolveFresh(); + expect(parent?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(parent?.locator).toEqual({ + source: "git-remote", + remoteName: "main", + remoteUrl: "https://github.com/T3Tools/t3code.git", + }); + + // No remote fetches the marked repository, and several marks leave gh's choice unknown. + yield* git(cwd, ["config", "remote.fork.gh-resolved", "someone/else"]); + expect((yield* resolveFresh())?.locator.remoteName).toBe("upstream"); + yield* git(cwd, ["config", "remote.fork.gh-resolved", "base"]); + yield* git(cwd, ["config", "remote.main.gh-resolved", "base"]); + expect((yield* resolveFresh())?.locator.remoteName).toBe("upstream"); + + // The same path on another HTTPS port is a different server. + yield* git(cwd, ["config", "--unset", "remote.fork.gh-resolved"]); + yield* git(cwd, ["config", "--unset", "remote.main.gh-resolved"]); + yield* git(cwd, ["remote", "add", "backup", "https://ghe.example.com:9443/acme/web.git"]); + yield* git(cwd, ["remote", "add", "ghe-fork", "https://ghe.example.com:8443/me/web.git"]); + yield* git(cwd, ["remote", "add", "ghe-parent", "https://ghe.example.com:8443/acme/web.git"]); + yield* git(cwd, ["config", "remote.ghe-fork.gh-resolved", "acme/web"]); + expect((yield* resolveFresh())?.locator.remoteName).toBe("ghe-parent"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + + it.effect("reads the project's gh default when the server inherited GIT_DIR", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-gh-default-git-dir-", + }); + const other = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-inherited-git-dir-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "git@github.com:julius/t3code-fork.git"]); + yield* git(cwd, ["remote", "add", "upstream", "git@github.com:T3Tools/t3code.git"]); + yield* git(cwd, ["config", "remote.origin.gh-resolved", "base"]); + yield* git(other, ["init"]); + yield* git(other, ["config", "remote.upstream.gh-resolved", "base"]); + + vi.stubEnv("GIT_DIR", path.join(other, ".git")); + yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity?.canonicalKey).toBe("github.com/julius/t3code-fork"); + expect(identity?.locator.remoteName).toBe("origin"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect("uses the last remote path segment as the repository name for nested groups", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index cdf9dc5e1b..826529e704 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -1,5 +1,7 @@ import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts"; +import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; +import { canonicalRepositoryPath, normalizeGitRemoteUrl } from "@t3tools/shared/git"; import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; @@ -12,7 +14,7 @@ import * as Path from "effect/Path"; import * as ProcessRunner from "../processRunner.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; -import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts"; +import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512; @@ -50,11 +52,10 @@ function isLocalRemoteUrl(url: string): boolean { function parseRemoteFetchUrls(stdout: string): Map { const remotes = new Map(); - for (const line of stdout.split("\n")) { - const trimmed = line.trim(); - if (trimmed.length === 0) continue; + for (const line of stdout.split(/\r?\n/)) { + // Git uses a tab before the URL and one space before the direction; both can occur in URLs. // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. - const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed); + const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line); if (!match) continue; const [, remoteName = "", remoteUrl = "", direction = ""] = match; if ( @@ -70,9 +71,43 @@ function parseRemoteFetchUrls(stdout: string): Map { return remotes; } +// `gh repo set-default` marks one remote with `base`, or with OWNER/REPO when it picked a +// parent repository. gh reads PRs from that repository, so the identity follows the mark when +// a remote fetches it. The locator must name a real remote: review checkouts fetch through it. +function pickMarkedRemote( + remotes: ReadonlyMap, + resolved: string, +): { readonly remoteName: string; readonly remoteUrl: string } | null { + const marks = resolved.split("\n").flatMap((line) => { + const match = /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()); + const remoteUrl = match?.[1] === undefined ? undefined : remotes.get(match[1]); + return match?.[1] && match[2] && remoteUrl + ? [{ remoteName: match[1], remoteUrl, value: match[2] }] + : []; + }); + // gh's choice is ambiguous with several marks; GitHubSourceControlProvider ignores them too. + const [mark, ...others] = marks; + if (!mark || others.length > 0) return null; + if (mark.value === "base") return { remoteName: mark.remoteName, remoteUrl: mark.remoteUrl }; + // Compare hosts with HTTP ports kept: one hostname can serve separate forges on two ports. + const host = parseGitRemoteHost(mark.remoteUrl)?.host; + const markedPath = mark.value.toLowerCase(); + const [remoteName, remoteUrl] = + [...remotes.entries()].find( + ([, url]) => + parseGitRemoteHost(url)?.host === host && + normalizeGitRemoteUrl(url).split("/").slice(1).join("/") === markedPath, + ) ?? []; + return remoteName && remoteUrl ? { remoteName, remoteUrl } : null; +} + function pickPrimaryRemote( remotes: ReadonlyMap, + resolved: string, ): { readonly remoteName: string; readonly remoteUrl: string } | null { + const marked = pickMarkedRemote(remotes, resolved); + if (marked) return marked; + for (const preferredRemoteName of ["upstream", "origin"] as const) { const remoteUrl = remotes.get(preferredRemoteName); if (remoteUrl) { @@ -88,7 +123,13 @@ function pickPrimaryRemote( function repositoryPathOf(canonicalKey: string, remoteUrl: string): string { const canonicalPath = canonicalKey.split("/").slice(1).join("/"); const displayPath = repositoryPathFromRemoteUrl(remoteUrl); - return displayPath?.toLowerCase() === canonicalPath ? displayPath : canonicalPath; + if (displayPath === null) return canonicalPath; + // A host that names repositories literally keeps the `.git` the display path drops. + return ( + [displayPath, `${displayPath}.git`].find( + (path) => canonicalRepositoryPath(path) === canonicalRepositoryPath(canonicalPath), + ) ?? canonicalPath + ); } function buildRepositoryOrigin( @@ -137,12 +178,17 @@ class RepositoryIdentityCacheKey extends Data.Class<{ readonly isBare: boolean; }> {} +const gitEnv = (platform: NodeJS.Platform): NodeJS.ProcessEnv => ({ + ...unsetInheritedRepositoryEnv(process.env, platform), + ...explicitBareRepositoryEnv(process.env, platform), +}); + const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")( function* (cwd: string) { const processRunner = yield* ProcessRunner.ProcessRunner; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform); + const env = gitEnv(yield* HostProcess.Platform); // `git -C` cannot enter a missing folder or a file, so every probe below would fail. const isFolder = yield* fileSystem.stat(cwd).pipe( @@ -165,7 +211,8 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver. return null; } if (topLevelResult.value.code === 0) { - const rootPath = topLevelResult.value.stdout.trim(); + // Paths may end in spaces, so strip only git's line terminator. + const rootPath = topLevelResult.value.stdout.replace(/\r?\n$/, ""); return rootPath.length > 0 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false }) : null; @@ -209,9 +256,7 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver. if (bareResult._tag === "None" || bareResult.value.timedOut) return null; if (bareResult.value.code !== 0) continue; - const [isBare, rootPath = ""] = bareResult.value.stdout - .split("\n") - .map((line) => line.trim()); + const [isBare, rootPath = ""] = bareResult.value.stdout.split(/\r?\n/); // A checkout's .git directory contains remotes but is not a project root. return isBare === "true" && rootPath.length > 0 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true }) @@ -227,20 +272,31 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn( cacheKey: RepositoryIdentityCacheKey, ): Effect.fn.Return { const processRunner = yield* ProcessRunner.ProcessRunner; - const remoteResult = yield* processRunner - .run({ - command: "git", - args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), "remote", "-v"], - env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform), - timeoutBehavior: "timedOutResult", - }) - .pipe(Effect.option); + const env = gitEnv(yield* HostProcess.Platform); + const runGit = (args: ReadonlyArray) => + processRunner + .run({ + command: "git", + args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), ...args], + env, + timeoutBehavior: "timedOutResult", + }) + .pipe(Effect.option); + const [remoteResult, resolvedResult] = yield* Effect.all( + [runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])], + { concurrency: "unbounded" }, + ); if (remoteResult._tag === "None" || remoteResult.value.code !== 0) { return null; } const remotes = parseRemoteFetchUrls(remoteResult.value.stdout); - const remote = pickPrimaryRemote(remotes); + // Exits 1 when no remote has a mark. + const resolved = + resolvedResult._tag === "Some" && resolvedResult.value.code === 0 + ? resolvedResult.value.stdout + : ""; + const remote = pickPrimaryRemote(remotes, resolved); return remote ? buildRepositoryIdentity({ ...remote, diff --git a/apps/server/src/project/ScratchThreadPromotion.ts b/apps/server/src/project/ScratchThreadPromotion.ts index f8d28a9fe0..91ef48adae 100644 --- a/apps/server/src/project/ScratchThreadPromotion.ts +++ b/apps/server/src/project/ScratchThreadPromotion.ts @@ -7,6 +7,7 @@ import { import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -50,6 +51,9 @@ const make = Effect.gen(function* () { const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; const random = yield* SecureRandom.SecureRandom; const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const realPath = (folder: string) => + fileSystem.realPath(folder).pipe(Effect.orElseSucceed(() => folder)); const fail = (reason: string) => (cause: unknown) => new ScratchThreadPromotionError({ reason, cause }); @@ -76,7 +80,7 @@ const make = Effect.gen(function* () { if ( folder === undefined || scratchRoot === undefined || - path.dirname(folder) !== scratchRoot || + (yield* realPath(path.dirname(folder))) !== (yield* realPath(scratchRoot)) || !(isScratch || alreadyPromoted) ) { return yield* new ScratchThreadPromotionError({ diff --git a/apps/server/src/project/gitCloneProgress.ts b/apps/server/src/project/gitCloneProgress.ts index f1d75b532b..b74ecf6da8 100644 --- a/apps/server/src/project/gitCloneProgress.ts +++ b/apps/server/src/project/gitCloneProgress.ts @@ -16,7 +16,10 @@ const STAGE_PREFIXES: ReadonlyArray = [ [/^Checking out files/, "checkout"], ]; -const PERCENT = /:\s+(\d+)%\s+\((\d+)\/(\d+)\)(?:,\s*(.*?))?\s*(?:,\s*done\.)?\s*$/; +// Linear on hostile remote output: the tail is trimmed in code (optional `\s*`/`.*?` groups backtrack +// cubically), and `s` lets it span U+2028 so a failed `$` cannot retry at every later counter. +const PERCENT = /:\s+(\d+)%\s+\((\d+)\/(\d+)\)(.*)$/s; +const DONE_SUFFIX = ", done."; /** Pass each bare-CR progress redraw as a separate line. */ export function parseGitCloneProgressLine(line: string): GitCloneProgressLine | null { @@ -26,8 +29,11 @@ export function parseGitCloneProgressLine(line: string): GitCloneProgressLine | const stage = stageEntry[1]; const match = PERCENT.exec(trimmed); if (!match) return { stage, percent: null, detail: null }; + let tail = (match[4] ?? "").trimEnd(); + if (tail.endsWith(DONE_SUFFIX)) tail = tail.slice(0, -DONE_SUFFIX.length).trimEnd(); + if (tail.length > 0 && !tail.startsWith(",")) return { stage, percent: null, detail: null }; const percent = Number(match[1]); - const rawDetail = match[4]?.trim() ?? ""; + const rawDetail = tail.slice(1).trim(); const detail = rawDetail.length > 0 && rawDetail !== "done." ? rawDetail : null; return { stage, diff --git a/apps/server/src/project/worktreeContainer.test.ts b/apps/server/src/project/worktreeContainer.test.ts new file mode 100644 index 0000000000..b10f8db93d --- /dev/null +++ b/apps/server/src/project/worktreeContainer.test.ts @@ -0,0 +1,94 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; + +import * as ProcessRunner from "../processRunner.ts"; +import { makeIsWorktreeContainer } from "./worktreeContainer.ts"; + +const git = Effect.fn("worktreeContainerTest.git")(function* ( + cwd: string, + ...args: ReadonlyArray +) { + const processRunner = yield* ProcessRunner.ProcessRunner; + return yield* processRunner.run({ + command: "git", + args: ["-C", cwd, "-c", "user.email=t@t", "-c", "user.name=t", ...args], + }); +}); + +it.layer(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))( + "isWorktreeContainer", + (it) => { + it.effect("is true only for a folder of worktrees around metadata that is no checkout", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const isWorktreeContainer = yield* makeIsWorktreeContainer; + const fixture = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-container-test-" }); + + const source = path.join(fixture, "source"); + yield* fileSystem.makeDirectory(source); + yield* git(source, "init", "-b", "develop"); + yield* fileSystem.writeFileString(path.join(source, "README.md"), "readme\n"); + yield* git(source, "add", "README.md"); + yield* git(source, "commit", "-m", "init"); + + const makeContainer = Effect.fn(function* (name: string, coreBare: boolean) { + const root = path.join(fixture, name); + yield* fileSystem.makeDirectory(root); + yield* git(fixture, "clone", "--bare", source, path.join(root, ".bare")); + yield* fileSystem.writeFileString(path.join(root, ".git"), "gitdir: ./.bare\n"); + yield* git(root, "worktree", "add", "develop", "develop"); + yield* git(root, "config", "core.bare", String(coreBare)); + return root; + }); + const makeSeparateGitDirCheckout = Effect.fn(function* (name: string) { + const root = path.join(fixture, name); + yield* fileSystem.makeDirectory(root); + yield* git(root, "init", "-b", "develop", "--separate-git-dir", ".metadata", "."); + return root; + }); + + const container = yield* makeContainer("container", false); + assert.isTrue(yield* isWorktreeContainer(container), "container"); + assert.isFalse(yield* isWorktreeContainer(path.join(container, "develop")), "its worktree"); + + const linked = path.join(fixture, "link"); + yield* fileSystem.symlink(container, linked); + assert.isTrue(yield* isWorktreeContainer(linked), "container through a symlink"); + + // The issue's steps leave core.bare set; Initialize Git would clear it later. + const bare = yield* makeContainer("bare", true); + assert.isTrue(yield* isWorktreeContainer(bare), "core.bare container"); + + // Git allows an orphan worktree before the first commit: no index, yet a valid checkout. + const fresh = yield* makeSeparateGitDirCheckout("fresh"); + yield* git(fresh, "worktree", "add", "--orphan", "-b", "feature", "../fresh-feature"); + assert.isFalse(yield* isWorktreeContainer(fresh), "fresh checkout with an orphan worktree"); + + const checkout = yield* makeSeparateGitDirCheckout("checkout"); + yield* fileSystem.writeFileString(path.join(checkout, "README.md"), "readme\n"); + yield* git(checkout, "add", "README.md"); + yield* git(checkout, "commit", "-m", "init"); + yield* git(checkout, "worktree", "add", "worktrees/feature", "-b", "feature"); + assert.isFalse(yield* isWorktreeContainer(checkout), "checkout with a nested worktree"); + + const outside = path.join(fixture, "outside"); + yield* git( + fixture, + "clone", + "--no-checkout", + "--separate-git-dir", + path.join(outside, ".metadata"), + source, + outside, + ); + yield* git(outside, "worktree", "add", "../outside-feature", "-b", "feature"); + assert.isFalse(yield* isWorktreeContainer(outside), "worktrees outside the folder"); + }), + ); + }, +); diff --git a/apps/server/src/project/worktreeContainer.ts b/apps/server/src/project/worktreeContainer.ts new file mode 100644 index 0000000000..f20e9c4375 --- /dev/null +++ b/apps/server/src/project/worktreeContainer.ts @@ -0,0 +1,95 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import * as ProcessRunner from "../processRunner.ts"; +import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; + +const parseGitfileTarget = (contents: string): string | undefined => { + const firstLine = contents.split(/\r?\n/u, 1)[0] ?? ""; + if (!firstLine.startsWith("gitdir:")) return undefined; + const target = firstLine.slice("gitdir:".length).trim(); + return target === "" ? undefined : target; +}; + +const splitNul = (stdout: string) => stdout.split("\0").filter((entry) => entry !== ""); + +/** + * Whether a folder only holds a repository's metadata and worktrees: its `.git` file points at + * metadata inside it, a linked worktree lives inside it, and either the repository is bare or it + * has commits but no index. A checkout whose tracked files are all deleted keeps its index, and a + * fresh one has no commit. Anything this cannot establish answers false. + */ +export const makeIsWorktreeContainer = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processRunner = yield* ProcessRunner.ProcessRunner; + const platform = yield* HostProcess.Platform; + const env = { + ...unsetInheritedRepositoryEnv(process.env, platform), + ...explicitBareRepositoryEnv(process.env, platform), + }; + + const realPath = (target: string) => fileSystem.realPath(target).pipe(Effect.option); + const isInside = (parent: string, child: string) => { + const relative = path.relative(parent, child); + return ( + relative !== "" && + relative !== ".." && + !relative.startsWith(`..${path.sep}`) && + !path.isAbsolute(relative) + ); + }; + + return Effect.fn("ProjectService.isWorktreeContainer")(function* (workspaceRoot: string) { + // A `.git` directory is an ordinary checkout, so only a gitfile costs any Git process. + const gitfileTarget = yield* fileSystem.readFileString(path.join(workspaceRoot, ".git")).pipe( + Effect.map(parseGitfileTarget), + Effect.orElseSucceed(() => undefined), + ); + if (gitfileTarget === undefined) return false; + const root = yield* realPath(workspaceRoot); + const gitDir = yield* realPath(path.resolve(workspaceRoot, gitfileTarget)); + if (root._tag === "None" || gitDir._tag === "None") return false; + if (!isInside(root.value, gitDir.value)) return false; + + const git = (args: ReadonlyArray) => + processRunner + .run({ + command: "git", + args: ["-C", workspaceRoot, ...args], + env, + timeoutBehavior: "timedOutResult", + }) + .pipe( + Effect.map((result) => (result.code === 0 && !result.timedOut ? result.stdout : null)), + Effect.orElseSucceed(() => null), + ); + + // Initializing Git in a bare container clears core.bare, so it is refused while still bare. + const isBare = yield* git(["rev-parse", "--is-bare-repository"]); + if (isBare === null) return false; + if (isBare.trim() !== "true") { + const hasCommit = yield* git(["rev-parse", "--quiet", "--verify", "HEAD^{commit}"]); + if (hasCommit === null) return false; + const hasIndex = yield* fileSystem + .exists(path.join(gitDir.value, "index")) + .pipe(Effect.orElseSucceed(() => true)); + if (hasIndex) return false; + } + + const worktrees = yield* git(["worktree", "list", "--porcelain", "-z"]); + if (worktrees === null) return false; + // The first entry is the main worktree, which Git reports as the metadata directory here. + const linkedWorktreePaths = splitNul(worktrees) + .filter((field) => field.startsWith("worktree ")) + .slice(1) + .map((field) => field.slice("worktree ".length)); + for (const worktreePath of linkedWorktreePaths) { + const worktree = yield* realPath(worktreePath); + if (worktree._tag === "Some" && isInside(root.value, worktree.value)) return true; + } + return false; + }); +}); diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index b1cf5c4f34..30915b31d4 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -9,6 +9,7 @@ import { ProviderInstanceId } from "@t3tools/contracts"; import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; import * as EffectAcpErrors from "effect-acp/errors"; @@ -20,6 +21,7 @@ import { logoutAcpRegistry, normalizeAcpRegistryAuthMethods, normalizeAcpRegistryCommands, + probeAcpRegistryConfiguration, } from "@t3tools/provider-acp-registry/testing"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; @@ -64,6 +66,22 @@ describe("ACP Registry probe", () => { { value: "gpt-5.4", name: "Duplicate" }, ], }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + { + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue: "ask", + options: [{ value: "ask", name: "Ask" }], + }, ], }, modelConfigId: "model", @@ -86,7 +104,24 @@ describe("ACP Registry probe", () => { ], models: [{ id: "gpt-5.4", name: "GPT-5.4", description: null }], currentModelId: "gpt-5.4", - configOptions: [], + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + options: [{ id: "high", label: "High" }], + currentValue: "high", + role: "reasoning", + }, + { + id: "mode", + label: "Mode", + type: "select", + options: [{ id: "ask", label: "Ask" }], + currentValue: "ask", + }, + ], + modelOptionIds: ["effort"], sessionManagement: { canList: true, canLoad: true, @@ -375,10 +410,63 @@ describe("ACP Registry probe", () => { }).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - Effect.scoped, ); }); + it.live.each(["succeeds", "fails"] as const)( + "deletes its health-probe session when deletion is advertised and %s", + (deleteOutcome) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "acp-probe-delete-" }); + const requestLogPath = NodePath.join(directory, "requests.ndjson"); + const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ + search: () => Effect.die("unused search"), + prepare: () => Effect.die("unused prepare"), + inspect: () => Effect.die("unused inspect"), + uninstallManagedBinary: () => Effect.die("unused uninstall"), + resolve: () => + Effect.succeed({ + agent: { + id: "mock-agent", + name: "Mock Agent", + version: "1.0.0", + description: "ACP probe cleanup test agent", + distribution: { npx: { package: "mock-agent@1.0.0" } }, + }, + distribution: "npx" as const, + spawn: { + command: "node", + args: [mockAgentPath], + env: { + ...process.env, + T3_ACP_V2_MANAGEMENT: "1", + T3_ACP_REQUEST_LOG_PATH: requestLogPath, + ...(deleteOutcome === "fails" ? { T3_ACP_FAIL_DELETE_SESSION: "1" } : {}), + }, + }, + }), + }); + + const result = yield* probeAcpRegistryConfiguration({ + instanceId, + settings: decodeSettings({ agentId: "mock-agent" }), + cwd: process.cwd(), + environment: process.env, + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + expect(result.probe.ready).toBe(true); + expect(result.probe.sessionManagement.canDelete).toBe(true); + + const requests = (yield* fs.readFileString(requestLogPath)) + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line)); + expect(requests.filter((request) => request.method === "session/delete")).toEqual([ + expect.objectContaining({ params: { sessionId: "mock-session-1" } }), + ]); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it("distinguishes authentication failures from generic probe failures", () => { const advertised = normalizeAcpRegistryAuthMethods([ { id: "grok-login", name: "Log in with Grok" }, diff --git a/apps/server/src/provider/AcpRegistrySessions.ts b/apps/server/src/provider/AcpRegistrySessions.ts new file mode 100644 index 0000000000..43c5b827f0 --- /dev/null +++ b/apps/server/src/provider/AcpRegistrySessions.ts @@ -0,0 +1,271 @@ +import { + AcpRegistryOperationError, + CommandId, + ThreadId, + type AcpRegistryImportSessionInput, + type AcpRegistryImportSessionResult, + type Project, + type ProjectId, + type ProviderDriverKind, + type ProviderInstanceId, +} from "@t3tools/contracts"; +import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Result from "effect/Result"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as AgentSessionImporter from "../project/AgentSessionImporter.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts"; +import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; +import * as ProviderRegistry from "./ProviderRegistry.ts"; + +export const importedThreadId = (input: { + readonly driver: ProviderDriverKind; + readonly instanceId: ProviderInstanceId; + readonly sessionId: string; +}) => + IdAllocator.deriveThreadFromProviderThread({ + driver: input.driver, + providerInstanceId: input.instanceId, + nativeThreadId: input.sessionId, + }); + +export class AcpRegistrySessions extends Context.Service< + AcpRegistrySessions, + { + readonly project: (projectId: ProjectId) => Effect.Effect; + readonly sessionManager: (instanceId: ProviderInstanceId) => Effect.Effect< + { + readonly instance: ProviderInstance; + readonly manager: NonNullable; + }, + AcpRegistryOperationError + >; + readonly findOwner: (input: { + readonly driver: ProviderDriverKind; + readonly instanceId: ProviderInstanceId; + readonly sessionId: string; + }) => Effect.Effect; + /** + * Binds a native ACP session to a T3 thread and copies its history in. Importing a + * session whose thread still lacks its history repairs that thread instead. + */ + readonly importSession: ( + input: AcpRegistryImportSessionInput, + ) => Effect.Effect; + } +>()("t3/provider/AcpRegistrySessions") {} + +const make = Effect.gen(function* () { + const projectService = yield* ProjectService.ProjectService; + const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter; + const random = yield* SecureRandom.SecureRandom; + const sql = yield* SqlClient.SqlClient; + + const findOwner = Effect.fn("AcpRegistrySessions.findOwner")(function* (input: { + readonly driver: ProviderDriverKind; + readonly instanceId: ProviderInstanceId; + readonly sessionId: string; + }) { + const rows = yield* sql<{ readonly thread_id: string }>` + SELECT provider.thread_id + FROM orchestration_v2_projection_provider_threads AS provider + JOIN orchestration_v2_projection_threads AS thread ON thread.thread_id = provider.thread_id + WHERE provider.driver = ${input.driver} + AND provider.provider_instance_id = ${input.instanceId} + AND json_extract(provider.payload_json, '$.nativeThreadRef.nativeId') = ${input.sessionId} + AND thread.deleted_at IS NULL + ORDER BY thread.updated_at DESC + LIMIT 1 + `.pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not inspect ACP session ownership.", + cause, + }), + ), + ); + return rows[0] ? ThreadId.make(rows[0].thread_id) : null; + }); + + const project = Effect.fn("AcpRegistrySessions.project")(function* (projectId: ProjectId) { + const found = yield* projectService.getById(projectId).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "project_not_found", + message: `Project ${projectId} is unavailable.`, + cause, + }), + ), + ); + return yield* Effect.fromOption( + found, + () => + new AcpRegistryOperationError({ + reason: "project_not_found", + message: `Project ${projectId} was not found.`, + }), + ); + }); + + const sessionManager = Effect.fn("AcpRegistrySessions.sessionManager")(function* ( + instanceId: ProviderInstanceId, + ) { + const instance = yield* providerInstances.getInstance(instanceId); + if (instance === undefined) { + return yield* new AcpRegistryOperationError({ + reason: "instance_not_found", + message: `Provider instance ${instanceId} was not found.`, + }); + } + if (instance.acpSessionManagement === undefined) { + return yield* new AcpRegistryOperationError({ + reason: "session_list_unsupported", + message: `Provider instance ${instanceId} does not expose ACP session management.`, + }); + } + return { instance, manager: instance.acpSessionManagement }; + }); + + const importSession = Effect.fn("AcpRegistrySessions.importSession")(function* ( + input: AcpRegistryImportSessionInput, + ) { + const { workspaceRoot } = yield* project(input.projectId); + const { instance } = yield* sessionManager(input.instanceId); + const providerSnapshot = yield* instance.snapshot.getSnapshot; + if ( + providerSnapshot.nativeSessions?.canLoad !== true && + providerSnapshot.nativeSessions?.canResume !== true + ) { + return yield* new AcpRegistryOperationError({ + reason: "session_resume_unsupported", + message: "The ACP agent cannot load or resume native sessions.", + }); + } + const threadId = importedThreadId({ + driver: instance.driverKind, + instanceId: input.instanceId, + sessionId: input.sessionId, + }); + const owner = yield* findOwner({ + driver: instance.driverKind, + instanceId: input.instanceId, + sessionId: input.sessionId, + }); + if (owner !== null && owner !== threadId) return { threadId: owner, imported: false } as const; + const existing = yield* threadManagement.getThreadShell(threadId).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not inspect the imported ACP session mapping.", + cause, + }), + ), + ); + if (existing !== null) { + const repairing = AgentSessionImporter.isNativeHistoryPending({ + historyOrigin: existing.historyOrigin, + hasRun: existing.latestRunId !== null, + }); + yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not import the ACP session history.", + cause, + }), + ), + ); + return { threadId, imported: repairing } as const; + } + + const provider = (yield* providerRegistry.getProviders).find( + (candidate) => candidate.instanceId === input.instanceId, + ); + const model = + provider?.models.find((candidate) => candidate.isDefault)?.slug ?? + provider?.models[0]?.slug ?? + "default"; + const commandId = CommandId.make(yield* random.uuidV4()); + const launched = yield* Effect.result( + startup.enqueueCommand( + threadLaunch.launch({ + commandId, + threadId, + projectId: input.projectId, + title: input.title ?? "Imported ACP session", + modelSelection: { instanceId: input.instanceId, model }, + runtimeMode: "approval-required", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + importedNativeThread: { + ref: { + driver: instance.driverKind, + nativeId: input.sessionId, + strength: "strong", + }, + metadata: { + itemIdentityVersion: 2, + ...(input.title === undefined ? {} : { title: input.title }), + ...(input.updatedAt === undefined ? {} : { updatedAt: input.updatedAt }), + }, + }, + createdBy: "user", + creationSource: "web", + }), + ), + ); + if (Result.isFailure(launched)) { + const racedImport = yield* threadManagement.getThreadShell(threadId).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not inspect the imported ACP session after launch failed.", + cause, + }), + ), + ); + if (racedImport !== null) return { threadId, imported: false } as const; + return yield* new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not create a 456code thread for the ACP session.", + cause: launched.failure, + }); + } + // The thread is usable without its history, so a failed read only logs. + yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( + Effect.catch((cause) => + Effect.logWarning("Could not import ACP session history", { + instanceId: input.instanceId, + sessionId: input.sessionId, + cause, + }), + ), + ); + return { threadId, imported: true } as const; + }, coordinator.withSessionMutation); + + return AcpRegistrySessions.of({ project, sessionManager, findOwner, importSession }); +}); + +export const layer = Layer.effect(AcpRegistrySessions, make); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 8cdd52d202..2a7d02fc28 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -35,6 +35,7 @@ import { ProjectCloneTracker } from "../project/ProjectCloneTracker.ts"; import { ProjectService } from "../project/ProjectService.ts"; import { ProjectSetupScriptRunner } from "../project/ProjectSetupScriptRunner.ts"; import { PullRequestReviewGuideService } from "../pullRequest/PullRequestReviewGuideService.ts"; +import { PullRequestService } from "../pullRequest/PullRequestService.ts"; import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts"; import { SecretRequests } from "../secrets/SecretRequests.ts"; import { ServerSettingsService } from "../serverSettings.ts"; @@ -43,6 +44,7 @@ import { GitVcsDriver } from "../vcs/GitVcsDriver.ts"; import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts"; import { buildCodexAdditionalContext } from "./CodexDeveloperInstructions.ts"; import { DocumentText } from "./DocumentText.ts"; +import { EnvironmentThemeService } from "../environmentTheme.ts"; import { ProviderRegistry } from "./ProviderRegistry.ts"; import budget from "./agentContextBudget.json" with { type: "json" }; @@ -51,6 +53,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(AssetSigner)({}), Layer.mock(DeviceService)({}), Layer.mock(DocumentText)({}), + Layer.mock(EnvironmentThemeService)({}), Layer.mock(GitVcsDriver)({}), Layer.mock(GitWorkflowService)({}), Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }), @@ -68,6 +71,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(ProviderAdapterRegistryV2)({}), Layer.mock(ProviderRegistry)({}), Layer.mock(PullRequestReviewGuideService)({}), + Layer.mock(PullRequestService)({}), Layer.mock(RemoteDelegation)({}), Layer.mock(ScheduledTaskService)({}), Layer.mock(SecretRequests)({}), @@ -114,13 +118,16 @@ const layerAdvertisedTools = McpHttpServer.layerTools.pipe( ); // Claude Code loads these tools up front instead of behind ToolSearch, outside this budget. -it.effect("only request_secret asks Claude Code to load it up front", () => +it.effect("only request_secret and send_to_user ask Claude Code to load them up front", () => Effect.gen(function* () { const mcp = yield* McpServer.McpServer; const alwaysLoad = mcp.tools .filter(({ tool }) => tool._meta?.["anthropic/alwaysLoad"] !== undefined) .map(({ tool }) => [tool.name, tool._meta]); - expect(alwaysLoad).toEqual([["request_secret", { "anthropic/alwaysLoad": true }]]); + expect(alwaysLoad).toEqual([ + ["request_secret", { "anthropic/alwaysLoad": true }], + ["send_to_user", { "anthropic/alwaysLoad": true }], + ]); }).pipe(Effect.provide(layerAdvertisedTools)), ); diff --git a/apps/server/src/provider/AntigravityAuth.test.ts b/apps/server/src/provider/AntigravityAuth.test.ts index d7099ec2bf..936cfcb6bc 100644 --- a/apps/server/src/provider/AntigravityAuth.test.ts +++ b/apps/server/src/provider/AntigravityAuth.test.ts @@ -320,6 +320,35 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("AntigravityAuth" }), ); + it.effect("does not blame the network when the runtime never answers initialize", () => + Effect.gen(function* () { + const initializing = yield* Deferred.make(); + const harness = yield* makeHarness({ + beforeInitialize: Deferred.succeed(initializing, undefined).pipe( + Effect.andThen(Effect.never), + ), + }); + yield* harness.auth.controller.start(owner); + yield* Deferred.await(initializing); + const blamesNetwork = /reach(ed)? Google|network|ipv6/i; + + yield* TestClock.adjust("90 seconds"); + const stalled = yield* harness.auth.controller.subscribe(owner).pipe( + Stream.filter((state) => state.message !== "Starting Google sign-in."), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + assert.equal(stalled.phase, "starting"); + assert.notMatch(stalled.message ?? "", blamesNetwork); + assert.match(stalled.message ?? "", /not started|stuck/i); + + yield* TestClock.adjust("210 seconds"); + const failed = yield* phase(harness.auth, "failed"); + assert.notMatch(failed.message ?? "", blamesNetwork); + assert.match(failed.message ?? "", /not respond|may not run/i); + }), + ); + it.effect("keeps the expired message once the Google link was shown", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/apps/server/src/provider/AntigravityAuth.ts b/apps/server/src/provider/AntigravityAuth.ts index 90105dd4b7..fcaf41275d 100644 --- a/apps/server/src/provider/AntigravityAuth.ts +++ b/apps/server/src/provider/AntigravityAuth.ts @@ -31,11 +31,15 @@ import { import type { ProviderAuthController } from "./ProviderAuthService.ts"; const AUTH_TIMEOUT_MS = 300_000; -// Once initialized, a healthy agent shows the Google link or finishes within seconds. Its bundled -// Python has no IPv4 fallback race, so a host with broken IPv6 waits about two minutes per Google -// request. The hint is timed from initialize, not spawn: the one-file runtime unpacks itself on -// every launch, which can take about a minute on Windows before it answers at all. +// Once initialized, a healthy agent shows the Google link within seconds; its bundled Python has no +// IPv4 fallback, so broken IPv6 stalls each Google request. Startup is timed separately: the +// one-file runtime unpacks on every launch (about a minute on Windows) before it answers initialize. const NO_RESPONSE_HINT_MS = 30_000; +const STARTUP_HINT_MS = 90_000; +const NOT_STARTED_MESSAGE = + "Antigravity has not started after 90 seconds. Its runtime may be stuck starting on this machine."; +const NOT_RESPONDING_MESSAGE = + "Antigravity did not respond. Its runtime may not run on this machine."; const NO_RESPONSE_MESSAGE = "Antigravity has not reached Google after 30 seconds. Check this machine's network connection. Broken IPv6 is a common cause."; const UNREACHABLE_MESSAGE = @@ -55,6 +59,7 @@ interface AuthFlow { readonly expiresAtMillis: number; state: ProviderAuthState; pending: AntigravityAuthorizationUrl | undefined; + initialized: boolean; callbackSent: boolean; fiber: Fiber.Fiber | undefined; forwarding: Fiber.Fiber | undefined; @@ -270,25 +275,31 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < ), ); + const publishStartingHint = (flow: AuthFlow, delayMs: number, message: string) => + Effect.sleep(delayMs).pipe( + Effect.andThen( + lock.withPermits(1)( + Effect.gen(function* () { + if (activeFlow !== flow || flow.state.phase !== "starting") return; + yield* publishFlow(flow, { ...flow.state, message }); + }), + ), + ), + Effect.forkScoped, + ); + const runSignIn = Effect.fn("AntigravityAuth.runSignIn")( function* (flow: AuthFlow, stopSessions: Effect.Effect) { yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses)); const runtime = yield* options.makeRuntime({ onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url), }); + const startupHint = yield* publishStartingHint(flow, STARTUP_HINT_MS, NOT_STARTED_MESSAGE); // `start` reuses this memoized handshake. yield* runtime.initialize(); - yield* Effect.sleep(NO_RESPONSE_HINT_MS).pipe( - Effect.andThen( - lock.withPermits(1)( - Effect.gen(function* () { - if (activeFlow !== flow || flow.state.phase !== "starting") return; - yield* publishFlow(flow, { ...flow.state, message: NO_RESPONSE_MESSAGE }); - }), - ), - ), - Effect.forkScoped, - ); + flow.initialized = true; + yield* Fiber.interrupt(startupHint); + yield* publishStartingHint(flow, NO_RESPONSE_HINT_MS, NO_RESPONSE_MESSAGE); const started = yield* runtime.start(); yield* lock.withPermits(1)( Effect.gen(function* () { @@ -313,9 +324,11 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < Effect.fail( setupError( "start", - flow.state.phase === "starting" - ? UNREACHABLE_MESSAGE - : "Google sign-in expired. Start sign-in again.", + flow.state.phase !== "starting" + ? "Google sign-in expired. Start sign-in again." + : flow.initialized + ? UNREACHABLE_MESSAGE + : NOT_RESPONDING_MESSAGE, ), ), }), @@ -402,6 +415,7 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < expiresAtMillis, state, pending: undefined, + initialized: false, callbackSent: false, fiber: undefined, forwarding: undefined, diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index 3fc86eea94..aa873bc351 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -17,11 +17,12 @@ import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import { HttpClient, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as AntigravityInstallation from "./AntigravityInstallation.ts"; +import * as ModelManifest from "./ModelManifest.ts"; import { type AntigravityReleaseAsset } from "./antigravityRelease.ts"; const serverContents = "antigravity runtime\n"; @@ -126,6 +127,13 @@ interface HarnessOptions { readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"]; readonly useDefaultValidation?: boolean; + readonly connectTimeout?: boolean; + readonly manifest?: Effect.Effect; + readonly native?: boolean; + readonly nativeVersion?: string; + readonly nativeManifest?: (manifest: { version: string; url: string; sha512: string }) => unknown; + readonly beforeManifest?: Effect.Effect; + readonly updateChecksEnabled?: Effect.Effect; } const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( @@ -133,6 +141,7 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const digest = yield* Digest.Digest; const baseDir = options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" })); const platform = options.platform ?? hostPlatform; @@ -168,7 +177,10 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( }); const installation = yield* AntigravityInstallation.makeAntigravityInstallation({ baseDir, - releaseAsset: asset, + ...(options.native ? {} : { releaseAsset: asset }), + ...(options.updateChecksEnabled === undefined + ? {} + : { updateChecksEnabled: options.updateChecksEnabled }), ...(options.useDefaultValidation ? {} : { @@ -185,11 +197,43 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( Effect.provideService(HostProcess.Platform, platform), Effect.provideService(HostProcess.Architecture, arch), Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }), + Effect.provideService(ModelManifest.ModelManifest, { + current: options.manifest ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refreshInBackground: Effect.void, + }), Effect.provideService( HttpClient.HttpClient, HttpClient.make((request) => - Effect.sync(() => { + Effect.suspend(() => { requests.push(request.url); + if (request.url.includes("/manifests/")) { + return Effect.gen(function* () { + yield* options.beforeManifest ?? Effect.void; + const version = options.nativeVersion ?? "1.5.7"; + const folder = platform === "win32" ? "windows-x64" : "linux-x64"; + const manifest = { + version, + url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/${version}-123/${folder}/cli_${platform === "win32" ? "windows_x64.exe" : "linux_x64.tar.gz"}`, + sha512: Hex.encode(yield* digest.digest(Digest.sha512, archive).pipe(Effect.orDie)), + }; + return HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify(options.nativeManifest?.(manifest) ?? manifest)), + ); + }); + } + if (options.connectTimeout) { + return Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + cause: new Error("Connect Timeout Error (attempted address: dl.google.com:443)"), + }), + }), + ); + } const response = HttpClientResponse.fromWeb( request, new Response(null, { @@ -203,15 +247,17 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( }, }), ); - return Object.defineProperty(response, "stream", { - value: - options.body ?? - Stream.make( - archive.subarray(0, 31), - archive.subarray(31, 149), - archive.subarray(149), - ), - }); + return Effect.succeed( + Object.defineProperty(response, "stream", { + value: + options.body ?? + Stream.make( + archive.subarray(0, 31), + archive.subarray(31, 149), + archive.subarray(149), + ), + }), + ); }), ), ), @@ -242,6 +288,256 @@ const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease") }); it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => { + it.effect.each([...new Set(["win32", hostPlatform])] as NodeJS.Platform[])( + "migrates the legacy managed runtime to the native CLI on %s and retains the old release", + (platform) => + Effect.gen(function* () { + const archive = + platform === "win32" + ? Buffer.from(serverContents) + : Buffer.from( + "H4sIAAAAAAACE+3RMQ7CQAwEQNe8Ik8wgYj3XIFQCiiOCxK/56CJRA9CYqZZrxsXLpc2n2q5ze0en5LdYZpe2b1n5rhf5+d+m+MuY8j4guXaSu3n4z+V9f9DXXo5HzcBAAAAAAAAAADAz3sA56lbdQAoAAA=", + "base64", + ); + const { installation, validations, requests, fs, baseDir, stagingReleased } = + yield* makeHarness({ native: true, archive, platform, previous: true }); + yield* installation.start; + expect(yield* terminalState(installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + yield* Deferred.await(stagingReleased); + const resolved = yield* installation.resolve(); + expect(resolved).toMatchObject({ source: "managed", version: "1.5.7", harnessPath: null }); + expect(validations[0]?.executable.harnessPath).toBeNull(); + expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents); + expect(requests.some((url) => url.includes("/manifests/"))).toBe(true); + const restarted = yield* makeHarness({ + baseDir, + native: true, + archive, + platform, + nativeVersion: "1.5.6", + }); + expect(yield* restarted.installation.start).toMatchObject({ + phase: "verifying", + message: "Checking the installed runtime.", + }); + expect(yield* terminalState(restarted.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + expect(restarted.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual( + [], + ); + expect((yield* restarted.installation.resolve()).executablePath).toBe( + resolved.executablePath, + ); + }), + ); + + // These tar fixtures exercise the POSIX extraction path; Windows downloads one executable. + it.effect.skipIf(hostPlatform === "win32")( + "rejects unsafe native tar members before activation", + () => + Effect.gen(function* () { + for (const archive of [ + "H4sIAAAAAAACE+3OMQqDQBAFUI/iCYxZJPdZMIRtFHQN5PYOKbW2EN5j4P9iYCZPtXyW/C3111ylD69h+Gc45rk/U4r1NnXdI2be6lrG90XPbWvNS5xvAAAAAAAAAAAA4D523kNDtgAoAAA=", + "H4sIAAAAAAACE+3RMQ7CMBAEQNe8Ii8IBhzxHhcIpYDCcSLxewwNiJ4IiZlmb6+54vp+m691PJe8jPUWviI2x2F4ZvOZMe7Ta37sdzGlQ+hiWME81Vza+fCf3p7flbmVy2kTAAAAAAAAAAAA+Hl3jhn2/wAoAAA=", + "H4sIAAAAAAACE+3TPQrCQBAG0K09RY4wRoPn2UJCClOsG8Hbu6YJ2CtI3mvmp5li+PJcp7Hkx1Sf6VuiuQzDWpvPGtGft/69P0Z/itRF+oHlXnNp59M+5e3/XVnacLseEnv8v/zLv/wDAAAAAAAAAPyZF/c+VksAKAAA", + ]) { + const { installation, validations } = yield* makeHarness({ + native: true, + archive: Buffer.from(archive, "base64"), + platform: "linux", + previous: true, + }); + yield* installation.start; + expect((yield* terminalState(installation)).phase).toBe("failed"); + expect(validations).toEqual([]); + yield* expectPreviousRelease(installation); + } + }), + ); + + it.effect.each([true, false])( + "respects background update checks (%s) while allowing explicit installation", + (enabled) => + Effect.gen(function* () { + const { installation, requests } = yield* makeHarness({ + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + updateChecksEnabled: Effect.succeed(enabled), + }); + yield* installation.checkForUpdate; + if (enabled) { + yield* installation.changes.pipe( + Stream.filter((value) => value.version === "1.5.7"), + Stream.runHead, + ); + yield* installation.state; + expect(requests).toHaveLength(1); + } else { + yield* installation.changes.pipe(Stream.runHead); + expect(requests).toEqual([]); + } + yield* installation.start; + expect((yield* terminalState(installation)).phase).toBe("succeeded"); + }), + ); + + it.effect("keeps withdrawn native releases from activating or launching", () => + Effect.gen(function* () { + let withdrawn = false; + const manifest = Effect.sync(() => + withdrawn + ? ({ + ...ModelManifest.BUNDLED_MODEL_MANIFEST, + compatibility: [ + { + driver: "antigravity", + t3CodeRange: ">=0.0.42", + ranges: [{ range: ">=1.5.7", status: "broken" }], + }, + ], + } satisfies ModelManifest.ModelManifestData) + : ModelManifest.BUNDLED_MODEL_MANIFEST, + ); + const first = yield* makeHarness({ + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + previous: true, + manifest, + validate: () => + Effect.sync(() => { + withdrawn = true; + }), + }); + yield* first.installation.start; + expect((yield* terminalState(first.installation)).phase).toBe("failed"); + yield* expectPreviousRelease(first.installation); + withdrawn = false; + const retry = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + manifest, + }); + yield* retry.installation.start; + expect((yield* terminalState(retry.installation)).phase).toBe("succeeded"); + withdrawn = true; + expect(yield* retry.installation.resolve().pipe(Effect.flip)).toMatchObject({ + operation: "resolve", + }); + expect(yield* retry.installation.start.pipe(Effect.flip)).toMatchObject({ + operation: "start", + }); + const recovery = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeVersion: "1.5.6", + archive: Buffer.from("recovery runtime"), + platform: "win32", + manifest, + }); + yield* recovery.installation.checkForUpdate; + expect(yield* recovery.installation.state).toMatchObject({ + installedVersion: "1.5.7", + version: "1.5.6", + }); + yield* recovery.installation.start; + expect(yield* terminalState(recovery.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.6", + }); + }), + ); + + it.effect("discovers subsequent native releases from Google's CLI channel", () => + Effect.gen(function* () { + const first = yield* makeHarness({ + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + }); + yield* first.installation.start; + expect((yield* terminalState(first.installation)).phase).toBe("succeeded"); + const initialPath = (yield* first.installation.resolve()).executablePath; + const next = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeVersion: "1.5.8", + archive: Buffer.from("next runtime"), + platform: "win32", + }); + yield* next.installation.start; + expect(yield* terminalState(next.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.8", + }); + const nextPath = (yield* next.installation.resolve()).executablePath; + expect(nextPath).not.toBe(initialPath); + const republished = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeVersion: "1.5.8", + archive: Buffer.from("republished runtime"), + platform: "win32", + }); + yield* republished.installation.start; + expect((yield* terminalState(republished.installation)).phase).toBe("succeeded"); + expect((yield* republished.installation.resolve()).executablePath).not.toBe(nextPath); + const offline = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeManifest: () => ({}), + archive: Buffer.from("unused"), + platform: "win32", + }); + yield* offline.installation.start; + expect(yield* terminalState(offline.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.8", + }); + expect(offline.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual([]); + }), + ); + + it.effect.each([ + { + name: "invalid checksum", + change: (manifest: { version: string; url: string; sha512: string }) => ({ + ...manifest, + sha512: "0".repeat(128), + }), + }, + { + name: "foreign download", + change: (manifest: { version: string; url: string; sha512: string }) => ({ + ...manifest, + url: "https://example.com/agy.exe", + }), + }, + ])("rejects a native $name and preserves the legacy release", ({ change }) => + Effect.gen(function* () { + const { installation, validations } = yield* makeHarness({ + native: true, + nativeManifest: change, + archive: Buffer.from(serverContents), + platform: "win32", + previous: true, + }); + const result = yield* Effect.result(installation.start); + if (result._tag === "Success") + expect((yield* terminalState(installation)).phase).toBe("failed"); + expect(validations).toEqual([]); + yield* expectPreviousRelease(installation); + }), + ); + it.effect("reports missing Node before downloading the standalone provider runtime", () => Effect.gen(function* () { const { installation, requests, validations } = yield* makeHarness(); @@ -353,6 +649,73 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst }), ); + it.effect( + "names the connection failure instead of disk space when the download cannot connect", + () => + Effect.gen(function* () { + const { installation, validations } = yield* makeHarness({ connectTimeout: true }); + yield* installation.start; + const state = yield* terminalState(installation); + expect(state.phase).toBe("failed"); + expect(state.message).not.toMatch(/disk space/i); + expect(state.message).toMatch(/connect|network|download/i); + expect(validations).toEqual([]); + }), + ); + + // The runtime's own abort is a real process; Windows has no POSIX sh. + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "explains that the linux-arm64 runtime needs 4 KiB pages when it aborts on a 16 KiB kernel", + () => + Effect.gen(function* () { + const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // Google's linux-arm64 build aborts like this on Asahi and Raspberry Pi 5 kernels. + const spawner = ChildProcessSpawner.make((command) => + ChildProcess.isStandardCommand(command) && + String(command.command).endsWith(executableName) + ? realSpawner.spawn( + ChildProcess.make( + "sh", + [ + "-c", + "echo 'F1111 11:50:12.383176 page-size.cc:19] Check failed: sysconf(_SC_PAGE_SIZE) == kPageSize (16384 vs. 4096) Compile-time page size does not match runtime page size' >&2; kill -ABRT $$", + ], + { stdin: "pipe", stdout: "pipe", stderr: "pipe" }, + ), + ) + : realSpawner.spawn(command), + ); + const { installation } = yield* makeHarness({ + arch: "arm64", + useDefaultValidation: true, + spawner, + }); + yield* installation.start; + const state = yield* terminalState(installation); + expect(state.phase).toBe("failed"); + expect(state.message).toMatch(/page/i); + }), + ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "refuses a 16 KiB-page linux-arm64 kernel before downloading the runtime", + () => + Effect.gen(function* () { + const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => + ChildProcess.isStandardCommand(command) && command.command === "getconf" + ? realSpawner.spawn(ChildProcess.make("sh", ["-c", "echo 16384"], command.options)) + : realSpawner.spawn(command), + ); + const { installation, requests } = yield* makeHarness({ arch: "arm64", spawner }); + yield* installation.start; + const state = yield* terminalState(installation); + expect(state.phase).toBe("failed"); + expect(state.message).toMatch(/4 KiB/); + expect(requests).toEqual([]); + }), + ); + it.effect.each(["download", "extract", "active pointer"] as const)( "preserves the old runtime after an ENOSPC error during %s", (stage) => @@ -688,10 +1051,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst const windowsDirectory = path.join(baseDir, `windows-${name}`); yield* fs.makeDirectory(windowsDirectory); yield* fs.writeFileString(path.join(windowsDirectory, name), "cli"); - expect(yield* windows.resolve("agy", { PATH: windowsDirectory })).toMatchObject({ - executablePath: path.join(windowsDirectory, name), - harnessPath: null, - }); + const selected = yield* windows.resolve("agy", { PATH: windowsDirectory }); + expect(selected.harnessPath).toBeNull(); + expect((yield* fs.realPath(selected.executablePath)).toLowerCase()).toBe( + (yield* fs.realPath(path.join(windowsDirectory, name))).toLowerCase(), + ); } }), ); @@ -730,6 +1094,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst expect(yield* installation.resolve(executableName)).toMatchObject({ source: "override", }); + expect( + yield* installation + .resolve(`~/external/${executableName}`) + .pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)), + ).toMatchObject({ source: "override", executablePath: externalExecutable }); yield* fs.remove(externalHarness); expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({ operation: "resolve", @@ -779,14 +1148,29 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst it.effect("keeps leased releases available while new sessions resolve the new release", () => Effect.gen(function* () { - const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true }); + const manifestEntered = yield* Deferred.make(); + const releaseManifest = yield* Deferred.make(); + const { installation, fs, stagingReleased } = yield* makeHarness({ + native: true, + platform: "win32", + archive: Buffer.from(serverContents), + previous: true, + beforeManifest: Deferred.succeed(manifestEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseManifest)), + ), + }); const processScope = yield* Scope.make(); const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope)); - yield* installation.start; + const starting = yield* installation.start.pipe(Effect.forkScoped); + yield* Deferred.await(manifestEntered); + const concurrent = yield* installation.acquire().pipe(Scope.provide(processScope)); + expect(concurrent.executablePath).toBe(oldExecutable.executablePath); + yield* Deferred.succeed(releaseManifest, undefined); + yield* Fiber.join(starting); expect((yield* terminalState(installation)).phase).toBe("succeeded"); yield* Deferred.await(stagingReleased); const current = yield* installation.resolve(); - expect(current.version).toBe("fixture-new"); + expect(current.version).toBe("1.5.7"); expect(current.executablePath).not.toBe(oldExecutable.executablePath); expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents); expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" }); diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index 686d1d2947..27a40e48fb 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -1,4 +1,9 @@ // @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest or free-space query. +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import * as ModelManifest from "./ModelManifest.ts"; +import { resolveProviderCompatibility } from "./providerCompatibility.ts"; +import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease"; +import { compareSemverVersions } from "@t3tools/shared/semver"; import * as EffectNodeStream from "@effect/platform-node/NodeStream"; import { ProviderDriverKind, type ProviderInstallState } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -21,7 +26,7 @@ import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as NodeCrypto from "node:crypto"; @@ -29,23 +34,32 @@ import * as NodeFSP from "node:fs/promises"; import * as EffectAcpErrors from "effect-acp/errors"; import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { + ANTIGRAVITY_CLI_MANIFEST_BASE, + antigravityCliTarget, + parseAntigravityCliRelease, + type AntigravityCliReleaseAsset, +} from "./antigravityCliRelease.ts"; import { openZipArchive } from "../zipArchive.ts"; import { makeAntigravityAcpRuntime } from "./acp/AntigravityAcpSupport.ts"; import { buildAntigravityAcpSpawnInput, prepareAntigravityProfile, } from "./antigravityAuthSupport.ts"; -import { - resolveAntigravityReleaseAsset, - type AntigravityReleaseAsset, -} from "./antigravityRelease.ts"; +import { type AntigravityReleaseAsset } from "./antigravityRelease.ts"; const DRIVER = ProviderDriverKind.make("antigravity"); const DOWNLOAD_TIMEOUT = "45 minutes"; const VALIDATION_TIMEOUT = "90 seconds"; +const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024; +const MAX_EXECUTABLE_BYTES = 512 * 1024 * 1024; +const UPDATE_CHECK_INTERVAL = 60 * 60 * 1000; const FREE_SPACE_MARGIN = 256 * 1024 * 1024; const RECORD_MAX_BYTES = 8 * 1024; const RELEASE_RECORD = ".install-complete.json"; +const LARGE_PAGE_KERNEL_MESSAGE = + "Google's linux-arm64 Antigravity runtime needs a kernel with 4 KiB memory pages, and this kernel uses larger pages (as on Asahi Linux or Raspberry Pi 5). Use a remote environment or a custom Antigravity executable."; const ReleaseId = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u)); const ActiveRelease = Schema.Struct({ releaseId: ReleaseId }); @@ -53,7 +67,7 @@ const InstalledRelease = Schema.Struct({ releaseId: ReleaseId, version: Schema.String, executable: Schema.Struct({ name: Schema.String, bytes: Schema.Number }), - harness: Schema.Struct({ name: Schema.String, bytes: Schema.Number }), + harness: Schema.NullOr(Schema.Struct({ name: Schema.String, bytes: Schema.Number })), }); type InstalledRelease = typeof InstalledRelease.Type; const encodeActiveRelease = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease)); @@ -100,6 +114,7 @@ interface AntigravityInstallationService { ) => Effect.Effect; readonly state: Effect.Effect; readonly changes: Stream.Stream; + readonly checkForUpdate: Effect.Effect; readonly remove: ( protectedBinaryPaths?: ReadonlyArray, ) => Effect.Effect; @@ -113,14 +128,22 @@ export class AntigravityInstallation extends Context.Service< AntigravityInstallation, Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; - return yield* makeAntigravityInstallation({ baseDir: config.baseDir }); + const settings = yield* ServerSettings.ServerSettingsService; + return yield* makeAntigravityInstallation({ + baseDir: config.baseDir, + updateChecksEnabled: settings.getSettings.pipe( + Effect.map((value) => value.enableProviderUpdateChecks), + Effect.orElseSucceed(() => false), + ), + }); }), ); } export interface AntigravityInstallationOptions { readonly baseDir: string; - readonly releaseAsset?: AntigravityReleaseAsset | null; + readonly releaseAsset?: AntigravityReleaseAsset | AntigravityCliReleaseAsset | null; + readonly updateChecksEnabled?: Effect.Effect; readonly validate?: ( executable: AntigravityExecutable, expectedVersion: string, @@ -159,6 +182,7 @@ function isRunning(state: ProviderInstallState) { export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.make")(function* ( options: AntigravityInstallationOptions, ) { + const manifestService = yield* ModelManifest.ModelManifest; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const random = yield* SecureRandom.SecureRandom; @@ -168,10 +192,11 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const platform = yield* HostProcess.Platform; const arch = yield* HostProcess.Architecture; const environment = yield* HostProcess.Environment; - const releaseAsset = + let releaseAsset = options.releaseAsset ?? null; + const supported = options.releaseAsset === undefined - ? resolveAntigravityReleaseAsset(platform, arch) - : options.releaseAsset; + ? antigravityCliTarget(platform, arch) !== null + : options.releaseAsset !== null; const names = executableNames(platform); const managedDirectory = path.join( options.baseDir, @@ -189,13 +214,36 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma operationId: null, phase: "idle", downloadedBytes: 0, - totalBytes: releaseAsset?.archiveBytes ?? null, + totalBytes: + releaseAsset !== null && "archiveBytes" in releaseAsset ? releaseAsset.archiveBytes : null, version: releaseAsset?.version ?? null, installedVersion: null, canRemove: false, message: null, }); + const isWithdrawn = Effect.fn("AntigravityInstallation.isWithdrawn")(function* (version: string) { + const manifest = yield* manifestService.current; + const status = ( + resolveProviderCompatibility(manifest.compatibility, DRIVER, version) ?? + resolveProviderCompatibility( + ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, + DRIVER, + version, + ) + )?.status; + return status === "broken" || status === "unsupported"; + }); + const ensureEligible = Effect.fn("AntigravityInstallation.ensureEligible")(function* ( + version: string, + ) { + if (yield* isWithdrawn(version)) + return yield* installationError( + "verify", + "This Antigravity release was withdrawn. Check for updates and try again.", + ); + }); + const readRecord = Effect.fn("AntigravityInstallation.readRecord")(function* ( filePath: string, schema: Schema.Codec, @@ -231,15 +279,20 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const record = yield* readRecord(path.join(directory, RELEASE_RECORD), InstalledRelease); if ( record.releaseId !== releaseId || - record.executable.name !== names.executable || - record.harness.name !== names.harness || + (record.harness === null + ? record.executable.name !== (platform === "win32" ? "agy.exe" : "antigravity") + : record.executable.name !== names.executable || record.harness.name !== names.harness) || !Number.isSafeInteger(record.executable.bytes) || record.executable.bytes <= 0 || - !Number.isSafeInteger(record.harness.bytes) || - record.harness.bytes <= 0 || + (record.harness !== null && + (!Number.isSafeInteger(record.harness.bytes) || record.harness.bytes <= 0)) || !record.version.trim() || - !(yield* executableFile(path.join(directory, names.executable), record.executable.bytes)) || - !(yield* executableFile(path.join(directory, names.harness), record.harness.bytes)) + !(yield* executableFile( + path.join(directory, record.executable.name), + record.executable.bytes, + )) || + (record.harness !== null && + !(yield* executableFile(path.join(directory, record.harness.name), record.harness.bytes))) ) { return yield* installationError( "resolve", @@ -247,8 +300,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); } return { - executablePath: path.join(directory, names.executable), - harnessPath: path.join(directory, names.harness), + executablePath: path.join(directory, record.executable.name), + harnessPath: record.harness === null ? null : path.join(directory, record.harness.name), source: "managed", version: record.version, managedVersionDirectory: directory, @@ -261,6 +314,16 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ) { if (!(yield* executableFile(candidate))) return null; const executablePath = yield* fs.realPath(candidate); + const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option); + const directory = path.dirname(executablePath); + if ( + Option.isSome(realVersions) && + path.dirname(directory) === realVersions.value && + /^[a-f0-9]{64}$/u.test(path.basename(directory)) + ) { + const installed = yield* completedRelease(path.basename(directory)); + return { ...installed, source }; + } // Keep launcher symlinks intact: version-manager shims dispatch by their invoked name. if (isAntigravityCli(candidate, executablePath)) { return { @@ -271,18 +334,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma managedVersionDirectory: null, } satisfies AntigravityExecutable; } - const directory = path.dirname(executablePath); const harnessPath = path.join(directory, names.harness); if (!(yield* executableFile(harnessPath))) return null; - const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option); - if ( - Option.isSome(realVersions) && - path.dirname(directory) === realVersions.value && - /^[a-f0-9]{64}$/u.test(path.basename(directory)) - ) { - const installed = yield* completedRelease(path.basename(directory)); - return { ...installed, executablePath, harnessPath, source } satisfies AntigravityExecutable; - } return { executablePath, harnessPath, @@ -327,7 +380,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma "AntigravityInstallation.resolve", )( function* (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) { - const override = binaryPath?.trim(); + const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory); if (override) { for (const candidate of yield* commandCandidates(override, processEnvironment)) { const selected = yield* fromExternal(candidate, "override"); @@ -340,7 +393,13 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma } if (yield* fs.exists(activePath)) { const active = yield* readRecord(activePath, ActiveRelease); - return yield* completedRelease(active.releaseId); + const installed = yield* completedRelease(active.releaseId); + if (yield* isWithdrawn(installed.version)) + return yield* installationError( + "resolve", + `Antigravity ${installed.version} no longer works with this 456code release. Update it in Antigravity setup.`, + ); + return installed; } for (const candidate of yield* commandCandidates(names.executable, processEnvironment)) { const selected = yield* fromExternal(candidate, "path"); @@ -348,7 +407,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma } return yield* installationError( "resolve", - releaseAsset + supported ? "Antigravity ACP runtime is not installed. Install it in this environment's provider settings or set a custom ACP executable path. The Antigravity app, IDE, and CLI are separate installations." : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`, ); @@ -437,8 +496,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma }); const initialized = yield* runtime.initialize(); if ( - initialized.agentInfo?.name !== "antigravity-acp" || - initialized.agentInfo.version !== expectedVersion || + (executable.harnessPath === null + ? initialized.agentInfo?.name !== "Antigravity ACP Server" + : initialized.agentInfo?.name !== "antigravity-acp") || + initialized.agentInfo?.version !== expectedVersion || // Antigravity 1.1.1 may report protocol 2 with legacy ACP; choose wire format from the response shape. (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) || initialized.agentCapabilities?.loadSession !== true || @@ -458,17 +519,23 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma Effect.provideService(SecureRandom.SecureRandom, random), Effect.mapError((cause) => { if (isInstallationError(cause)) return cause; - const detail = - isAcpProcessExitedError(cause) && - /\b(?:AF_INET6|enforce_kernel_ipv6_support)\b/.test(cause.stderr ?? "") - ? "Antigravity requires IPv6 socket support. Enable IPv6 in this environment. On WSL, remove ipv6.disable=1 from .wslconfig and run wsl --shutdown." + const stderr = isAcpProcessExitedError(cause) ? (cause.stderr ?? "") : ""; + const detail = /\b(?:AF_INET6|enforce_kernel_ipv6_support)\b/.test(stderr) + ? "Antigravity requires IPv6 socket support. Enable IPv6 in this environment. On WSL, remove ipv6.disable=1 from .wslconfig and run wsl --shutdown." + : /page-size\.cc|Compile-time page size does not match/.test(stderr) + ? LARGE_PAGE_KERNEL_MESSAGE : "The downloaded Antigravity runtime could not start in this environment."; return installationError("verify", detail, cause); }), ); const install = Effect.fn("AntigravityInstallation.install")( - function* (asset: AntigravityReleaseAsset) { + function* (asset: AntigravityReleaseAsset | AntigravityCliReleaseAsset) { + yield* ensureEligible(asset.version); + const cli = "sha512" in asset; + // Existing installation records use 64-character IDs, including native SHA-512 prefixes. + const releaseId = cli ? asset.sha512.slice(0, 64) : asset.sha256; + const archiveBytes = cli ? null : asset.archiveBytes; yield* resolveNodeExecutable("Antigravity", environment).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), @@ -477,23 +544,35 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause), ), ); + if (!cli && platform === "linux" && arch === "arm64") { + const pageSize = yield* spawner + .string(ChildProcess.make("getconf", ["PAGESIZE"], { stdin: "ignore", stderr: "ignore" })) + .pipe( + Effect.map((output) => Number(output.trim())), + Effect.timeout("5 seconds"), + Effect.orElseSucceed(() => Number.NaN), + ); + if (pageSize > 4096) { + return yield* installationError("download", LARGE_PAGE_KERNEL_MESSAGE); + } + } const report = (phase: ProviderInstallState["phase"], message: string | null) => SubscriptionRef.update(state, (current) => ({ ...current, phase, message })); yield* fs.makeDirectory(versionsDirectory, { recursive: true }); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true })); - const destination = path.join(versionsDirectory, asset.sha256); + const destination = path.join(versionsDirectory, releaseId); const activate = Effect.fn("AntigravityInstallation.activate")( function* () { + yield* ensureEligible(asset.version); const pointerDirectory = yield* fs.makeTempDirectoryScoped({ directory: managedDirectory, prefix: "active.json.", }); const pointerPath = path.join(pointerDirectory, "contents.tmp"); - yield* fs.writeFileString( - pointerPath, - yield* encodeActiveRelease({ releaseId: asset.sha256 }), - { flag: "wx", mode: 0o600 }, - ); + yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), { + flag: "wx", + mode: 0o600, + }); yield* fs.rename(pointerPath, activePath); yield* SubscriptionRef.update( state, @@ -517,7 +596,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); if (yield* fs.exists(destination)) { - const existing = yield* completedRelease(asset.sha256); + const existing = yield* completedRelease(releaseId); if (existing.version !== asset.version) { return yield* installationError( "verify", @@ -537,8 +616,9 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }), catch: (cause) => installationError("download", "Could not check free disk space.", cause), }).pipe(Effect.option); - const required = - asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN; + const required = cli + ? MAX_DOWNLOAD_BYTES + MAX_EXECUTABLE_BYTES + FREE_SPACE_MARGIN + : asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN; if ( Option.isSome(available) && available.value.bavail * available.value.bsize < BigInt(required) @@ -555,7 +635,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const archivePath = path.join(staging, "download.zip"); const pairDirectory = path.join(staging, "runtime"); yield* fs.makeDirectory(pairDirectory); - const hash = NodeCrypto.createHash("sha256"); + const hash = NodeCrypto.createHash(cli ? "sha512" : "sha256"); let downloadedBytes = 0; let lastProgressAt = yield* Clock.currentTimeMillis; yield* Effect.gen(function* () { @@ -569,7 +649,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma if ( identityBody && contentLength !== undefined && - Number(contentLength) !== asset.archiveBytes + archiveBytes !== null && + Number(contentLength) !== archiveBytes ) { return yield* installationError( "download", @@ -580,15 +661,15 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma Stream.tap((chunk) => Effect.gen(function* () { downloadedBytes += chunk.byteLength; - if (downloadedBytes > asset.archiveBytes) { + if (downloadedBytes > (archiveBytes ?? MAX_DOWNLOAD_BYTES)) { return yield* installationError( "download", - "The Antigravity download exceeded the pinned release size.", + "The Antigravity download exceeded its allowed size.", ); } hash.update(chunk); const now = yield* Clock.currentTimeMillis; - if (now - lastProgressAt >= 250 || downloadedBytes === asset.archiveBytes) { + if (now - lastProgressAt >= 250 || downloadedBytes === archiveBytes) { lastProgressAt = now; yield* SubscriptionRef.update(state, (current) => ({ ...current, @@ -599,99 +680,166 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })), ); - }).pipe(Effect.timeout(DOWNLOAD_TIMEOUT)); - if (downloadedBytes !== asset.archiveBytes || hash.digest("hex") !== asset.sha256) { + }).pipe( + Effect.timeout(DOWNLOAD_TIMEOUT), + Effect.mapError((cause) => + HttpClientError.isHttpClientError(cause) || Cause.isTimeoutError(cause) + ? installationError( + "download", + "Could not download Antigravity from Google. Check the network connection and any proxy settings, then try again.", + cause, + ) + : cause, + ), + ); + if ( + (archiveBytes !== null && downloadedBytes !== archiveBytes) || + hash.digest("hex") !== (cli ? asset.sha512 : asset.sha256) + ) { return yield* installationError( "download", - "The Antigravity download failed its size or SHA-256 check. Nothing was installed.", + "The Antigravity download failed its size or checksum check. Nothing was installed.", ); } yield* report("extracting", "Extracting the verified runtime."); - yield* Effect.gen(function* () { - const archive = yield* openZipArchive(archivePath, (detail, cause) => - installationError("extract", detail, cause), - ); - if (archive.entryCount !== 2) { - return yield* installationError( - "extract", - "The archive must contain exactly the Antigravity executable and its harness.", - ); - } - const seen = new Set(); - for (;;) { - const entry = yield* archive.next; - if (!entry) break; - const expected = [asset.executable, asset.harness].find( - (file) => file.name === entry.fileName, - ); - const unixType = (entry.externalFileAttributes >>> 16) & 0o170000; + if (cli) { + const executablePath = path.join(pairDirectory, asset.executable.name); + if (asset.format === "executable") { + yield* fs.copyFile(archivePath, executablePath); + } else { + const tar = cliArchiveTarCommand(platform, environment); + const list = yield* spawner.string(ChildProcess.make(tar, ["-tzf", archivePath])); + const types = yield* spawner.string(ChildProcess.make(tar, ["-tvzf", archivePath])); if ( - !expected || - seen.has(entry.fileName) || - entry.fileName.includes("/") || - entry.fileName.includes("\\") || - (unixType !== 0 && unixType !== 0o100000) || - (entry.externalFileAttributes & 0x10) !== 0 || - (entry.generalPurposeBitFlag & 1) !== 0 || - ![0, 8].includes(entry.compressionMethod) || - entry.uncompressedSize !== expected.bytes + list.trim() !== asset.executable.name || + types.trim().split(/\r?\n/u).length !== 1 || + !types.startsWith("-") ) { return yield* installationError( "extract", - "The archive contains an unexpected, unsafe, or incorrectly sized member.", + "The Antigravity archive must contain one regular executable.", ); } - seen.add(entry.fileName); yield* Effect.gen(function* () { - const readable = yield* archive.streamEntry(entry); + const child = yield* spawner.spawn( + ChildProcess.make(tar, ["-xOzf", archivePath, asset.executable.name], { + stdout: "pipe", + stderr: "pipe", + }), + ); let extractedBytes = 0; - yield* EffectNodeStream.fromReadable({ - evaluate: () => readable, - onError: wrapFailure("extract", "Could not extract the Antigravity runtime."), - }).pipe( + yield* child.stdout.pipe( Stream.tap((chunk) => Effect.gen(function* () { extractedBytes += chunk.byteLength; - if (extractedBytes > expected.bytes) { + if (extractedBytes > MAX_EXECUTABLE_BYTES) return yield* installationError( "extract", - "An archive member exceeded its pinned size.", + "The Antigravity executable exceeded its size limit.", ); - } }), ), - Stream.run( - fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }), - ), + Stream.run(fs.sink(executablePath, { flag: "wx", mode: 0o700 })), ); - if (extractedBytes !== expected.bytes) { - return yield* installationError("extract", "An archive member was truncated."); - } + if ((yield* child.exitCode) !== 0 || extractedBytes === 0) + return yield* installationError( + "extract", + "Could not extract the Antigravity executable.", + ); }).pipe(Effect.scoped); } - if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) { - return yield* installationError( - "extract", - "The archive is missing the Antigravity executable or its harness.", + } else + yield* Effect.gen(function* () { + const archive = yield* openZipArchive(archivePath, (detail, cause) => + installationError("extract", detail, cause), ); - } - }).pipe(Effect.scoped); + if (archive.entryCount !== 2) { + return yield* installationError( + "extract", + "The archive must contain exactly the Antigravity executable and its harness.", + ); + } + const seen = new Set(); + for (;;) { + const entry = yield* archive.next; + if (!entry) break; + const expected = [asset.executable, asset.harness].find( + (file) => file.name === entry.fileName, + ); + const unixType = (entry.externalFileAttributes >>> 16) & 0o170000; + if ( + !expected || + seen.has(entry.fileName) || + entry.fileName.includes("/") || + entry.fileName.includes("\\") || + (unixType !== 0 && unixType !== 0o100000) || + (entry.externalFileAttributes & 0x10) !== 0 || + (entry.generalPurposeBitFlag & 1) !== 0 || + ![0, 8].includes(entry.compressionMethod) || + entry.uncompressedSize !== expected.bytes + ) { + return yield* installationError( + "extract", + "The archive contains an unexpected, unsafe, or incorrectly sized member.", + ); + } + seen.add(entry.fileName); + yield* Effect.gen(function* () { + const readable = yield* archive.streamEntry(entry); + let extractedBytes = 0; + yield* EffectNodeStream.fromReadable({ + evaluate: () => readable, + onError: wrapFailure("extract", "Could not extract the Antigravity runtime."), + }).pipe( + Stream.tap((chunk) => + Effect.gen(function* () { + extractedBytes += chunk.byteLength; + if (extractedBytes > expected.bytes) { + return yield* installationError( + "extract", + "An archive member exceeded its pinned size.", + ); + } + }), + ), + Stream.run( + fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }), + ), + ); + if (extractedBytes !== expected.bytes) { + return yield* installationError("extract", "An archive member was truncated."); + } + }).pipe(Effect.scoped); + } + if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) { + return yield* installationError( + "extract", + "The archive is missing the Antigravity executable or its harness.", + ); + } + }).pipe(Effect.scoped); yield* fs.remove(archivePath); const executablePath = path.join(pairDirectory, asset.executable.name); - const harnessPath = path.join(pairDirectory, asset.harness.name); + const harnessPath = cli ? null : path.join(pairDirectory, asset.harness.name); if (platform !== "win32") { yield* fs.chmod(executablePath, 0o755); - yield* fs.chmod(harnessPath, 0o755); + if (harnessPath !== null) yield* fs.chmod(harnessPath, 0o755); } - if (platform === "darwin" && arch === "x64") { + if (!cli && platform === "darwin" && arch === "x64") { // Google signs the Intel build with the hardened runtime but no JIT entitlement, so // libffi's writable+executable trampolines spin forever. Re-sign ad hoc after the hash check. const exitCode = yield* spawner .spawn( ChildProcess.make( "/usr/bin/codesign", - ["--force", "--sign", "-", executablePath, harnessPath], + [ + "--force", + "--sign", + "-", + executablePath, + ...(harnessPath === null ? [] : [harnessPath]), + ], { stdout: "ignore", stderr: "ignore" }, ), ) @@ -718,13 +866,16 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma asset.version, ).pipe(Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT)); const record: InstalledRelease = { - releaseId: asset.sha256, + releaseId, version: asset.version, executable: { name: asset.executable.name, bytes: Number((yield* fs.stat(executablePath)).size), }, - harness: { name: asset.harness.name, bytes: Number((yield* fs.stat(harnessPath)).size) }, + harness: + cli || harnessPath === null + ? null + : { name: asset.harness.name, bytes: Number((yield* fs.stat(harnessPath)).size) }, }; yield* fs.writeFileString( path.join(pairDirectory, RELEASE_RECORD), @@ -733,7 +884,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); yield* fs.rename(pairDirectory, destination).pipe( Effect.catch((cause) => - completedRelease(asset.sha256).pipe( + completedRelease(releaseId).pipe( Effect.flatMap((existing) => existing.version === asset.version ? validate(existing, asset.version).pipe( @@ -768,31 +919,119 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), ); - const start = gate - .withPermit( + let lastUpdateCheck: number | undefined; + const refreshRelease = Effect.fn("AntigravityInstallation.refreshRelease")(function* ( + explicit = false, + ) { + if (options.releaseAsset !== undefined || !supported) return; + if (!explicit && !(yield* options.updateChecksEnabled ?? Effect.succeed(true))) return; + const now = yield* Clock.currentTimeMillis; + if (!explicit && lastUpdateCheck !== undefined && now - lastUpdateCheck < UPDATE_CHECK_INTERVAL) + return; + lastUpdateCheck = now; + const musl = + platform === "linux" && + (yield* fs.exists( + arch === "arm64" ? "/lib/libc.musl-aarch64.so.1" : "/lib/libc.musl-x86_64.so.1", + )); + const target = antigravityCliTarget(platform, arch, musl); + const latest = yield* http.get(`${ANTIGRAVITY_CLI_MANIFEST_BASE}/${target}.json`).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.json), + Effect.map((json) => parseAntigravityCliRelease(json, platform, arch, musl)), + Effect.timeout("10 seconds"), + Effect.orElseSucceed(() => null), + ); + if (latest === null) return; + if (yield* isWithdrawn(latest.version)) { + releaseAsset = null; + return; + } + releaseAsset = latest; + yield* SubscriptionRef.updateEffect(state, (value) => + isRunning(value) + ? Effect.succeed(value) + : Effect.gen(function* () { + const keepInstalled = + value.installedVersion !== null && + compareSemverVersions(value.installedVersion, latest.version) > 0 && + !(yield* isWithdrawn(value.installedVersion)); + return { + ...value, + version: keepInstalled ? value.installedVersion : latest.version, + totalBytes: null, + }; + }), + ); + }); + + const start = Effect.gen(function* () { + const current = yield* SubscriptionRef.get(state); + if (isRunning(current)) return current; + yield* refreshRelease(true); + return yield* gate.withPermit( Effect.gen(function* () { const current = yield* SubscriptionRef.get(state); if (isRunning(current)) return current; - if (!releaseAsset) { + if (!supported) { return yield* installationError( "start", `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`, ); } + const asset = + releaseAsset !== null && !(yield* isWithdrawn(releaseAsset.version)) + ? releaseAsset + : null; + const installed = yield* resolve().pipe(Effect.option); + const reuse = + Option.isSome(installed) && + installed.value.source === "managed" && + installed.value.harnessPath === null && + (asset === null || compareSemverVersions(installed.value.version!, asset.version) > 0) + ? installed.value + : undefined; + if (asset === null && reuse === undefined) + return yield* installationError( + "start", + "Could not find a native Antigravity CLI release. Check the network connection and try again.", + ); const operationId = yield* random.uuidV4(); const next: ProviderInstallState = { driver: DRIVER, operationId, - phase: "downloading", + phase: reuse === undefined ? "downloading" : "verifying", downloadedBytes: 0, - totalBytes: releaseAsset.archiveBytes, - version: releaseAsset.version, + totalBytes: asset !== null && "archiveBytes" in asset ? asset.archiveBytes : null, + version: reuse?.version ?? asset?.version ?? null, installedVersion: current.installedVersion, canRemove: current.canRemove, - message: "Downloading Google's official Antigravity runtime.", + message: + reuse === undefined + ? "Downloading Google's official Antigravity runtime." + : "Checking the installed runtime.", }; yield* SubscriptionRef.set(state, next); - const work = install(releaseAsset).pipe( + const work = ( + reuse === undefined + ? install(asset!) + : validate(reuse, reuse.version!).pipe( + Effect.scoped, + Effect.timeout(VALIDATION_TIMEOUT), + Effect.andThen(ensureEligible(reuse.version!)), + Effect.andThen( + SubscriptionRef.update(state, (value) => ({ + ...value, + phase: "succeeded" as const, + installedVersion: reuse.version, + message: null, + })), + ), + ) + ).pipe( + Effect.mapError( + wrapFailure("verify", "Could not verify the installed Antigravity runtime."), + ), Effect.onExit((exit) => Exit.isFailure(exit) ? SubscriptionRef.update(state, (value) => { @@ -823,8 +1062,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma running = { operationId, fiber }; return next; }).pipe(Effect.uninterruptible), - ) - .pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation."))); + ); + }).pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation."))); const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) { return yield* gate.withPermit( @@ -932,6 +1171,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma cancel, state: SubscriptionRef.get(state), changes: SubscriptionRef.changes(state), + checkForUpdate: refreshRelease().pipe(Effect.ignore), remove, }); }); diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 791ed748de..a676273827 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -291,561 +291,519 @@ describe("Antigravity model catalog", () => { it.layer(layerTest)("Antigravity provider snapshots", (it) => { it.effect("does not probe or run helper safety checks while disabled", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness({ enabled: false }); - const snapshot = yield* harness.provider.snapshot.refresh; - expect(snapshot).toMatchObject({ - enabled: false, + Effect.gen(function* () { + const harness = yield* makeHarness({ enabled: false }); + const snapshot = yield* harness.provider.snapshot.refresh; + expect(snapshot).toMatchObject({ + enabled: false, + installed: false, + status: "disabled", + auth: { status: "unknown" }, + models: [], + setup: { canAuthenticate: true, canInstall: true }, + showInteractionModeToggle: false, + supportsConversationRollback: false, + supportsTextGeneration: false, + }); + expect(yield* Ref.get(harness.probeCalls)).toBe(0); + expect(yield* Ref.get(harness.safetyCalls)).toBe(0); + }), + ); + + it.effect("treats initialize as installation proof, not account or model discovery", () => + Effect.gen(function* () { + for (const auth of [ + undefined, + { type: "oauth-personal", label: "Google account" }, + { type: "oauth-business", label: "Gemini Enterprise" }, + { type: "gemini-api-key", label: "Gemini API key" }, + { type: "agent-platform", label: "Agent Platform" }, + ]) { + const harness = yield* makeHarness(auth ? { auth } : {}); + expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ installed: false, - status: "disabled", + status: "warning", auth: { status: "unknown" }, models: [], - setup: { canAuthenticate: true, canInstall: true }, - showInteractionModeToggle: false, - supportsConversationRollback: false, - supportsTextGeneration: false, }); - expect(yield* Ref.get(harness.probeCalls)).toBe(0); - expect(yield* Ref.get(harness.safetyCalls)).toBe(0); - }), - ), - ); - - it.effect("treats initialize as installation proof, not account or model discovery", () => - Effect.scoped( - Effect.gen(function* () { - for (const auth of [ - undefined, - { type: "oauth-personal", label: "Google account" }, - { type: "oauth-business", label: "Gemini Enterprise" }, - { type: "gemini-api-key", label: "Gemini API key" }, - { type: "agent-platform", label: "Agent Platform" }, - ]) { - const harness = yield* makeHarness(auth ? { auth } : {}); - expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ - installed: false, - status: "warning", - auth: { status: "unknown" }, - models: [], - }); - yield* harness.initialize; - const snapshot = yield* harness.provider.snapshot.getSnapshot; - expect(snapshot).toMatchObject({ - installed: true, - status: "warning", - version: "agy_acp_server_20260818_01_RC01", - auth: { status: "unknown", ...(auth ? { type: auth.type } : {}) }, - message: - auth?.type === "gemini-api-key" || auth?.type === "agent-platform" - ? `Antigravity is installed. Connect with ${auth.label} to load models.` - : "Antigravity is installed. Google account access is not checked yet.", - models: [], - }); - expect(yield* Ref.get(harness.probeCalls)).toBe(1); - } - }), - ), + yield* harness.initialize; + const snapshot = yield* harness.provider.snapshot.getSnapshot; + expect(snapshot).toMatchObject({ + installed: true, + status: "warning", + version: "agy_acp_server_20260818_01_RC01", + auth: { status: "unknown", ...(auth ? { type: auth.type } : {}) }, + message: + auth?.type === "gemini-api-key" || auth?.type === "agent-platform" + ? `Antigravity is installed. Connect with ${auth.label} to load models.` + : "Antigravity is installed. Google account access is not checked yet.", + models: [], + }); + expect(yield* Ref.get(harness.probeCalls)).toBe(1); + } + }), ); it.effect("does not offer Auto, so Auto threads fall back to Supervised", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - // Antigravity has no automatic review; the shared ACP policy would approve every request. - expect((yield* harness.provider.snapshot.getSnapshot).supportedRuntimeModes).toEqual([ - "approval-required", - "auto-accept-edits", - "full-access", - ]); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + // Antigravity has no automatic review; the shared ACP policy would approve every request. + expect((yield* harness.provider.snapshot.getSnapshot).supportedRuntimeModes).toEqual([ + "approval-required", + "auto-accept-edits", + "full-access", + ]); + }), ); it.effect("publishes session metadata and native commands without another health probe", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const nextReady = yield* Stream.toPull( - harness.provider.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.auth.status === "authenticated" && snapshot.slashCommands.length > 0, - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + const nextReady = yield* Stream.toPull( + harness.provider.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.auth.status === "authenticated" && snapshot.slashCommands.length > 0, ), - ); - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - const [snapshot] = yield* nextReady; - expect(snapshot).toMatchObject({ - status: "ready", - auth: { status: "authenticated", type: "oauth-personal" }, - supportsTextGeneration: true, - }); - expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); - expect(snapshot.slashCommands).toEqual(expectedCommands); - expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual( - expectedCommands, - ); - expect(yield* Ref.get(harness.probeCalls)).toBe(1); - }), - ), + ), + ); + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + const [snapshot] = yield* nextReady; + expect(snapshot).toMatchObject({ + status: "ready", + auth: { status: "authenticated", type: "oauth-personal" }, + supportsTextGeneration: true, + }); + expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); + expect(snapshot.slashCommands).toEqual(expectedCommands); + expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual( + expectedCommands, + ); + expect(yield* Ref.get(harness.probeCalls)).toBe(1); + }), ); it.effect("clears all account metadata on sign-out and authentication failure", () => - Effect.scoped( - Effect.gen(function* () { - const auth = { type: "gemini-api-key", label: "Gemini API key" }; - const harness = yield* makeHarness({ auth }); - yield* harness.initialize; - for (const clear of [harness.provider.onSignedOut, harness.provider.onAuthRequired]) { - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* clear; - expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ - installed: true, - status: "warning", - auth: { status: "unauthenticated", type: auth.type, label: auth.label }, - message: "Connect with Gemini API key to use Antigravity and load models.", - models: [], - slashCommands: [], - skills: [], - workspaceSnapshots: [], - supportsTextGeneration: false, - }); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* harness.provider.onConfigOptionsUpdated([modelConfig]); - expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual([]); - expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]); - } - const refreshed = yield* harness.provider.snapshot.refresh; - expect(refreshed.auth).toEqual({ - status: "unauthenticated", - type: auth.type, - label: auth.label, - }); - expect(refreshed.message).toBe( - "Connect with Gemini API key to use Antigravity and load models.", - ); - expect(refreshed.supportsTextGeneration).toBe(false); - }), - ), - ); - - it.effect("replaces live model choices and accepts an empty catalog", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; + Effect.gen(function* () { + const auth = { type: "gemini-api-key", label: "Gemini API key" }; + const harness = yield* makeHarness({ auth }); + yield* harness.initialize; + for (const clear of [harness.provider.onSignedOut, harness.provider.onAuthRequired]) { yield* harness.provider.onSessionStarted(started, "/workspace"); yield* harness.provider.onAvailableCommands(commands, "/workspace"); - const before = yield* harness.provider.snapshot.getSnapshot; - const configOptions = [ - { - ...modelConfig, - currentValue: "gemini-3.8-flash-high", - options: modelOptions.slice(0, 3), - }, - ]; - const nextSnapshot = yield* Stream.toPull( - harness.provider.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.models.length === 3), - ), - ); - yield* harness.provider.onConfigOptionsUpdated(configOptions); - expect((yield* nextSnapshot)[0]).toMatchObject({ - models: buildAntigravityModelsFromSession({ configOptions }), - auth: before.auth, - workspaceSnapshots: before.workspaceSnapshots, - slashCommands: expectedCommands, + yield* clear; + expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ + installed: true, + status: "warning", + auth: { status: "unauthenticated", type: auth.type, label: auth.label }, + message: "Connect with Gemini API key to use Antigravity and load models.", + models: [], + slashCommands: [], + skills: [], + workspaceSnapshots: [], + supportsTextGeneration: false, }); - yield* harness.provider.onConfigOptionsUpdated([]); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + yield* harness.provider.onConfigOptionsUpdated([modelConfig]); + expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual([]); expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]); - }), - ), + } + const refreshed = yield* harness.provider.snapshot.refresh; + expect(refreshed.auth).toEqual({ + status: "unauthenticated", + type: auth.type, + label: auth.label, + }); + expect(refreshed.message).toBe( + "Connect with Gemini API key to use Antigravity and load models.", + ); + expect(refreshed.supportsTextGeneration).toBe(false); + }), + ); + + it.effect("replaces live model choices and accepts an empty catalog", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + const before = yield* harness.provider.snapshot.getSnapshot; + const configOptions = [ + { + ...modelConfig, + currentValue: "gemini-3.8-flash-high", + options: modelOptions.slice(0, 3), + }, + ]; + const nextSnapshot = yield* Stream.toPull( + harness.provider.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.length === 3), + ), + ); + yield* harness.provider.onConfigOptionsUpdated(configOptions); + expect((yield* nextSnapshot)[0]).toMatchObject({ + models: buildAntigravityModelsFromSession({ configOptions }), + auth: before.auth, + workspaceSnapshots: before.workspaceSnapshots, + slashCommands: expectedCommands, + }); + yield* harness.provider.onConfigOptionsUpdated([]); + expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]); + }), ); it.effect("does not guess a version before a custom launcher's first handshake", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* Deferred.succeed(harness.initialProbe, { - ...initializeResult, - agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, - }); - yield* harness.initialUpdate; - expect((yield* harness.provider.snapshot.getSnapshot).version).toBeNull(); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Deferred.succeed(harness.initialProbe, { + ...initializeResult, + agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, + }); + yield* harness.initialUpdate; + expect((yield* harness.provider.snapshot.getSnapshot).version).toBeNull(); + }), ); it.effect("does not replace a handshake version with an unknown custom-launcher probe", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted({ - ...started, - initializeResult: { - ...initializeResult, - agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" }, - }, - }); - yield* Ref.set( - harness.probe, - Effect.succeed({ - ...initializeResult, - agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, - }), - ); - expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0"); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted({ + ...started, + initializeResult: { + ...initializeResult, + agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" }, + }, + }); + yield* Ref.set( + harness.probe, + Effect.succeed({ + ...initializeResult, + agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, + }), + ); + expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0"); + }), ); it.effect("replaces one account's catalog instead of combining accounts", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - yield* harness.provider.onSignedOut; - yield* harness.provider.onSessionStarted({ - ...started, - sessionSetupResult: { - sessionId: "new-account-session", - configOptions: [ - { ...modelConfig, currentValue: "gemini-pro-agent", options: [modelOptions[9]!] }, - ], - }, - }); - expect( - (yield* harness.provider.snapshot.getSnapshot).models.map((model) => model.slug), - ).toEqual(["gemini-pro-agent"]); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + yield* harness.provider.onSignedOut; + yield* harness.provider.onSessionStarted({ + ...started, + sessionSetupResult: { + sessionId: "new-account-session", + configOptions: [ + { ...modelConfig, currentValue: "gemini-pro-agent", options: [modelOptions[9]!] }, + ], + }, + }); + expect( + (yield* harness.provider.snapshot.getSnapshot).models.map((model) => model.slug), + ).toEqual(["gemini-pro-agent"]); + }), ); it.effect("retains known account metadata when a local health check fails", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + yield* Ref.set( + harness.probe, + Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")), + ); + const snapshot = yield* harness.provider.snapshot.refresh; + expect(snapshot).toMatchObject({ + installed: true, + status: "error", + auth: { status: "authenticated" }, + }); + expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); + expect(snapshot.slashCommands).toEqual(expectedCommands); + expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace"); + }), + ); + + it.effect("distinguishes missing executables from a failed installed executable", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + const failures = [ + { + error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "ENOENT" } }), + installed: false, + }, + { + error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "EACCES" } }), + installed: true, + }, + { + error: new ProviderSetupError({ + instanceId, + operation: "resolve", + detail: "Antigravity is not installed.", + }), + installed: false, + }, + ]; + for (const { error, installed } of failures) { yield* harness.provider.onSessionStarted(started, "/workspace"); yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* Ref.set( - harness.probe, - Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")), - ); + yield* Ref.set(harness.probe, Effect.fail(error)); const snapshot = yield* harness.provider.snapshot.refresh; expect(snapshot).toMatchObject({ - installed: true, + installed, status: "error", auth: { status: "authenticated" }, }); - expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); - expect(snapshot.slashCommands).toEqual(expectedCommands); - expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace"); - }), - ), - ); - - it.effect("distinguishes missing executables from a failed installed executable", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const failures = [ - { - error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "ENOENT" } }), - installed: false, - }, - { - error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "EACCES" } }), - installed: true, - }, - { - error: new ProviderSetupError({ - instanceId, - operation: "resolve", - detail: "Antigravity is not installed.", - }), - installed: false, - }, - ]; - for (const { error, installed } of failures) { - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* Ref.set(harness.probe, Effect.fail(error)); - const snapshot = yield* harness.provider.snapshot.refresh; - expect(snapshot).toMatchObject({ - installed, - status: "error", - auth: { status: "authenticated" }, - }); - expect(snapshot.models).toHaveLength(installed ? 11 : 0); - expect(snapshot.slashCommands).toHaveLength(installed ? 2 : 0); - expect(snapshot.workspaceSnapshots).toHaveLength(installed ? 1 : 0); - expect(snapshot.supportsTextGeneration).toBe(installed); - } - }), - ), + expect(snapshot.models).toHaveLength(installed ? 11 : 0); + expect(snapshot.slashCommands).toHaveLength(installed ? 2 : 0); + expect(snapshot.workspaceSnapshots).toHaveLength(installed ? 1 : 0); + expect(snapshot.supportsTextGeneration).toBe(installed); + } + }), ); it.effect("does not let an old health result restore a signed-out account", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - const releaseProbe = yield* Deferred.make(); - const probeEntered = yield* Deferred.make(); - yield* Ref.set( - harness.probe, - Deferred.succeed(probeEntered, undefined).pipe( - Effect.andThen(Deferred.await(releaseProbe)), - ), - ); - const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); - yield* Deferred.await(probeEntered); - yield* harness.provider.onSignedOut; - yield* Deferred.succeed(releaseProbe, initializeResult); - const snapshot = yield* Fiber.join(refresh); - expect(snapshot).toMatchObject({ - auth: { status: "unauthenticated" }, - models: [], - supportsTextGeneration: false, - }); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + const releaseProbe = yield* Deferred.make(); + const probeEntered = yield* Deferred.make(); + yield* Ref.set( + harness.probe, + Deferred.succeed(probeEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseProbe)), + ), + ); + const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); + yield* Deferred.await(probeEntered); + yield* harness.provider.onSignedOut; + yield* Deferred.succeed(releaseProbe, initializeResult); + const snapshot = yield* Fiber.join(refresh); + expect(snapshot).toMatchObject({ + auth: { status: "unauthenticated" }, + models: [], + supportsTextGeneration: false, + }); + }), ); it.effect("exposes helper support only when the supplied safety check allows it", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness({ safe: false }); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(false); - yield* Ref.set(harness.safety, Effect.succeed(true)); - yield* harness.provider.snapshot.refresh; - expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(true); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness({ safe: false }); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(false); + yield* Ref.set(harness.safety, Effect.succeed(true)); + yield* harness.provider.snapshot.refresh; + expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(true); + }), ); it.effect("keeps discovered workspace skills through session and command updates", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const skills = [ - { - name: "deploy", - description: "Ship it", - path: "/workspace/.agent/skills/deploy", - enabled: true, - }, - ]; - const discovered = yield* harness.provider.snapshotForCwd("/workspace", skills); - expect(discovered.skills).toEqual(skills); - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - const after = yield* harness.provider.snapshot.getSnapshot; - expect( - after.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace")?.skills, - ).toEqual(skills); - expect((yield* harness.provider.snapshotForCwd("/workspace")).skills).toEqual(skills); - - const rescanned = [ - ...skills, - { name: "review", path: "/workspace/.agent/skills/review", enabled: true }, - ]; - yield* harness.provider.snapshotForCwd("/workspace", rescanned); - yield* harness.provider.onSessionStarted(started, "/workspace"); - expect( - (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find( - (entry) => entry.cwd === "/workspace", - )?.skills, - ).toEqual(rescanned); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + const skills = [ + { + name: "deploy", + description: "Ship it", + path: "/workspace/.agent/skills/deploy", + enabled: true, + }, + ]; + const discovered = yield* harness.provider.snapshotForCwd("/workspace", skills); + expect(discovered.skills).toEqual(skills); + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + const after = yield* harness.provider.snapshot.getSnapshot; + expect(after.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace")?.skills).toEqual( + skills, + ); + expect((yield* harness.provider.snapshotForCwd("/workspace")).skills).toEqual(skills); + + const rescanned = [ + ...skills, + { name: "review", path: "/workspace/.agent/skills/review", enabled: true }, + ]; + yield* harness.provider.snapshotForCwd("/workspace", rescanned); + yield* harness.provider.onSessionStarted(started, "/workspace"); + expect( + (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find( + (entry) => entry.cwd === "/workspace", + )?.skills, + ).toEqual(rescanned); + }), ); it.effect("bounds workspace metadata without starting sessions for workspace lookup", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - for (let index = 0; index < 35; index++) { - yield* harness.provider.onAvailableCommands(commands, `/workspace-${index}`); - } - const snapshot = yield* harness.provider.snapshotForCwd("/workspace-34"); - expect(snapshot.workspaceSnapshots).toHaveLength(32); - expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace-3"); - expect(snapshot.slashCommands).toEqual(expectedCommands); - expect(yield* Ref.get(harness.probeCalls)).toBe(1); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + for (let index = 0; index < 35; index++) { + yield* harness.provider.onAvailableCommands(commands, `/workspace-${index}`); + } + const snapshot = yield* harness.provider.snapshotForCwd("/workspace-34"); + expect(snapshot.workspaceSnapshots).toHaveLength(32); + expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace-3"); + expect(snapshot.slashCommands).toEqual(expectedCommands); + expect(yield* Ref.get(harness.probeCalls)).toBe(1); + }), ); it.effect( "publishes limits, retains a successful read on failure, and clears them on sign-out", () => - Effect.scoped( - Effect.gen(function* () { - const limits: ServerProviderUsageLimits = { - checkedAt: "2026-10-09T12:00:00.000Z", - windows: [ - { - id: "3p-weekly", - kind: "weekly", - label: "Claude & GPT (shared) · Weekly", - usedPercent: 75, - }, - ], - }; - const usage = yield* Ref.make(limits); - const harness = yield* makeHarness({ probeUsage: Ref.get(usage) }); - const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); - yield* harness.initialize; - expect((yield* published)?.usageLimits).toEqual(limits); - // The second health check is the one the failed background read triggers. - const checks = yield* Ref.make(0); - const failedReadApplied = yield* Deferred.make(); - yield* Ref.set( - harness.probe, - Ref.updateAndGet(checks, (count) => count + 1).pipe( - Effect.tap((count) => - count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void, - ), - Effect.as(initializeResult), - ), - ); - yield* Ref.set(usage, { - checkedAt: "2026-10-09T12:01:00.000Z", - windows: [], - unavailable: { reason: "probeFailed" }, - }); - yield* harness.provider.snapshot.refresh; - yield* Deferred.await(failedReadApplied); - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits); - yield* harness.provider.onSignedOut; - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); - yield* Ref.set(usage, { - checkedAt: "2026-10-09T12:02:00.000Z", - windows: [], - unavailable: { reason: "unsupported" }, - }); - const unsupported = yield* harness.nextPublish( - (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported", - ); - yield* harness.provider.snapshot.refresh; - expect((yield* unsupported)?.usageLimits?.windows).toEqual([]); - }), - ), - ); - - it.effect("a quota read finishing after sign-out cannot restore account limits", () => - Effect.scoped( Effect.gen(function* () { - const readStarted = yield* Deferred.make(); - const readResult = yield* Deferred.make(); - const usage = yield* Ref.make>( - Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }), - ); - const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); + const limits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:00:00.000Z", + windows: [ + { + id: "3p-weekly", + kind: "weekly", + label: "Claude & GPT (shared) · Weekly", + usedPercent: 75, + }, + ], + }; + const usage = yield* Ref.make(limits); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage) }); + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); yield* harness.initialize; - yield* Ref.set(harness.probe, Effect.succeed(initializeResult)); + expect((yield* published)?.usageLimits).toEqual(limits); + // The second health check is the one the failed background read triggers. + const checks = yield* Ref.make(0); + const failedReadApplied = yield* Deferred.make(); yield* Ref.set( - usage, - Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))), + harness.probe, + Ref.updateAndGet(checks, (count) => count + 1).pipe( + Effect.tap((count) => + count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void, + ), + Effect.as(initializeResult), + ), ); - const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); - yield* Deferred.await(readStarted); - yield* harness.provider.onSignedOut; - yield* Deferred.succeed(readResult, { + yield* Ref.set(usage, { checkedAt: "2026-10-09T12:01:00.000Z", - windows: [ - { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }, - ], + windows: [], + unavailable: { reason: "probeFailed" }, }); - yield* Fiber.join(refresh); + yield* harness.provider.snapshot.refresh; + yield* Deferred.await(failedReadApplied); + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits); + yield* harness.provider.onSignedOut; expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + yield* Ref.set(usage, { + checkedAt: "2026-10-09T12:02:00.000Z", + windows: [], + unavailable: { reason: "unsupported" }, + }); + const unsupported = yield* harness.nextPublish( + (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported", + ); + yield* harness.provider.snapshot.refresh; + expect((yield* unsupported)?.usageLimits?.windows).toEqual([]); }), - ), + ); + + it.effect("a quota read finishing after sign-out cannot restore account limits", () => + Effect.gen(function* () { + const readStarted = yield* Deferred.make(); + const readResult = yield* Deferred.make(); + const usage = yield* Ref.make>( + Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }), + ); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); + yield* harness.initialize; + yield* Ref.set(harness.probe, Effect.succeed(initializeResult)); + yield* Ref.set( + usage, + Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))), + ); + const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); + yield* Deferred.await(readStarted); + yield* harness.provider.onSignedOut; + yield* Deferred.succeed(readResult, { + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }], + }); + yield* Fiber.join(refresh); + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + }), ); it.effect("reports ready and starts sessions while one shared quota read is pending", () => - Effect.scoped( - Effect.gen(function* () { - const reads = yield* Ref.make(0); - const readStarted = yield* Deferred.make(); - const readResult = yield* Deferred.make(); - const harness = yield* makeHarness({ - probeUsage: Ref.update(reads, (count) => count + 1).pipe( - Effect.andThen(Deferred.succeed(readStarted, undefined)), - Effect.andThen(Deferred.await(readResult)), - ), - }); - const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); - yield* harness.initialize; - yield* Deferred.await(readStarted); - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onSessionStarted(started, "/other"); - const ready = yield* harness.provider.snapshot.getSnapshot; - expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } }); - expect(ready.usageLimits).toBeUndefined(); - expect(yield* Ref.get(reads)).toBe(1); - const limits = { - checkedAt: "2026-10-09T12:00:00.000Z", - windows: [ - { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }, - ], - } satisfies ServerProviderUsageLimits; - yield* Deferred.succeed(readResult, limits); - expect((yield* published)?.usageLimits).toEqual(limits); - }), - ), + Effect.gen(function* () { + const reads = yield* Ref.make(0); + const readStarted = yield* Deferred.make(); + const readResult = yield* Deferred.make(); + const harness = yield* makeHarness({ + probeUsage: Ref.update(reads, (count) => count + 1).pipe( + Effect.andThen(Deferred.succeed(readStarted, undefined)), + Effect.andThen(Deferred.await(readResult)), + ), + }); + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); + yield* harness.initialize; + yield* Deferred.await(readStarted); + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onSessionStarted(started, "/other"); + const ready = yield* harness.provider.snapshot.getSnapshot; + expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } }); + expect(ready.usageLimits).toBeUndefined(); + expect(yield* Ref.get(reads)).toBe(1); + const limits = { + checkedAt: "2026-10-09T12:00:00.000Z", + windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }], + } satisfies ServerProviderUsageLimits; + yield* Deferred.succeed(readResult, limits); + expect((yield* published)?.usageLimits).toEqual(limits); + }), ); it.effect("a quota read for the previous account is dropped after a new sign-in", () => - Effect.scoped( - Effect.gen(function* () { - const oldReadStarted = yield* Deferred.make(); - const newLimits = { - checkedAt: "2026-10-09T12:01:00.000Z", - windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }], - } satisfies ServerProviderUsageLimits; - const usage = yield* Ref.make>( - Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)), - ); - const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); - const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); - yield* harness.initialize; - yield* Deferred.await(oldReadStarted); - yield* Ref.set(usage, Effect.succeed(newLimits)); - yield* harness.provider.onSignedIn; - yield* harness.provider.onSessionStarted(started); - expect((yield* published)?.usageLimits).toEqual(newLimits); - // Switching again must not republish the previous account's limits, even if the read fails. - const failed = { - checkedAt: "2026-10-09T12:02:00.000Z", - windows: [], - unavailable: { reason: "probeFailed" }, - } satisfies ServerProviderUsageLimits; - yield* Ref.set(usage, Effect.succeed(failed)); - const republished = yield* harness.nextPublish( - (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed", - ); - yield* harness.provider.onSignedIn; - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); - yield* harness.provider.onSessionStarted(started); - expect((yield* republished)?.usageLimits).toEqual(failed); - }), - ), + Effect.gen(function* () { + const oldReadStarted = yield* Deferred.make(); + const newLimits = { + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }], + } satisfies ServerProviderUsageLimits; + const usage = yield* Ref.make>( + Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)), + ); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); + yield* harness.initialize; + yield* Deferred.await(oldReadStarted); + yield* Ref.set(usage, Effect.succeed(newLimits)); + yield* harness.provider.onSignedIn; + yield* harness.provider.onSessionStarted(started); + expect((yield* published)?.usageLimits).toEqual(newLimits); + // Switching again must not republish the previous account's limits, even if the read fails. + const failed = { + checkedAt: "2026-10-09T12:02:00.000Z", + windows: [], + unavailable: { reason: "probeFailed" }, + } satisfies ServerProviderUsageLimits; + yield* Ref.set(usage, Effect.succeed(failed)); + const republished = yield* harness.nextPublish( + (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed", + ); + yield* harness.provider.onSignedIn; + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + yield* harness.provider.onSessionStarted(started); + expect((yield* republished)?.usageLimits).toEqual(failed); + }), ); }); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index db0e21acf0..5abc8e44b2 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -1,3 +1,4 @@ +import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { ANTIGRAVITY_DEFAULT_MODEL, ProviderDriverKind, @@ -40,7 +41,7 @@ import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts"; const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] }); const MAX_WORKSPACE_SNAPSHOTS = 32; -const HEALTH_CHECK_TIMEOUT = "90 seconds"; +const HEALTH_CHECK_TIMEOUT_MS = 90_000; const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity."; const AUTH_UNCHECKED_MESSAGE = "Antigravity is installed. Google account access is not checked yet."; @@ -155,6 +156,7 @@ interface AntigravityProviderState { } interface AntigravityProviderOptions { + readonly environment?: NodeJS.ProcessEnv; readonly stampIdentity: (snapshot: ServerProviderDraft) => Effect.Effect; readonly probe: Effect.Effect< EffectAcpSchema.InitializeResponse, @@ -271,10 +273,12 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const checkProvider = Effect.fn("checkAntigravityProvider")(function* () { if (!settings.enabled) return yield* getSnapshot; const before = yield* SubscriptionRef.get(metadata); - const result = yield* options.probe.pipe( - Effect.timeoutOption(HEALTH_CHECK_TIMEOUT), - Effect.result, + const timeoutMs = resolveProviderProbeTimeoutMs( + "antigravity", + HEALTH_CHECK_TIMEOUT_MS, + options.environment, ); + const result = yield* options.probe.pipe(Effect.timeoutOption(timeoutMs), Effect.result); const initialized = Result.isSuccess(result) && Option.isSome(result.success) ? result.success.value : undefined; const version = initialized?.agentInfo?.version; @@ -289,7 +293,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func ? "Antigravity ACP runtime is not installed or its executable could not be found." : failure ? "Antigravity could not complete its local health check." - : `Antigravity did not respond to its local health check within ${HEALTH_CHECK_TIMEOUT}.`; + : `Antigravity did not respond to its local health check within ${timeoutMs / 1_000} seconds.`; const supportsTextGeneration = initialized !== undefined ? yield* options.supportsTextGeneration : false; const updatedAt = DateTime.formatIso(yield* DateTime.now); diff --git a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts index bf3c931887..b89cffa423 100644 --- a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts +++ b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts @@ -14,10 +14,13 @@ import { buildClaudeCapabilitiesProbeQueryOptions, probeClaudeCapabilities, probeClaudeWorkspaceSnapshot, + spawnClaudeProbeThroughEnv, } from "./ClaudeProvider.ts"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); +const hostPath = process.env.PATH; + const decodeClaudeSettings = Schema.decodeEffect(ClaudeSettings); it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => { @@ -27,6 +30,7 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp environment: { HOME: "/home/user" }, cwd: undefined, managedMcpConfig: true, + spawnVia: undefined, }); // Claude exits before initializing when handed --strict-mcp-config here. @@ -35,6 +39,29 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false"); }); +// A shell trampoline would not do: dash drops the exported function, and the launcher exits 127. +it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "starts a Bash launcher that calls an exported function in the probe's workspace", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped()); + yield* fileSystem.writeFileString(`${workspace}/claude`, '#!/bin/bash\nt3_launch "$@"\n'); + yield* fileSystem.chmod(`${workspace}/claude`, 0o755); + const child = spawnClaudeProbeThroughEnv({ + command: "claude", + args: ["--probe"], + cwd: workspace, + env: { PATH: `.:${hostPath}`, "BASH_FUNC_t3_launch%%": '() { echo "$PWD $@"; }' }, + // @effect-diagnostics-next-line abortControllerInEffect:off - The launcher exits on its own. + signal: new AbortController().signal, + }); + assert.deepEqual(child.spawnargs.slice(0, 3), ["/usr/bin/env", "-C", workspace]); + const output = yield* Effect.promise(() => child.stdout.setEncoding("utf8").toArray()); + assert.equal(output.join(""), `${workspace} --probe\n`); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("reports a deleted worktree's scan as finished, not pending", () => Effect.gen(function* () { const snapshot = yield* probeClaudeWorkspaceSnapshot( diff --git a/apps/server/src/provider/ClaudeCodeModelRoutes.test.ts b/apps/server/src/provider/ClaudeCodeModelRoutes.test.ts new file mode 100644 index 0000000000..2c06148cac --- /dev/null +++ b/apps/server/src/provider/ClaudeCodeModelRoutes.test.ts @@ -0,0 +1,67 @@ +import { assert, describe, it } from "@effect/vitest"; +import { type ModelSelection, ProviderInstanceId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; + +import { makeClaudeCodeModelRoutes } from "./ClaudeCodeModelRoutes.ts"; +import { + BUNDLED_CLAUDE_MODEL_CATALOG, + resolveClaudeCatalogApiModelId, +} from "./ClaudeModelCatalog.ts"; + +describe("Claude Code model routes", () => { + it.effect( + "a turn that starts before the first probe settles waits and then gets its routes", + () => + Effect.gen(function* () { + const haiku = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-haiku-4-5", + } satisfies ModelSelection; + const routes = yield* makeClaudeCodeModelRoutes( + () => Effect.succeed("same settings"), + "/state", + ); + const early = yield* routes + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* routes.record([ + { value: "haiku", resolvedModel: "us.anthropic.claude-haiku-4-5-20251001-v1:0" }, + ]); + yield* routes.settle; + assert.strictEqual( + resolveClaudeCatalogApiModelId(yield* Fiber.join(early), haiku), + "haiku", + ); + + // A first check that never reaches the probe still releases waiting turns. + const unprobed = yield* makeClaudeCodeModelRoutes( + () => Effect.succeed("same settings"), + "/state", + ); + const waiting = yield* unprobed + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* unprobed.settle; + assert.strictEqual(yield* Fiber.join(waiting), BUNDLED_CLAUDE_MODEL_CATALOG); + + const stuck = yield* makeClaudeCodeModelRoutes( + () => Effect.succeed("same settings"), + "/state", + ); + const fallback = yield* stuck + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("2 minutes"); + assert.strictEqual(yield* Fiber.join(fallback), BUNDLED_CLAUDE_MODEL_CATALOG); + // Later turns, steers and effort changes do not wait for the stuck probe again. + const later = yield* stuck + .route(BUNDLED_CLAUDE_MODEL_CATALOG, "/project") + .pipe(Effect.timeoutOption("1 second"), Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("1 second"); + assert.deepStrictEqual(yield* Fiber.join(later), Option.some(BUNDLED_CLAUDE_MODEL_CATALOG)); + }), + ); +}); diff --git a/apps/server/src/provider/ClaudeCodeModelRoutes.ts b/apps/server/src/provider/ClaudeCodeModelRoutes.ts new file mode 100644 index 0000000000..6a9e7a48e6 --- /dev/null +++ b/apps/server/src/provider/ClaudeCodeModelRoutes.ts @@ -0,0 +1,116 @@ +import { + type ModelInfo as ClaudeModelInfo, + resolveSettings as resolveClaudeSettings, + type SettingSource, + type Settings as ClaudeSdkSettings, +} from "@anthropic-ai/claude-agent-sdk"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; + +import { claudeLocalSettingsDirectory } from "./Drivers/ClaudeHome.ts"; +import { type ClaudeModelCatalog, withClaudeCodeModelRoutes } from "./ClaudeModelCatalog.ts"; + +// Env names that pick the backend, its region, or the model a family alias resolves to. +const MODEL_SETTINGS_ENV_PREFIXES = [ + "ANTHROPIC_", + "CLAUDE_CODE_USE_", + "AWS_", + "CLOUD_ML_", + "VERTEX_", +]; + +/** Equal keys mean Claude Code resolves model ids the same way under both settings. */ +function claudeModelSettingsKey(settings: ClaudeSdkSettings): string { + const sortedEntries = (record: Readonly> | undefined) => + Object.entries(record ?? {}).toSorted(([a], [b]) => a.localeCompare(b)); + return JSON.stringify([ + settings.availableModels ?? null, + sortedEntries(settings.modelOverrides), + sortedEntries(settings.env).filter(([name]) => + MODEL_SETTINGS_ENV_PREFIXES.some((prefix) => name.startsWith(prefix)), + ), + ]); +} + +const NO_MODEL_SETTINGS_KEY = claudeModelSettingsKey({}); + +class ClaudeModelSettingsReadError extends Schema.TaggedError()( + "ClaudeModelSettingsReadError", + { cause: Schema.Defect() }, +) {} + +export const resolveClaudeModelSettingsKey = Effect.fn("resolveClaudeModelSettingsKey")(function* ( + settingSources: ReadonlyArray, + cwd: string | null, +) { + // The SDK reads the local file from cwd, Claude Code from the main checkout's root. No key, so + // no routes, when that root file touches model settings. + const localDirectory = cwd === null ? null : yield* claudeLocalSettingsDirectory(cwd); + if (localDirectory !== null && localDirectory !== cwd) { + const rootLocal = yield* Effect.tryPromise({ + try: () => resolveClaudeSettings({ cwd: localDirectory, settingSources: ["local"] }), + catch: (cause) => new ClaudeModelSettingsReadError({ cause }), + }).pipe( + Effect.map(({ sources }) => sources.find(({ source }) => source === "local")?.settings), + Effect.orElseSucceed(() => undefined), + ); + if (claudeModelSettingsKey(rootLocal ?? {}) !== NO_MODEL_SETTINGS_KEY) return undefined; + } + return yield* Effect.tryPromise({ + try: () => + resolveClaudeSettings({ + ...(cwd === null ? {} : { cwd }), + settingSources: [...settingSources], + }), + catch: (cause) => new ClaudeModelSettingsReadError({ cause }), + }).pipe( + Effect.map(({ effective }) => claudeModelSettingsKey(effective)), + Effect.orElseSucceed(() => undefined), + ); +}); + +type ReportedModel = Pick; + +/** + * Claude Code's reported model ids, applied to a turn only where its cwd resolves model settings + * as the probe's cwd did. `settle` releases turns waiting for the first probe, whatever its outcome. + */ +export const makeClaudeCodeModelRoutes = Effect.fn("makeClaudeCodeModelRoutes")(function* ( + settingsKey: (cwd: string | null) => Effect.Effect, + probeCwd: string, +) { + const firstProbeSettled = yield* Deferred.make(); + const reported = yield* Ref.make<{ + readonly models: ReadonlyArray; + readonly settingsKey: string | undefined; + }>({ models: [], settingsKey: undefined }); + return { + record: Effect.fn("ClaudeCodeModelRoutes.record")(function* ( + models: ReadonlyArray, + ) { + yield* Ref.set(reported, { models, settingsKey: yield* settingsKey(probeCwd) }); + }), + settle: Deferred.succeed(firstProbeSettled, undefined).pipe(Effect.asVoid), + route: Effect.fn("ClaudeCodeModelRoutes.route")(function* ( + base: ClaudeModelCatalog, + cwd: string | null, + launchSettings?: ClaudeSdkSettings, + ) { + // Leave room for the sequential version and capability probes before falling back once; + // an expired wait counts as settled so later calls do not wait again. + yield* Deferred.await(firstProbeSettled).pipe( + Effect.timeoutOption("2 minutes"), + Effect.andThen(Deferred.succeed(firstProbeSettled, undefined)), + ); + if (claudeModelSettingsKey(launchSettings ?? {}) !== NO_MODEL_SETTINGS_KEY) return base; + const { models, settingsKey: probeKey } = yield* Ref.get(reported); + const routed = withClaudeCodeModelRoutes(base, models); + // Project settings can point an alias at another model, so routes hold only where the + // cwd resolves the same model settings as the probe's. + if (routed === base || probeKey === undefined) return base; + return (yield* settingsKey(cwd)) === probeKey ? routed : base; + }), + }; +}); diff --git a/apps/server/src/provider/ClaudeModelCatalog.test.ts b/apps/server/src/provider/ClaudeModelCatalog.test.ts index 76436f729f..bbcc02f901 100644 --- a/apps/server/src/provider/ClaudeModelCatalog.test.ts +++ b/apps/server/src/provider/ClaudeModelCatalog.test.ts @@ -1,8 +1,11 @@ import { assert, describe, it } from "@effect/vitest"; -import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { type ModelSelection, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import { resolveProviderCatalog, type ModelManifestData } from "./ModelManifest.ts"; import { + BUNDLED_CLAUDE_MODEL_CATALOG, + capClaudeCatalogEffort, + type ClaudeModelCatalog, formatClaudeVersionUpgradeMessage, getClaudeCatalogModelCapabilities, normalizeClaudeCatalogEffort, @@ -14,6 +17,7 @@ import { resolveClaudeModelSlug, resolveClaudeUpdateRequiredModels, scopeClaudeModelCatalog, + withClaudeCodeModelRoutes, } from "./ClaudeModelCatalog.ts"; const manifest = (): ModelManifestData => ({ @@ -133,6 +137,13 @@ describe("Claude model catalog", () => { formatClaudeVersionUpgradeMessage(catalog, "3.1.9"), "Claude Code v3.1.9 is too old for Claude Synthetic Next. Upgrade to v3.2.0 or newer to access it.", ); + // Claude Code before 2.1.321 does not know claude-fable-5-2 and runs it with a 200K window. + assert.notInclude( + resolveClaudeModelsForVersion(BUNDLED_CLAUDE_MODEL_CATALOG, "2.1.320").map( + (model) => model.slug, + ), + "claude-fable-5-2", + ); }); it("resolves aliases and declarative adapter mappings", () => { @@ -230,4 +241,301 @@ describe("Claude model catalog", () => { ["claude-synthetic-next", "claude-custom-tuned"], ); }); + + // Rows Claude Code 2.1.310 reports from initialization for each configuration. + it("sends the model id Claude Code reports when it serves a catalog model under another id", () => { + const apiModel = ( + catalog: ClaudeModelCatalog, + model: string, + options?: ModelSelection["options"], + ) => + resolveClaudeCatalogApiModelId(catalog, { + instanceId: ProviderInstanceId.make("claudeAgent"), + model, + ...(options ? { options } : {}), + }); + + // Bedrock with ANTHROPIC_DEFAULT_*_MODEL and an availableModels allowlist of their ids. + const configuredBedrock = withClaudeCodeModelRoutes(BUNDLED_CLAUDE_MODEL_CATALOG, [ + { value: "default", resolvedModel: "global.anthropic.claude-opus-5-5" }, + { value: "sonnet", resolvedModel: "global.anthropic.claude-sonnet-5-5[1m]" }, + { value: "opus", resolvedModel: "global.anthropic.claude-opus-5-5" }, + { value: "haiku", resolvedModel: "global.anthropic.claude-haiku-5-5" }, + ]); + assert.strictEqual(apiModel(configuredBedrock, "claude-haiku-5-5"), "haiku"); + assert.strictEqual(apiModel(configuredBedrock, "haiku-5.5"), "haiku"); + assert.strictEqual(apiModel(configuredBedrock, "claude-sonnet-5-5"), "sonnet"); + assert.strictEqual(apiModel(configuredBedrock, "claude-opus-5-5"), "opus"); + assert.strictEqual(apiModel(configuredBedrock, "claude-opus-5"), "claude-opus-5"); + + // Bedrock with no model settings: Claude Code's `haiku` is Haiku 4.5 there. + const defaultBedrock = withClaudeCodeModelRoutes(BUNDLED_CLAUDE_MODEL_CATALOG, [ + { + value: "us.anthropic.claude-opus-4-6-v1", + resolvedModel: "us.anthropic.claude-opus-4-6-v1", + }, + { + value: "us.anthropic.claude-opus-4-6-v1[1m]", + resolvedModel: "us.anthropic.claude-opus-4-6-v1[1m]", + }, + { value: "haiku", resolvedModel: "us.anthropic.claude-haiku-4-5-20251001-v1:0" }, + ]); + assert.strictEqual( + apiModel(defaultBedrock, "claude-opus-4-6", [{ id: "contextWindow", value: "1m" }]), + "us.anthropic.claude-opus-4-6-v1[1m]", + ); + assert.strictEqual( + apiModel(defaultBedrock, "claude-opus-4-6", [{ id: "contextWindow", value: "200k" }]), + "us.anthropic.claude-opus-4-6-v1", + ); + assert.strictEqual(apiModel(defaultBedrock, "claude-haiku-4-5"), "haiku"); + assert.strictEqual(apiModel(defaultBedrock, "claude-haiku-5-5"), "claude-haiku-5-5"); + + // First-party ids already are what Claude Code runs, even when an alias points elsewhere. + const firstParty = withClaudeCodeModelRoutes(BUNDLED_CLAUDE_MODEL_CATALOG, [ + { value: "default", resolvedModel: "claude-opus-5-5" }, + { value: "opus", resolvedModel: "claude-opus-5-5" }, + { value: "claude-fable-5-1[1m]", resolvedModel: "claude-fable-5-1[1m]" }, + { value: "haiku", resolvedModel: "claude-haiku-4-5-20251001" }, + ]); + assert.strictEqual(firstParty, BUNDLED_CLAUDE_MODEL_CATALOG); + }); + + it("marks effort options that would run above the cap without changing ids or defaults", () => { + const effortModel = (slug: string) => ({ + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + type: "select" as const, + options: [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "xhigh", label: "Extra High" }, + { id: "max", label: "Max" }, + { id: "ultracode", label: "Ultracode" }, + { id: "ultrathink", label: "Ultrathink" }, + ], + }, + ], + }, + }); + const models = [effortModel("claude-plain"), effortModel("claude-remapped")]; + const catalog: ClaudeModelCatalog = { + models: [ + { + model: models[0]!, + runtime: { effortMap: { ultracode: "xhigh", ultrathink: null } }, + compatibility: {}, + }, + { + model: models[1]!, + runtime: { effortMap: { max: "high", xhigh: "max", ultrathink: null } }, + compatibility: {}, + }, + ], + }; + const options = (cap: "high" | "xhigh") => + capClaudeCatalogEffort(catalog, models, [{ maxEffortLevel: cap }]).map((model) => { + const effort = model.capabilities?.optionDescriptors?.[0]; + return effort?.type === "select" ? effort.options : undefined; + }); + + assert.deepStrictEqual(options("high"), [ + [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "xhigh", label: "Extra High (capped to High)" }, + { id: "max", label: "Max (capped to High)" }, + { id: "ultracode", label: "Ultracode (capped to High)" }, + { id: "ultrathink", label: "Ultrathink" }, + ], + [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "xhigh", label: "Extra High (capped to High)" }, + { id: "max", label: "Max" }, + { id: "ultracode", label: "Ultracode" }, + { id: "ultrathink", label: "Ultrathink" }, + ], + ]); + // An effortMap that sends Extra High as max stays unmarked under an xhigh cap: the CLI runs + // it at xhigh, which is what the label says. + assert.deepStrictEqual( + options("xhigh").map((model) => model?.map((option) => option.label)), + [ + ["Medium", "High", "Extra High", "Max (capped to Extra High)", "Ultracode", "Ultrathink"], + ["Medium", "High", "Extra High", "Max", "Ultracode", "Ultrathink"], + ], + ); + + // A per-model cap applies without a top-level one and leaves other models uncapped. + assert.deepStrictEqual( + capClaudeCatalogEffort(catalog, models, [ + { modelMaxEffortLevels: new Map([["claude-plain", "high"]]) }, + ]).map((model) => { + const effort = model.capabilities?.optionDescriptors?.[0]; + return effort?.type === "select" ? effort.options.map((option) => option.label) : []; + }), + [ + [ + "Medium", + "High", + "Extra High (capped to High)", + "Max (capped to High)", + "Ultracode (capped to High)", + "Ultrathink", + ], + ["Medium", "High", "Extra High", "Max", "Ultracode", "Ultrathink"], + ], + ); + + // Without an Extra High option (Opus 4.6), the CLI clamps an xhigh cap down to High. + const noXhigh = { + slug: "claude-no-xhigh", + name: "claude-no-xhigh", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + type: "select" as const, + options: [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "max", label: "Max" }, + ], + }, + ], + }, + }; + const [capped] = capClaudeCatalogEffort( + { models: [] }, + [noXhigh], + [{ maxEffortLevel: "xhigh" }], + ); + const cappedEffort = capped?.capabilities?.optionDescriptors?.[0]; + assert.deepStrictEqual( + cappedEffort?.type === "select" ? cappedEffort.options.map((option) => option.label) : [], + ["Low", "Medium", "High", "Max (capped to High)"], + ); + }); + + it("leaves custom model effort labels alone under a cap", () => { + const custom = { + slug: "claude-custom-copy", + name: "Copy", + isCustom: true, + capabilities: { + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + type: "select" as const, + options: [ + { id: "high", label: "High", isDefault: true }, + { id: "max", label: "Max (capped to High)" }, + ], + }, + ], + }, + }; + + assert.deepStrictEqual( + capClaudeCatalogEffort({ models: [] }, [custom], [{ maxEffortLevel: "high" }]), + [custom], + ); + }); + + it("resolves maxEffortLevel per settings source and per model key like Claude Code", () => { + const opus = { + slug: "claude-opus-5-5", + name: "Opus 5.5", + isCustom: false, + aliases: ["opus", "opus-5.5", "claude-opus-5.5"], + capabilities: { + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + type: "select" as const, + options: [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "max", label: "Max" }, + ], + }, + ], + }, + }; + const catalog: ClaudeModelCatalog = { + models: [ + { model: opus, runtime: {}, compatibility: {} }, + { + model: { + slug: "claude-opus-5", + name: "Opus 5", + isCustom: false, + capabilities: { optionDescriptors: [] }, + }, + runtime: {}, + compatibility: {}, + }, + ], + }; + const maxLabel = (sources: Parameters[2]) => { + const effort = capClaudeCatalogEffort(catalog, [opus], sources)[0]?.capabilities + ?.optionDescriptors?.[0]; + return effort?.type === "select" ? effort.options.at(-1)?.label : undefined; + }; + const perModel = (entries: Record) => ({ + modelMaxEffortLevels: new Map(Object.entries(entries)), + }); + + // Claude Code matches family aliases and [1m] spellings case-insensitively. + assert.strictEqual(maxLabel([perModel({ Opus: "medium" })]), "Max (capped to Medium)"); + assert.strictEqual( + maxLabel([perModel({ "claude-opus-5-5[1M]": "medium" })]), + "Max (capped to Medium)", + ); + assert.strictEqual(maxLabel([perModel({ " OPUS[1m] ": "medium" })]), "Max (capped to Medium)"); + // Other keys name the most specific model id they contain, so dated and provider-prefixed ids + // match while the catalog's dotted aliases and a less specific model id do not. + for (const key of [ + "claude-opus-5-5-20260101", + "CLAUDE-OPUS-5-5-20260101[1m]", + "us.anthropic.claude-opus-5-5-v1:0", + "claude-opus-5-5-latest", + ]) { + assert.strictEqual(maxLabel([perModel({ [key]: "medium" })]), "Max (capped to Medium)", key); + } + for (const key of ["claude-opus-5.5", "opus-5.5", "opus-5-5", "opus [1m]", "claude-opus-5"]) { + assert.strictEqual(maxLabel([perModel({ [key]: "medium" })]), "Max", key); + } + // Keys naming the same model keep the lowest cap, and a `max` key does not exempt it. + assert.strictEqual( + maxLabel([perModel({ opus: "max", "claude-opus-5-5": "low" })]), + "Max (capped to Low)", + ); + // A per-model `max` only exempts the model from its own source's top-level cap. + assert.strictEqual( + maxLabel([{ maxEffortLevel: "medium", ...perModel({ opus: "max" }) }]), + "Max", + ); + assert.strictEqual( + maxLabel([perModel({ opus: "max" }), { maxEffortLevel: "high" }]), + "Max (capped to High)", + ); + assert.strictEqual( + maxLabel([{ maxEffortLevel: "medium" }, perModel({ opus: "high" })]), + "Max (capped to Medium)", + ); + }); }); diff --git a/apps/server/src/provider/ClaudeModelCatalog.ts b/apps/server/src/provider/ClaudeModelCatalog.ts index 4efca48f25..e3d4ea4397 100644 --- a/apps/server/src/provider/ClaudeModelCatalog.ts +++ b/apps/server/src/provider/ClaudeModelCatalog.ts @@ -32,6 +32,8 @@ export interface ClaudeCatalogModel { readonly model: ServerProviderModel; readonly runtime: ClaudeCodeProfile; readonly compatibility: ClaudeCodeCompatibility; + /** What to send Claude Code instead of the slug, from its own model list. */ + readonly apiModel?: string; } export interface ClaudeModelCatalog { @@ -221,7 +223,7 @@ export function claudeReportedModels( return models; } -function resolveClaudeCatalogModel( +export function resolveClaudeCatalogModel( catalog: ClaudeModelCatalog, slugOrAlias: string | null | undefined, ): ClaudeCatalogModel | undefined { @@ -235,6 +237,44 @@ function resolveClaudeCatalogModel( ); } +// Cloud backends decorate first-party ids: Bedrock adds a region prefix and a +// version ("us.anthropic.claude-opus-4-6-v1"), Vertex adds "@". +function stripClaudeBackendDecoration(wireModel: string): string { + return wireModel + .replace(/^(?:[a-z-]+\.)?anthropic\./, "") + .replace(/-v\d+(?::\d+)?$/, "") + .replace(/@[^@]*$/, ""); +} + +/** + * On Bedrock, Vertex and similar backends Claude Code does not accept the first-party slug: it + * either sends it verbatim or, when `availableModels` excludes it, silently runs the default + * model instead. Its model list names the id that does work, often a family alias that + * `ANTHROPIC_DEFAULT_*_MODEL` points at a backend id. + */ +export function withClaudeCodeModelRoutes( + catalog: ClaudeModelCatalog, + reportedModels: ReadonlyArray>, +): ClaudeModelCatalog { + const apiModels = new Map(); + for (const reported of reportedModels) { + if (reported.value === "default") continue; + const wireModel = stripClaudeContextWindowSuffix(reported.resolvedModel ?? reported.value); + const firstPartyModel = stripClaudeBackendDecoration(wireModel); + if (firstPartyModel === wireModel) continue; + const entry = resolveClaudeCatalogModel(catalog, firstPartyModel); + if (!entry || apiModels.has(entry.model.slug)) continue; + apiModels.set(entry.model.slug, stripClaudeContextWindowSuffix(reported.value)); + } + if (apiModels.size === 0) return catalog; + return { + models: catalog.models.map((entry) => { + const apiModel = apiModels.get(entry.model.slug); + return apiModel ? { ...entry, apiModel } : entry; + }), + }; +} + export function resolveClaudeModelSlug(catalog: ClaudeModelCatalog, slugOrAlias: string): string { return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.slug ?? slugOrAlias; } @@ -322,6 +362,137 @@ export function formatClaudeVersionUpgradeMessage( return `Claude Code ${versionLabel} is too old for ${unavailable.model.name}. Upgrade to v${unavailable.compatibility.minVersion} or newer to access it.`; } +/** Claude Code's effort levels, lowest first. */ +export const CLAUDE_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const; +export type ClaudeEffortLevel = (typeof CLAUDE_EFFORT_LEVELS)[number]; + +function claudeEffortRank(level: string | undefined): number { + return CLAUDE_EFFORT_LEVELS.indexOf(level as ClaudeEffortLevel); +} + +/** One settings source's effort caps, with `modelSettings` keys as the user wrote them. */ +export interface ClaudeEffortCapSource { + readonly maxEffortLevel?: ClaudeEffortLevel; + readonly modelMaxEffortLevels?: ReadonlyMap; +} + +const CLAUDE_1M_SUFFIX = "[1m]"; +const CLAUDE_CODE_FAMILY_ALIASES: ReadonlySet = new Set([ + "opus", + "sonnet", + "haiku", + "fable", +]); + +/** + * Names the model a `modelSettings` key caps the way Claude Code does, which is narrower than the + * catalog's aliases: only a family alias (optionally `[1m]`) resolves as an alias, and any other key + * names the most specific model id it contains, so `claude-opus-5-5-20260101` and Bedrock ids match + * while `claude-opus-5.5` matches nothing. + */ +function resolveClaudeModelSettingsKey( + catalog: ClaudeModelCatalog, + key: string, +): string | undefined { + const lowered = key.trim().toLowerCase(); + const unsuffixed = lowered.endsWith(CLAUDE_1M_SUFFIX) + ? lowered.slice(0, -CLAUDE_1M_SUFFIX.length) + : lowered; + if (CLAUDE_CODE_FAMILY_ALIASES.has(unsuffixed)) { + return catalog.models.find( + (entry) => !entry.model.isCustom && entry.model.aliases?.includes(unsuffixed), + )?.model.slug; + } + let match: string | undefined; + for (const { model } of catalog.models) { + if (!model.isCustom && lowered.includes(model.slug) && model.slug.length > (match?.length ?? 0)) + match = model.slug; + } + return match; +} + +/** Keys `modelSettings` caps by canonical slug, keeping the lowest cap when several keys name one model. */ +function resolveClaudeModelMaxEffortLevels( + catalog: ClaudeModelCatalog, + levels: ReadonlyMap | undefined, +): ReadonlyMap { + const resolved = new Map(); + for (const [key, level] of levels ?? []) { + const slug = resolveClaudeModelSettingsKey(catalog, key); + if (!slug) continue; + const current = resolved.get(slug); + if (!current || claudeEffortRank(level) < claudeEffortRank(current)) resolved.set(slug, level); + } + return resolved; +} + +/** + * Claude Code clamps efforts above `maxEffortLevel` to the model's highest level under it, so + * such options are relabelled, not removed, keeping stored selections valid. Per-model caps + * replace their own source's top-level cap and `max` means none; across sources the lowest wins. + */ +export function capClaudeCatalogEffort( + catalog: ClaudeModelCatalog, + models: ReadonlyArray, + sources: ReadonlyArray, +): ReadonlyArray { + if (sources.length === 0) return models; + const resolvedSources = sources.map((source) => ({ + maxEffortLevel: source.maxEffortLevel, + modelMaxEffortLevels: resolveClaudeModelMaxEffortLevels(catalog, source.modelMaxEffortLevels), + })); + return models.map((model) => { + // Custom model labels are user-authored, so they are left alone. + if (model.isCustom || !model.capabilities?.optionDescriptors) return model; + const modelMaxEffortLevel = resolvedSources.reduce( + (lowest, source) => { + const level = source.modelMaxEffortLevels.get(model.slug) ?? source.maxEffortLevel; + return level && + level !== "max" && + (!lowest || claudeEffortRank(level) < claudeEffortRank(lowest)) + ? level + : lowest; + }, + undefined, + ); + if (!modelMaxEffortLevel) return model; + const capRank = claudeEffortRank(modelMaxEffortLevel); + return { + ...model, + capabilities: { + ...model.capabilities, + optionDescriptors: model.capabilities.optionDescriptors.map((descriptor) => { + if (descriptor.id !== "effort" || descriptor.type !== "select") return descriptor; + const cap = descriptor.options.reduce<{ rank: number; label: string } | undefined>( + (best, option) => { + const rank = claudeEffortRank(option.id); + return rank >= 0 && rank <= capRank && rank > (best?.rank ?? -1) + ? { rank, label: option.label } + : best; + }, + undefined, + ); + if (!cap) return descriptor; + return { + ...descriptor, + options: descriptor.options.map((option) => { + const idRank = claudeEffortRank(option.id); + const sentRank = claudeEffortRank( + normalizeClaudeCatalogEffort(catalog, option.id, model.slug), + ); + const displayedRank = idRank >= 0 ? idRank : sentRank; + const runsRank = sentRank >= 0 ? sentRank : idRank; + return displayedRank > cap.rank && runsRank > cap.rank + ? { ...option, label: `${option.label} (capped to ${cap.label})` } + : option; + }), + }; + }), + }, + }; + }); +} + export function resolveClaudeCatalogEffort( catalog: ClaudeModelCatalog, model: string | null | undefined, @@ -329,7 +500,7 @@ export function resolveClaudeCatalogEffort( ): string | undefined { if (!resolveClaudeCatalogModel(catalog, model)) { const effort = raw?.trim(); - return effort && ["low", "medium", "high", "xhigh", "max"].includes(effort) + return effort && (CLAUDE_EFFORT_LEVELS as ReadonlyArray).includes(effort) ? effort : undefined; } @@ -375,7 +546,7 @@ export function resolveClaudeCatalogApiModelId( modelSelection: ModelSelection, ): string { const entry = resolveClaudeCatalogModel(catalog, modelSelection.model); - const slug = entry?.model.slug ?? modelSelection.model; + const slug = entry?.apiModel ?? entry?.model.slug ?? modelSelection.model; const descriptors = getProviderOptionDescriptors({ caps: entry?.model.capabilities ?? EMPTY_CAPABILITIES, selections: modelSelection.options, diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index 8b748cad39..bc4e9979dd 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -1,5 +1,9 @@ // apps/server/src/provider/ClaudeProvider.ts // probes claude capabilities & account metadata +// @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK's spawn hook returns a Node child process. +import * as NodeChildProcess from "node:child_process"; + +import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { type ClaudeSettings, type ModelCapabilities, @@ -19,6 +23,9 @@ import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { createModelCapabilities } from "@t3tools/shared/model"; +import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as SpawnWorker from "../process/SpawnWorker.ts"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { query as claudeQuery, @@ -28,6 +35,7 @@ import { type SDKControlGetUsageResponse, type SDKUserMessage, type SettingSource, + type SpawnOptions as ClaudeSpawnOptions, } from "@anthropic-ai/claude-agent-sdk"; import { @@ -62,6 +70,10 @@ import { } from "./claudeUsageLimits.ts"; import { BUNDLED_CLAUDE_MODEL_CATALOG, + CLAUDE_EFFORT_LEVELS, + capClaudeCatalogEffort, + type ClaudeEffortCapSource, + type ClaudeEffortLevel, type ClaudeModelCatalog, claudeReportedModels, formatClaudeVersionUpgradeMessage, @@ -179,11 +191,16 @@ function formatClaudeSubscriptionAuthLabel(subscriptionType: string): string { return `Claude ${subscriptionLabel} Subscription`; } +function hasApiKey(apiKeySource: string | undefined): boolean { + return Boolean(apiKeySource) && apiKeySource !== "none"; +} + function claudeAuthMetadata(input: { readonly subscriptionType: string | undefined; readonly authMethod: string | undefined; + readonly apiKeySource: string | undefined; }): { readonly type: string; readonly label: string } | undefined { - if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") { + if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey" || hasApiKey(input.apiKeySource)) { return { type: "apiKey", label: "Claude API Key", @@ -218,8 +235,7 @@ function claudeAuthStatus( } if (capabilities.tokenSource !== "none") return "authenticated"; // API keys can authenticate with tokenSource: none; also check key and account fields. - const hasApiKey = Boolean(capabilities.apiKeySource) && capabilities.apiKeySource !== "none"; - return hasApiKey || capabilities.email || capabilities.subscriptionType + return hasApiKey(capabilities.apiKeySource) || capabilities.email || capabilities.subscriptionType ? "authenticated" : "unauthenticated"; } @@ -235,14 +251,49 @@ const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [ "local", ] as const satisfies ReadonlyArray; +/** + * The SDK's own spawn stats the executable and hands libuv the workspace as cwd, so a mount + * that stops answering freezes the server. `env` enters the cwd and finds the CLI in the child. + * A shell would not do: dash drops the exported Bash functions a launcher may call. + */ +export function spawnClaudeProbeThroughEnv({ + command, + args, + cwd, + env, + signal, +}: ClaudeSpawnOptions) { + const launch = envTrampoline(command, args, cwd) ?? { command, args, cwd }; + return NodeChildProcess.spawn(launch.command, launch.args, { + ...("cwd" in launch ? { cwd: launch.cwd } : {}), + env, + signal, + // The probe ignores stderr. + stdio: ["pipe", "pipe", "ignore"], + }); +} + +/** Windows runs CreateProcess on the calling thread, so the probe launches from a launcher thread. */ +function spawnClaudeProbeOffThread({ command, args, cwd, env, signal }: ClaudeSpawnOptions) { + const child = SpawnWorker.spawnPiped(command, args, { cwd, env, signal, windowsHide: true }); + // The probe ignores stderr; drain it so a full pipe cannot stall the CLI. + child.stderr.resume(); + return child; +} + export function buildClaudeCapabilitiesProbeQueryOptions(input: { readonly executablePath: string; readonly abortController: AbortController; readonly environment: NodeJS.ProcessEnv; readonly cwd: string | undefined; readonly managedMcpConfig: boolean; + readonly spawnVia: "env" | "launcher-thread" | undefined; }): ClaudeQueryOptions { return { + ...(input.spawnVia === "env" ? { spawnClaudeCodeProcess: spawnClaudeProbeThroughEnv } : {}), + ...(input.spawnVia === "launcher-thread" + ? { spawnClaudeCodeProcess: spawnClaudeProbeOffThread } + : {}), persistSession: false, pathToClaudeCodeExecutable: input.executablePath, abortController: input.abortController, @@ -285,8 +336,73 @@ export type ClaudeCapabilitiesProbe = { /** Undefined means get_usage failed; absent windows on success mean no subscription windows, as with API keys. */ readonly usage?: Pick; readonly usageCheckedAt?: string; + /** Each settings source's `maxEffortLevel` caps; Claude Code clamps every higher effort. */ + readonly effortCapSources?: ReadonlyArray; +}; + +// `getSettings` exists at runtime but is missing from the SDK's `Query` type, and older CLIs +// reject the control request. +type ClaudeSettingsQuery = { + readonly getSettings?: () => Promise<{ + readonly effective?: unknown; + readonly sources?: unknown; + }>; }; +function parseClaudeMaxEffortLevel(value: unknown): ClaudeEffortLevel | undefined { + return CLAUDE_EFFORT_LEVELS.find((level) => level === value); +} + +function parseClaudeModelMaxEffortLevels( + modelSettings: unknown, +): ReadonlyMap | undefined { + if (!modelSettings || typeof modelSettings !== "object") return undefined; + const levels = new Map(); + for (const [model, settings] of Object.entries(modelSettings)) { + const level = parseClaudeMaxEffortLevel( + settings && typeof settings === "object" + ? (settings as { readonly maxEffortLevel?: unknown }).maxEffortLevel + : undefined, + ); + if (level) levels.set(model, level); + } + return levels.size > 0 ? levels : undefined; +} + +function parseClaudeEffortCapSource(settings: unknown): ClaudeEffortCapSource | undefined { + if (!settings || typeof settings !== "object") return undefined; + const { maxEffortLevel, modelSettings } = settings as { + readonly maxEffortLevel?: unknown; + readonly modelSettings?: unknown; + }; + const level = parseClaudeMaxEffortLevel(maxEffortLevel); + const modelMaxEffortLevels = parseClaudeModelMaxEffortLevels(modelSettings); + return level || modelMaxEffortLevels + ? { + ...(level ? { maxEffortLevel: level } : {}), + ...(modelMaxEffortLevels ? { modelMaxEffortLevels } : {}), + } + : undefined; +} + +// `sources` holds each settings file's raw settings. CLIs that report only the merged `effective` +// settings are read as a single source. +function parseClaudeEffortCapSources( + settings: { readonly effective?: unknown; readonly sources?: unknown } | undefined, +): ReadonlyArray | undefined { + const sources = Array.isArray(settings?.sources) + ? settings.sources.flatMap((source) => { + const parsed = parseClaudeEffortCapSource( + source && typeof source === "object" + ? (source as { readonly settings?: unknown }).settings + : undefined, + ); + return parsed ? [parsed] : []; + }) + : [parseClaudeEffortCapSource(settings?.effective)].filter((source) => source !== undefined); + return sources.length > 0 ? sources : undefined; +} + function parseClaudeInitializationCommands( commands: ReadonlyArray | undefined, ): ReadonlyArray { @@ -375,7 +491,7 @@ function claudeGatewayDiscoveryGraceMs(environment: Readonly()( "ClaudeCapabilitiesProbeSdkError", - { operation: Schema.Literals(["initialize", "usage"]), cause: Schema.Defect() }, + { operation: Schema.Literals(["initialize", "usage", "settings"]), cause: Schema.Defect() }, ) { override get message(): string { return `Claude capability probe ${this.operation} failed.`; @@ -387,7 +503,7 @@ const probeClaudeCapabilities = ( claudeSettings: ClaudeSettings, environment?: NodeJS.ProcessEnv, cwd?: string, - includeUsage = true, + includeStatus = true, ) => { const abort = new AbortController(); const abortProbe = Effect.sync(() => { @@ -401,12 +517,19 @@ const probeClaudeCapabilities = ( ); const managedMcpConfig = yield* hasClaudeManagedMcpConfig(); // Workspace probes (no usage) discard models; the machine probe refreshes the shared cache. - const graceMs = includeUsage + const graceMs = includeStatus ? claudeGatewayDiscoveryGraceMs({ ...claudeEnvironment, ...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)), }) : 0; + const platform = yield* HostProcess.Platform; + const spawnVia = + platform === "win32" + ? "launcher-thread" + : platform === "linux" && (yield* Effect.promise(supportsEnvChdir)) + ? "env" + : undefined; return yield* Effect.tryPromise({ try: async () => { const q = claudeQuery({ @@ -420,6 +543,7 @@ const probeClaudeCapabilities = ( environment: claudeEnvironment, cwd, managedMcpConfig, + spawnVia, }), }); const init = await q.initializationResult(); @@ -428,22 +552,39 @@ const probeClaudeCapabilities = ( catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "initialize", cause }), }); }).pipe( - Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS), + Effect.timeout( + resolveProviderProbeTimeoutMs("claude", CAPABILITIES_PROBE_TIMEOUT_MS, environment), + ), Effect.flatMap(({ q, init, graceMs }) => Effect.gen(function* () { // Usage has its own deadline so a slow optional request cannot discard initialization. // Only the rate limits are read, so skip the local transcript scan that fills // `behaviors`: with a few GB of transcripts it outlasts the deadline. + // The effort caps are read in parallel under the same deadline; workspace probes skip both. const usageCheckedAt = DateTime.formatIso(yield* DateTime.now); - const usageResult = includeUsage - ? yield* Effect.tryPromise({ - try: () => - q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ - skipBehaviors: true, - }), - catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "usage", cause }), - }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result) - : undefined; + const { getSettings } = q as ClaudeSettingsQuery; + const [usageResult, settingsResult] = yield* Effect.all( + [ + includeStatus + ? Effect.tryPromise({ + try: () => + q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ + skipBehaviors: true, + }), + catch: (cause) => + new ClaudeCapabilitiesProbeSdkError({ operation: "usage", cause }), + }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result) + : Effect.undefined, + includeStatus && getSettings + ? Effect.tryPromise({ + try: () => getSettings.call(q), + catch: (cause) => + new ClaudeCapabilitiesProbeSdkError({ operation: "settings", cause }), + }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result) + : Effect.undefined, + ], + { concurrency: "unbounded" }, + ); const usage = usageResult && Result.isSuccess(usageResult) ? { @@ -451,6 +592,9 @@ const probeClaudeCapabilities = ( rate_limits: usageResult.success.rate_limits, } : undefined; + const effortCapSources = parseClaudeEffortCapSources( + settingsResult && Result.isSuccess(settingsResult) ? settingsResult.success : undefined, + ); const account = init.account as | { readonly email?: string; @@ -469,6 +613,7 @@ const probeClaudeCapabilities = ( slashCommands: parseClaudeInitializationCommands(init.commands), ...(init.models?.length ? { models: init.models } : {}), ...(usage ? { usage, usageCheckedAt } : {}), + ...(effortCapSources ? { effortCapSources } : {}), } satisfies ClaudeCapabilitiesProbe; }).pipe( Effect.tap(() => @@ -576,7 +721,12 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( ["--version"], providerProbeEnvironment(resolvedEnvironment), cwd, - ).pipe(Effect.timeoutOption(CLAUDE_VERSION_CHECK_TIMEOUT_MS), Effect.result); + ).pipe( + Effect.timeoutOption( + resolveProviderProbeTimeoutMs("claude", CLAUDE_VERSION_CHECK_TIMEOUT_MS, resolvedEnvironment), + ), + Effect.result, + ); if (Result.isFailure(versionProbe)) { const error = versionProbe.failure; @@ -650,12 +800,16 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined; const probeFailure = probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined; - const models = claudeProviderModels( - [ - ...resolveClaudeModelsForVersion(modelCatalog, parsedVersion), - ...claudeReportedModels(modelCatalog, claudeSettings.customModels, capabilities?.models), - ], - claudeSettings.customModels, + const models = capClaudeCatalogEffort( + modelCatalog, + claudeProviderModels( + [ + ...resolveClaudeModelsForVersion(modelCatalog, parsedVersion), + ...claudeReportedModels(modelCatalog, claudeSettings.customModels, capabilities?.models), + ], + claudeSettings.customModels, + ), + capabilities?.effortCapSources ?? [], ); const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment); const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])]; @@ -677,7 +831,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( auth: { status: "unknown" }, message: probeFailure ? Cause.isTimeoutError(probeFailure) - ? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.` + ? `Timed out after ${resolveProviderProbeTimeoutMs("claude", CAPABILITIES_PROBE_TIMEOUT_MS, resolvedEnvironment) / 1_000}s while checking Claude account status.` : "Claude Agent CLI failed while checking account status." : "Could not verify Claude authentication status from initialization result.", }, @@ -689,6 +843,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( (yield* readClaudeSettingsEnv(claudeSettings, cwd, resolvedEnvironment)).ANTHROPIC_BASE_URL ?? resolvedEnvironment.ANTHROPIC_BASE_URL; const customApiEndpoint = customClaudeApiEndpointHost(baseUrl) !== undefined; + const endpoint = customApiEndpoint ? URL.parse(baseUrl?.trim() ?? "")?.origin : undefined; if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") { const path = yield* Path.Path; const configDir = (yield* makeClaudeEnvironment(claudeSettings, resolvedEnvironment)) @@ -734,10 +889,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( // A proxy's ANTHROPIC_AUTH_TOKEN reads as an API key; the endpoint is what the token is for. const authMetadata = apiProviderAuthMetadata(capabilities.apiProvider) ?? - (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined) ?? + (customApiEndpoint + ? { type: "customEndpoint", label: "Custom API endpoint", ...(endpoint ? { endpoint } : {}) } + : undefined) ?? claudeAuthMetadata({ subscriptionType, authMethod: capabilities.tokenSource, + apiKeySource: capabilities.apiKeySource, }); const usageCheckedAt = capabilities.usageCheckedAt ?? checkedAt; const usageLimits = !capabilities.usage diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index da04166e0b..f3b1214824 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -384,8 +384,8 @@ const makeHarnessFor = Effect.fnUntraced(function* ( setIdentityFailure: (value: "issuer" | "audience" | "signature") => { identityFailure = value; }, - mismatchCallbackState: () => { - mismatchedState = true; + mismatchCallbackState: (value = true) => { + mismatchedState = value; }, setCallbackClientId: (value: string) => { callbackClientId = value; @@ -854,16 +854,24 @@ it.effect( ), ); -it.effect("rejects mismatched callback state before any token exchange or credential write", () => +it.effect("rejects mismatched callback state and keeps waiting for the real redirect", () => provision( Effect.gen(function* () { const h = yield* makeHarness; h.mismatchCallbackState(); yield* h.signIn; - assert.include((yield* h.phase("failed")).message!, "could not be verified"); + assert.include(h.callbackResponses[0]!.body, "does not belong to the active sign-in"); assert.strictEqual(h.exchanges.length, 0); assert.deepEqual(h.storedRecords(), []); assert.isTrue(Option.isNone(yield* h.auth.read)); + h.mismatchCallbackState(false); + const waiting = yield* h.phase("waiting"); + const redirectUri = new URL(waiting.authorizationUrl!).searchParams.get("redirect_uri")!; + const unparsable = yield* Effect.promise(() => fetch(`${new URL(redirectUri).origin}//`)); + assert.strictEqual(unparsable.status, 404); + yield* h.finishCallback(waiting); + yield* h.phase("succeeded"); + assert.strictEqual(h.exchanges.length, 1); }), ), ); diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.ts index dcd4c87545..55a3809ebb 100644 --- a/apps/server/src/provider/CodexChatGptAuth.ts +++ b/apps/server/src/provider/CodexChatGptAuth.ts @@ -441,9 +441,10 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* Effect.tryPromise({ try: () => new Promise((resolve, reject) => { + const callbackBase = "http://127.0.0.1/auth/callback"; const server = NodeHttp.createServer((request, response) => { - const url = new URL(request.url ?? "/", "http://127.0.0.1"); - if (request.method !== "GET" || url.pathname !== "/auth/callback") { + const url = URL.parse(request.url ?? "/", callbackBase); + if (request.method !== "GET" || url?.pathname !== "/auth/callback") { response.writeHead(404).end(); return; } @@ -451,8 +452,18 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* response.writeHead(410).end("Sign-in is no longer active."); return; } + // Reject a stray request without ending the sign-in, so the real redirect still lands. + let returned: URL; + try { + returned = codexCallbackUrl(url.toString(), callbackBase, state); + } catch { + response + .writeHead(400) + .end("This response does not belong to the active sign-in."); + return; + } used = true; - callback.resolve({ url, response }); + callback.resolve({ url: returned, response }); }); server.once("error", reject); server.listen(0, "127.0.0.1", () => resolve(server)); diff --git a/apps/server/src/provider/CodexDeveloperInstructions.test.ts b/apps/server/src/provider/CodexDeveloperInstructions.test.ts index 289ce1860a..c5c58afc3c 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.test.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.test.ts @@ -32,19 +32,6 @@ describe("buildCodexAdditionalContext", () => { }); describe("Codex runtime context", () => { - it("describes Markdown media support in the runtime context in both modes", () => { - { - const instructions = runtimeInstructions({ - model: "gpt-5.3-codex", - reasoningEffort: "high", - }); - NodeAssert.match( - instructions, - /.*embed images, video, and audio.*Markdown image syntax with absolute file paths.*Link every other file you cite or produce by its absolute path.*files viewer.*<\/runtime_info>/, - ); - } - }); - it("flattens multiline metadata into single-line runtime info", () => { const instructions = runtimeInstructions({ model: "gpt\n5.3\ncodex", diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts index daf1dac265..f1c0edf0cf 100644 --- a/apps/server/src/provider/CodexInstallation.test.ts +++ b/apps/server/src/provider/CodexInstallation.test.ts @@ -41,6 +41,8 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( platform?: NodeJS.Platform; spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; runtimeRenameFailures?: number; + /** Served by URL instead of the pinned package. */ + responses?: Readonly Response>>; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -109,6 +111,8 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( HttpClient.make((request) => Effect.sync(() => { downloads++; + const respond = input.responses?.[request.url]; + if (respond) return HttpClientResponse.fromWeb(request, respond()); return Object.defineProperty( HttpClientResponse.fromWeb( request, @@ -528,4 +532,214 @@ it.effect("keeps an activated runtime when a later update fails verification", ( }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); -// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout. +const upstreamVersion = "0.163.0"; +const upstreamArchive = Buffer.from( + "H4sIAAAAAAACA+3WzY7CIBQF4D5Kw1oqtNQmPoh7rKStP9BQdMaYefcBE43T9RQ1nm8B7Q1Jk94cYN3peW026juZDvOqsrzO3nj2yofnUK9KwZKUJREcByet/2TymabuPby29S3/NIz0EIbWDC5u/sXf/PO8EAL5j+G/ew1vuP/TXrp2bpunnf/5KP+syCvkP4bJmg5vlf96JxuVbQej4+efi2qUf17g/h/Hhezl2RzdStmhM5osUz5Lyen+RljGF0XGiK/6H9UoF4pS2rpdCCr7fq/oRtqvTocVSjt77k2nr6vud0vyg6ABAAAAAAAAAAAAAABE8gvVbjvaACgAAA==", + "base64", +); +const upstreamReleaseUrl = `https://github.com/openai/codex/releases/download/rust-v${upstreamVersion}`; +const upstreamResponses = (checksum: string) => ({ + "https://registry.npmjs.org/@openai/codex/latest": () => + Response.json({ version: upstreamVersion }), + [`${upstreamReleaseUrl}/codex-package_SHA256SUMS`]: () => + new Response( + `${"0".repeat(64)} codex-package-x86_64-apple-darwin.tar.gz\n${checksum} codex-package-aarch64-apple-darwin.tar.gz\n`, + ), + [`${upstreamReleaseUrl}/codex-package-aarch64-apple-darwin.tar.gz`]: () => + new Response(upstreamArchive), +}); + +it.effect("updates a managed install to OpenAI's newest release and never downgrades it", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + const h = yield* makeHarness({ responses: upstreamResponses(checksum) }); + yield* h.installation.checkForUpdate; + // A fresh install still gets the pinned release. + expect((yield* h.installation.state).version).toBe("0.156.1"); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: upstreamVersion, + }); + + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: upstreamVersion, + version: upstreamVersion, + }); + expect((yield* h.installation.resolve()).version).toBe(upstreamVersion); + + // Without upstream information the older pin is not offered as a reinstall. + const restarted = yield* makeHarness({ baseDir: h.baseDir }); + expect(yield* restarted.installation.state).toMatchObject({ + installedVersion: upstreamVersion, + version: upstreamVersion, + }); + yield* restarted.installation.start; + expect(yield* terminalState(restarted.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: upstreamVersion, + }); + expect(restarted.downloads()).toBe(0); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("keeps the managed install when an update fails its published checksum", () => + Effect.gen(function* () { + const h = yield* makeHarness({ responses: upstreamResponses("f".repeat(64)) }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "failed", + installedVersion: "0.156.1", + message: expect.stringContaining("SHA-256"), + }); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("does not install a cached update the manifest has since withdrawn", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + expect((yield* h.installation.state).version).toBe(upstreamVersion); + manifest = { + ...manifest, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + const downloads = h.downloads(); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: "0.156.1", + }); + expect(h.downloads()).toBe(downloads); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("returns a managed install the manifest withdraws to the pinned release", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + }); + yield* h.installation.checkForUpdate; + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + installedVersion: upstreamVersion, + }); + + manifest = { + ...manifest, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + yield* h.installation.checkForUpdate; + expect(yield* h.installation.state).toMatchObject({ + installedVersion: upstreamVersion, + version: "0.156.1", + }); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: "0.156.1", + }); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect.each(["update", "reinstall"] as const)( + "rejects withdrawal during $0 validation", + (operation) => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + let withdraw = operation === "update"; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + options: { + validate: (_executable, version) => + Effect.sync(() => { + if (withdraw && version === upstreamVersion) + manifest = { + ...ModelManifest.BUNDLED_MODEL_MANIFEST, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + }), + }, + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + if (operation === "reinstall") { + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("succeeded"); + withdraw = true; + } + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("failed"); + if (operation === "update") { + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + } else { + expect((yield* h.installation.state).version).toBe("0.156.1"); + yield* Effect.flip(h.installation.resolve()); + } + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.ts index 44ed9fd458..a8e4828ee2 100644 --- a/apps/server/src/provider/CodexInstallation.ts +++ b/apps/server/src/provider/CodexInstallation.ts @@ -4,7 +4,7 @@ import { type ProviderInstallState, type ServerProviderCompatibilityAdvisory, } from "@t3tools/contracts"; -import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease"; +import { cliArchiveTarCommand, parseChecksums } from "@t3tools/shared/cliRelease"; import { compareSemverVersions } from "@t3tools/shared/semver"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; @@ -29,11 +29,18 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as NodeCrypto from "node:crypto"; import * as ServerConfig from "../config.ts"; +import { selectManagedRelease } from "./managedRelease.ts"; import * as ModelManifest from "./ModelManifest.ts"; import { resolveProviderCompatibility } from "./providerCompatibility.ts"; const DRIVER = ProviderDriverKind.make("codex"); const STAGING_STALE_AFTER_MS = 24 * 60 * 60_000; +const UPDATE_CHECK_INTERVAL_MS = 60 * 60_000; +const UPDATE_CHECK_TIMEOUT = "20 seconds"; +const UPSTREAM_LATEST_URL = "https://registry.npmjs.org/@openai/codex/latest"; +const UPSTREAM_RELEASES_URL = "https://github.com/openai/codex/releases/download"; +// An upstream release has no recorded size; current packages are about 160 MB. +const UPSTREAM_MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024; const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u)); const ActiveRelease = Schema.Struct({ version: Version }); const InstalledRelease = Schema.Struct({ @@ -48,6 +55,7 @@ const PackageManifest = Schema.Struct({ entrypoint: Schema.String, }); const decodeVersion = Schema.decodeUnknownEffect(Version); +const decodeNpmLatest = Schema.decodeUnknownEffect(Schema.Struct({ version: Version })); const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease)); const encodeActive = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease)); export interface CodexReleaseAsset { @@ -55,7 +63,8 @@ export interface CodexReleaseAsset { readonly target: string; readonly url: string; readonly sha256: string; - readonly archiveBytes: number; + /** Null for an upstream release, whose package checksum is published without a size. */ + readonly archiveBytes: number | null; } const RELEASES: Readonly> = { "darwin-arm64": { @@ -139,6 +148,11 @@ interface CodexInstallationService { ) => Effect.Effect; readonly state: Effect.Effect; readonly changes: Stream.Stream; + /** + * Looks up OpenAI's newest Codex release, at most hourly, and offers it + * through `state.version` when it is newer than the managed install. + */ + readonly checkForUpdate: Effect.Effect; readonly remove: ( protectedBinaryPaths?: ReadonlyArray, ) => Effect.Effect; @@ -186,15 +200,31 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const activePath = path.join(managedDirectory, "active.json"); const executableName = platform === "win32" ? "codex.exe" : "codex"; const gate = yield* Semaphore.make(1); + const updateCheckGate = yield* Semaphore.make(1); let leases = 0; let running: { readonly operationId: string; readonly fiber: Fiber.Fiber } | undefined; + let upstream: CodexReleaseAsset | null = null; + let upstreamCheckedAt: number | null = null; + + // A local Codex is used as is, so only a managed install is ever updated. + const managedVersion = (current: ProviderInstallState) => + current.source === "managed" ? current.installedVersion : null; + // What `start` installs next. Clients compare `version` with + // `installedVersion` to offer an update. + const offer = (installedVersion: string | null) => { + const release = selectManagedRelease(installedVersion, asset, upstream); + return { + version: release?.version ?? installedVersion, + totalBytes: release?.archiveBytes ?? null, + }; + }; + const state = yield* SubscriptionRef.make({ driver: DRIVER, operationId: null, phase: "idle", downloadedBytes: 0, - totalBytes: asset?.archiveBytes ?? null, - version: asset?.version ?? null, + ...offer(null), installedVersion: null, executablePath: null, canRemove: false, @@ -279,6 +309,70 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ) ); }); + const isSupported = (version: string) => + compatibility(version).pipe(Effect.map((advisory) => advisory?.status === "supported")); + // Forgets what the manifest withdrew after it was seen. Managed resolution + // refuses a withdrawn install, so the pin replaces it rather than a re-check. + const keptInstall = Effect.fn("CodexInstallation.keptInstall")(function* ( + installedVersion: string | null, + ) { + if (upstream && !(yield* isSupported(upstream.version))) upstream = null; + return installedVersion !== null && (yield* isSupported(installedVersion)) + ? installedVersion + : null; + }); + // npm names the latest stable release; its GitHub release lists the package + // checksums, so an upstream update stays SHA-256 verified. + const lookupUpstream = Effect.gen(function* () { + if (!asset) return null; + const latest = yield* http + .execute(HttpClientRequest.get(UPSTREAM_LATEST_URL)) + .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + const { version } = yield* latest.json.pipe(Effect.flatMap(decodeNpmLatest)); + // Managed resolution refuses anything else, so offering it would break sessions. + if (!(yield* isSupported(version))) return null; + const releaseUrl = `${UPSTREAM_RELEASES_URL}/rust-v${version}`; + const checksums = yield* http + .execute(HttpClientRequest.get(`${releaseUrl}/codex-package_SHA256SUMS`)) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.text), + ); + const fileName = `codex-package-${asset.target}.tar.gz`; + const sha256 = parseChecksums(checksums).get(fileName); + if (!sha256) return null; + return { + version, + target: asset.target, + url: `${releaseUrl}/${fileName}`, + sha256, + archiveBytes: null, + } satisfies CodexReleaseAsset; + }); + // A check already in flight covers concurrent subscribers, including when it fails. + const checkForUpdate = updateCheckGate + .withPermitsIfAvailable(1)( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (upstreamCheckedAt === null || now - upstreamCheckedAt >= UPDATE_CHECK_INTERVAL_MS) { + // A failed lookup counts too, and keeps whatever release was offered before. + upstreamCheckedAt = now; + upstream = yield* lookupUpstream.pipe( + Effect.timeout(UPDATE_CHECK_TIMEOUT), + Effect.orElseSucceed(() => upstream), + ); + } + // A running install already published the release it is installing. + yield* SubscriptionRef.updateEffect(state, (current) => + isRunning(current) + ? Effect.succeed(current) + : keptInstall(managedVersion(current)).pipe( + Effect.map((kept) => ({ ...current, ...offer(kept) })), + ), + ); + }), + ) + .pipe(Effect.ignore); const resolveManaged = Effect.fn("CodexInstallation.resolveManaged")( function* () { const active = yield* readRecord(activePath, ActiveRelease); @@ -464,6 +558,14 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ); const install = Effect.fn("CodexInstallation.install")( function* (release: CodexReleaseAsset) { + const ensureEligible = Effect.fn("CodexInstallation.ensureEligible")(function* () { + if (release.version !== asset?.version && !(yield* isSupported(release.version))) { + return yield* installationError( + "verify", + "This Codex release was withdrawn. Check for updates and try again.", + ); + } + }); yield* decodeVersion(release.version); yield* fs.makeDirectory(managedDirectory, { recursive: true }); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true })); @@ -480,12 +582,14 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function mode: 0o600, flag: "wx", }); + yield* ensureEligible(); yield* fs.rename(pointer, activePath); yield* SubscriptionRef.update( state, (current) => ({ ...current, + ...offer(release.version), phase: "succeeded", source: "managed", installedVersion: release.version, @@ -508,6 +612,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function "verify", "The existing managed Codex release differs from the official package. Remove it and reinstall.", ); + yield* ensureEligible(); yield* validate(existing, release.version).pipe( Effect.scoped, Effect.timeout("90 seconds"), @@ -523,6 +628,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const runtime = path.join(staging, "runtime"); yield* fs.makeDirectory(runtime); const hash = NodeCrypto.createHash("sha256"); + const maxArchiveBytes = release.archiveBytes ?? UPSTREAM_MAX_ARCHIVE_BYTES; let downloadedBytes = 0; let lastProgressAt = yield* Clock.currentTimeMillis; const response = yield* http @@ -532,7 +638,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function Stream.tap((chunk) => Effect.gen(function* () { downloadedBytes += chunk.byteLength; - if (downloadedBytes > release.archiveBytes) + if (downloadedBytes > maxArchiveBytes) return yield* installationError( "download", "The Codex download exceeded the expected release size.", @@ -556,7 +662,10 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ), }), ); - if (downloadedBytes !== release.archiveBytes || hash.digest("hex") !== release.sha256) + if ( + (release.archiveBytes !== null && downloadedBytes !== release.archiveBytes) || + hash.digest("hex") !== release.sha256 + ) return yield* installationError( "download", "The Codex download failed its size or SHA-256 check. Nothing was installed.", @@ -600,6 +709,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }) satisfies ProviderInstallState, ); const executable = yield* fromDirectory(runtime, release.version, release.target); + yield* ensureEligible(); yield* validate(executable, release.version).pipe( Effect.scoped, Effect.timeout("90 seconds"), @@ -642,13 +752,54 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ), ), ); + // Nothing newer is known, so "reinstall" re-checks the active runtime rather + // than replacing it with an older pinned release. + const reverify = Effect.fn("CodexInstallation.reverify")( + function* () { + const active = yield* readRecord(activePath, ActiveRelease); + const executable = yield* completedRelease(active.version); + yield* validate(executable, executable.version).pipe( + Effect.scoped, + Effect.timeout("90 seconds"), + ); + const kept = yield* keptInstall(executable.version); + if (kept === null) { + yield* SubscriptionRef.update(state, (current) => ({ ...current, ...offer(kept) })); + return yield* installationError( + "verify", + "This Codex release was withdrawn. Check for updates and try again.", + ); + } + yield* SubscriptionRef.update( + state, + (current) => + ({ + ...current, + ...offer(kept), + phase: "succeeded", + source: "managed", + installedVersion: executable.version, + executablePath: executable.executablePath, + message: null, + }) satisfies ProviderInstallState, + ); + }, + Effect.mapError( + wrapFailure( + "verify", + "The installed Codex runtime could not start. Remove it and reinstall.", + ), + ), + ); const start = gate .withPermit( Effect.gen(function* () { const current = yield* SubscriptionRef.get(state); if (isRunning(current)) return current; if (yield* reuseLocal()) return yield* SubscriptionRef.get(state); - if (!asset) { + const installedVersion = yield* keptInstall(managedVersion(current)); + const release = selectManagedRelease(installedVersion, asset, upstream); + if (!release && installedVersion === null) { return yield* installationError( "start", `OpenAI does not publish a Codex runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`, @@ -658,14 +809,13 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const next: ProviderInstallState = { ...current, operationId, - phase: "downloading", + phase: release ? "downloading" : "verifying", downloadedBytes: 0, - totalBytes: asset.archiveBytes, - version: asset.version, - message: "Downloading Codex.", + ...offer(installedVersion), + message: release ? "Downloading Codex." : "Checking Codex.", }; yield* SubscriptionRef.set(state, next); - const work = install(asset).pipe( + const work = (release ? install(release) : reverify()).pipe( Effect.onExit((exit) => Exit.isFailure(exit) ? SubscriptionRef.update(state, (value) => { @@ -745,6 +895,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function (current) => ({ ...current, + ...offer(null), operationId: null, phase: "idle", downloadedBytes: 0, @@ -796,11 +947,13 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function if (!(yield* fs.exists(activePath))) return; const active = yield* readRecord(activePath, ActiveRelease); const installed = yield* completedRelease(active.version); + const kept = yield* keptInstall(installed.version); yield* SubscriptionRef.update( state, (current) => ({ ...current, + ...offer(kept), installedVersion: installed.version, executablePath: installed.executablePath, source: "managed", @@ -832,6 +985,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function cancel, state: SubscriptionRef.get(state), changes: SubscriptionRef.changes(state), + checkForUpdate, remove, }); }); diff --git a/apps/server/src/provider/CodexMcpElicitation.test.ts b/apps/server/src/provider/CodexMcpElicitation.test.ts index 66dd7ddb6e..60a4b7fe8f 100644 --- a/apps/server/src/provider/CodexMcpElicitation.test.ts +++ b/apps/server/src/provider/CodexMcpElicitation.test.ts @@ -146,7 +146,7 @@ describe("Codex MCP elicitation approvals", () => { } satisfies EffectCodexSchema.McpServerElicitationRequestParams; NodeAssert.deepStrictEqual(toMcpElicitationResponse(inputRequest, "accept"), { - action: "decline", + action: "cancel", }); }); @@ -162,7 +162,7 @@ describe("Codex MCP elicitation approvals", () => { } satisfies EffectCodexSchema.McpServerElicitationRequestParams; NodeAssert.deepStrictEqual(toMcpElicitationResponse(urlRequest, "accept"), { - action: "decline", + action: "cancel", }); }); diff --git a/apps/server/src/provider/CodexMcpElicitation.ts b/apps/server/src/provider/CodexMcpElicitation.ts index eafe09e07e..c8362dad1e 100644 --- a/apps/server/src/provider/CodexMcpElicitation.ts +++ b/apps/server/src/provider/CodexMcpElicitation.ts @@ -185,8 +185,10 @@ export function toMcpElicitationResponse( return { action: decision }; } + // T3 cannot answer these itself. `decline` reads as the user's refusal, and Codex's browser + // plugin saves it as a thread-wide site denial; `cancel` leaves no saved decision. if (payload.mode === "url") { - return { action: "decline" }; + return { action: "cancel" }; } const persist = @@ -217,7 +219,7 @@ export function toMcpElicitationResponse( } if (form?.required?.some((key) => !Object.hasOwn(content, key))) { - return { action: "decline" }; + return { action: "cancel" }; } return { diff --git a/apps/server/src/provider/CodexProvider.test.ts b/apps/server/src/provider/CodexProvider.test.ts index 30f63b21f3..a70ea15a73 100644 --- a/apps/server/src/provider/CodexProvider.test.ts +++ b/apps/server/src/provider/CodexProvider.test.ts @@ -1,6 +1,149 @@ import { assert, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Queue from "effect/Queue"; +import * as Scope from "effect/Scope"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as TestClock from "effect/testing/TestClock"; +import * as HostProcess from "@t3tools/shared/HostProcess"; -import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts"; +import { + applyPreferredCodexDefaultModel, + codexCustomEndpoint, + codexRoutesSpendNativeQuota, + makeCodexSkillsProbe, + mapCodexModelCapabilities, +} from "./CodexProvider.ts"; + +function makeFakeCodexAppServers() { + const helpers: Array<{ + readonly codexHome: unknown; + readonly crash: Effect.Effect; + readonly requests: Array; + closed: boolean; + }> = []; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const output = yield* Queue.unbounded(); + const exited = yield* Deferred.make(); + const crash = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(1)).pipe( + Effect.andThen(Queue.end(output)), + Effect.asVoid, + ); + const helper = { + codexHome: command._tag === "StandardCommand" ? command.options.env?.CODEX_HOME : undefined, + crash, + requests: [] as Array, + closed: false, + }; + helpers.push(helper); + yield* Effect.addFinalizer(() => Effect.sync(() => (helper.closed = true))); + const respond = (id: unknown, result: unknown) => + Queue.offer(output, new TextEncoder().encode(`${JSON.stringify({ id, result })}\n`)); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(900_000_000 + helpers.length), + exitCode: Deferred.await(exited), + isRunning: Effect.map(Deferred.isDone(exited), (done) => !done), + kill: () => crash, + unref: Effect.succeed(Effect.void), + stdin: Sink.forEach((chunk: string | Uint8Array) => + Effect.forEach( + (typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk)) + .split("\n") + .filter(Boolean), + (line) => { + const frame = JSON.parse(line) as { + readonly id?: number; + readonly method: string; + readonly params?: { readonly cwds: ReadonlyArray }; + }; + if (frame.id === undefined) return Effect.void; + if (frame.method === "initialize") { + return respond(frame.id, { + codexHome: "/codex-home", + platformFamily: "unix", + platformOs: "linux", + userAgent: "codex/0.0.0", + }); + } + helper.requests.push(frame.params); + return respond(frame.id, { + data: (frame.params?.cwds ?? []).map((cwd) => ({ + cwd, + errors: [], + skills: [ + { + name: `skill-in-${cwd}`, + path: `${cwd}/SKILL.md`, + enabled: true, + description: "", + scope: "repo", + }, + ], + })), + }); + }, + { discard: true }, + ), + ), + stdout: Stream.fromQueue(output), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + }), + ); + return { helpers, spawner }; +} + +it.effect("reuses one Codex skills helper per launch until it idles out", () => + Effect.gen(function* () { + const { helpers, spawner } = makeFakeCodexAppServers(); + const providerScope = yield* Scope.make(); + const probe = yield* makeCodexSkillsProbe().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Scope.provide(providerScope), + ); + const read = (cwd: string, homePath = "/home-a") => + probe({ binaryPath: "codex", homePath, cwd, environment: {} }).pipe( + Effect.map((skills) => skills.map((skill) => skill.name)), + ); + + assert.deepStrictEqual(yield* read("/alpha"), ["skill-in-/alpha"]); + assert.deepStrictEqual(yield* read("/beta"), ["skill-in-/beta"]); + assert.strictEqual(helpers.length, 1); + assert.deepStrictEqual(helpers[0]!.requests, [ + { cwds: ["/alpha"], forceReload: true }, + { cwds: ["/beta"], forceReload: true }, + ]); + + // Another home is another launch identity; the previous helper retires at once. + assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]); + assert.strictEqual(helpers.length, 2); + assert.strictEqual(helpers[0]!.closed, true); + assert.strictEqual(helpers[1]!.codexHome, "/home-b"); + + // A helper that exits is replaced within the same read. + yield* helpers[1]!.crash; + assert.deepStrictEqual(yield* read("/beta", "/home-b"), ["skill-in-/beta"]); + assert.strictEqual(helpers.length, 3); + + yield* TestClock.adjust("29 seconds"); + assert.strictEqual(helpers[2]!.closed, false); + yield* TestClock.adjust("1 second"); + assert.strictEqual(helpers[2]!.closed, true); + assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]); + assert.strictEqual(helpers.length, 4); + + yield* Scope.close(providerScope, Exit.void); + assert.strictEqual(helpers[3]!.closed, true); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), +); it("maps current Codex model capability fields", () => { const capabilities = mapCodexModelCapabilities({ @@ -12,6 +155,7 @@ it("maps current Codex model capability fields", () => { id: "gpt-test", isDefault: true, model: "gpt-test", + availableAccessPrograms: { cyber: ["standard", "daybreakBlue"] }, defaultServiceTier: "flex", serviceTiers: [ { @@ -61,6 +205,16 @@ it("maps current Codex model capability fields", () => { ], currentValue: "flex", }, + { + id: "cyberAccessProgram", + label: "Cyber Access", + type: "select", + options: [ + { id: "standard", label: "Standard", isDefault: true }, + { id: "daybreakBlue", label: "Daybreak Blue" }, + ], + currentValue: "standard", + }, ]); }); @@ -153,3 +307,36 @@ it("ignores custom models that shadow a preferred slug", () => { assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4"); }); + +it("reports native quota only for an OpenAI login on a native route", () => { + const chatgpt = { type: "chatgpt", email: "a@example.com", planType: "pro" } as const; + const hub = { + model_provider: "hub", + model_providers: { hub: { base_url: "https://hub.example.com/v1" } }, + }; + const cases = [ + ["default route", chatgpt, true, {}, true], + ["openai base url", chatgpt, true, { openai_base_url: "https://chatgpt.com/x" }, true], + ["openai proxy url", chatgpt, true, { openai_base_url: "https://proxy.example.com" }, false], + ["custom provider", chatgpt, true, hub, false], + ["unknown provider id", chatgpt, true, { model_provider: "missing" }, false], + ["unreadable config", chatgpt, true, null, false], + ["login not required", chatgpt, false, {}, false], + ["api key", { type: "apiKey" }, true, {}, false], + ] as const; + for (const [name, account, requiresOpenaiAuth, config, expected] of cases) { + assert.strictEqual( + codexRoutesSpendNativeQuota({ account, requiresOpenaiAuth }, config), + expected, + name, + ); + } + // The custom endpoint is what a usage-limit hub is matched against. + assert.strictEqual(codexCustomEndpoint(hub), "https://hub.example.com"); + assert.strictEqual( + codexCustomEndpoint({ openai_base_url: "http://127.0.0.1:8317/v1" }), + "http://127.0.0.1:8317", + ); + assert.strictEqual(codexCustomEndpoint({ openai_base_url: "https://chatgpt.com/x" }), undefined); + assert.strictEqual(codexCustomEndpoint({}), undefined); +}); diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index 868d2fb172..b9fbb22198 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -1,11 +1,15 @@ +import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { pipe } from "effect/Function"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as RcMap from "effect/RcMap"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Schedule from "effect/Schedule"; @@ -56,7 +60,6 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import packageJson from "../../package.json" with { type: "json" }; const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError); -const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000; type CodexRateLimitsProbe = | { @@ -70,6 +73,69 @@ type CodexRateLimitsProbe = } | { readonly failure: string }; +const CodexRoutingConfig = Schema.Struct({ + model_provider: Schema.optionalKey(Schema.NullOr(Schema.String)), + openai_base_url: Schema.optionalKey(Schema.NullOr(Schema.String)), + model_providers: Schema.optionalKey( + Schema.Record( + Schema.String, + Schema.Struct({ base_url: Schema.optionalKey(Schema.NullOr(Schema.String)) }), + ), + ), +}); +const decodeCodexRoutingConfig = Schema.decodeUnknownOption(CodexRoutingConfig); + +const CodexCyberAccessConfig = Schema.Struct({ + daybreak: Schema.optionalKey(Schema.NullOr(Schema.Boolean)), + features: Schema.optionalKey( + Schema.NullOr( + Schema.Struct({ + api_key_cyber_access_programs: Schema.optionalKey(Schema.NullOr(Schema.Boolean)), + }), + ), + ), +}); +const decodeCodexCyberAccessConfig = Schema.decodeUnknownOption(CodexCyberAccessConfig); + +// Null is Codex's auth-dependent OpenAI default; undefined is a route that cannot be read. +function codexRouteBaseUrl(config: unknown): string | null | undefined { + const decoded = decodeCodexRoutingConfig(config); + if (Option.isNone(decoded)) return undefined; + const routing = decoded.value; + const providerId = routing.model_provider ?? "openai"; + if (providerId === "openai") return routing.openai_base_url || null; + const provider = routing.model_providers?.[providerId]; + return provider ? (provider.base_url ?? null) : undefined; +} + +function routesToNativeOpenai(config: unknown): boolean { + const baseUrl = codexRouteBaseUrl(config); + if (baseUrl === undefined) return false; + if (baseUrl === null) return true; + if (!URL.canParse(baseUrl)) return false; + const url = new URL(baseUrl); + return ( + url.protocol === "https:" && + (url.hostname === "api.openai.com" || url.hostname === "chatgpt.com") + ); +} + +/** The origin of the custom endpoint Codex sends model requests to, if it uses one. */ +export function codexCustomEndpoint(config: unknown): string | undefined { + const baseUrl = codexRouteBaseUrl(config); + const url = baseUrl ? URL.parse(baseUrl) : null; + return url && /^https?:$/.test(url.protocol) && !routesToNativeOpenai(config) + ? url.origin + : undefined; +} + +// A stored login does not mean this provider's traffic spends that login's quota. +export const codexRoutesSpendNativeQuota = ( + account: CodexSchema.V2GetAccountResponse, + config: unknown, +): boolean => + account.requiresOpenaiAuth && account.account?.type !== "apiKey" && routesToNativeOpenai(config); + const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const; const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000; const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000; @@ -90,10 +156,15 @@ const CODEX_PRESENTATION = { export interface CodexAppServerProviderSnapshot { readonly account: CodexSchema.V2GetAccountResponse; + readonly endpoint?: string | undefined; + readonly nativeUsage?: boolean; readonly rateLimits?: CodexRateLimitsProbe; readonly version: string | undefined; readonly models: ReadonlyArray | undefined; readonly serviceTier?: string | undefined; + /** Undefined when `config/read` failed, so T3 cannot know Codex's default program. */ + readonly daybreakEnabled?: boolean | undefined; + readonly cyberAccessProgramsUnavailable?: boolean | undefined; readonly skills: ReadonlyArray; } @@ -114,6 +185,12 @@ const SERVICE_TIER_DESCRIPTIONS: Readonly> = { ultrafast: "Even faster, more expensive", }; +const CYBER_ACCESS_PROGRAM_LABELS: Readonly> = { + standard: "Standard", + daybreakBlue: "Daybreak Blue", + daybreakRed: "Daybreak Red", +}; + function reasoningEffortLabel(reasoningEffort: string): string { return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort; } @@ -242,6 +319,25 @@ export function mapCodexModelCapabilities( currentValue: defaultServiceTier, }); } + const cyberAccessPrograms = model.availableAccessPrograms?.cyber ?? []; + if (cyberAccessPrograms.length > 0) { + const hasStandard = cyberAccessPrograms.includes("standard"); + const defaultProgram = hasStandard ? "standard" : cyberAccessPrograms[0]; + optionDescriptors.push({ + id: "cyberAccessProgram", + label: "Cyber Access", + type: "select", + // Standard stays selectable as an opt-out; Codex rejects it visibly when the login cannot use it. + options: (hasStandard ? cyberAccessPrograms : ["standard", ...cyberAccessPrograms]).map( + (program) => ({ + id: program, + label: CYBER_ACCESS_PROGRAM_LABELS[program] ?? program, + ...(program === defaultProgram ? { isDefault: true } : {}), + }), + ), + ...(defaultProgram === undefined ? {} : { currentValue: defaultProgram }), + }); + } return createModelCapabilities({ optionDescriptors, @@ -281,37 +377,95 @@ export function applyPreferredCodexDefaultModel( }); } -function applyConfiguredCodexServiceTier( +function mapCodexOptionDescriptors( models: ReadonlyArray, - serviceTier: string | undefined, + update: ( + descriptors: ReadonlyArray, + model: ServerProviderModel, + ) => ReadonlyArray, ): ReadonlyArray { - if (!serviceTier) return models; return models.map((model) => { if (!model.capabilities?.optionDescriptors) return model; return { ...model, capabilities: { ...model.capabilities, - optionDescriptors: model.capabilities.optionDescriptors.map((descriptor) => { - if (descriptor.id !== "serviceTier" || descriptor.type !== "select") return descriptor; - const value = descriptor.options.find( - (option) => - option.id === serviceTier || (serviceTier === "fast" && option.id === "priority"), - )?.id; - if (!value) return descriptor; - return { - ...descriptor, - currentValue: value, - options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => - option.id === value ? { ...option, isDefault: true } : option, - ), - }; - }), + optionDescriptors: update(model.capabilities.optionDescriptors, model), }, }; }); } +function withConfiguredSelectDefault( + models: ReadonlyArray, + descriptorId: string, + pick: (options: ReadonlyArray<{ readonly id: string }>) => string | undefined, +): ReadonlyArray { + return mapCodexOptionDescriptors(models, (descriptors) => + descriptors.map((descriptor) => { + if (descriptor.id !== descriptorId || descriptor.type !== "select") return descriptor; + const value = pick(descriptor.options); + if (!value) return descriptor; + return { + ...descriptor, + currentValue: value, + options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => + option.id === value ? { ...option, isDefault: true } : option, + ), + }; + }), + ); +} + +function applyConfiguredCodexServiceTier( + models: ReadonlyArray, + serviceTier: string | undefined, +): ReadonlyArray { + if (!serviceTier) return models; + return withConfiguredSelectDefault( + models, + "serviceTier", + (options) => + options.find( + (option) => + option.id === serviceTier || (serviceTier === "fast" && option.id === "priority"), + )?.id, + ); +} + +/** Mirrors Codex: `daybreak = true` prefers a Daybreak program, Blue before Red. */ +function applyConfiguredCodexCyberAccess( + models: ReadonlyArray, + snapshot: Pick< + CodexAppServerProviderSnapshot, + "daybreakEnabled" | "cyberAccessProgramsUnavailable" + >, +): ReadonlyArray { + // Without a descriptor no turn sends a program; without a default only an explicit choice goes. + const offered = mapCodexOptionDescriptors(models, (descriptors, model) => + descriptors.flatMap((descriptor): ReadonlyArray => { + if (descriptor.id !== "cyberAccessProgram" || descriptor.type !== "select") { + return [descriptor]; + } + if (model.isCustom || snapshot.cyberAccessProgramsUnavailable === true) return []; + if (snapshot.daybreakEnabled !== undefined) return [descriptor]; + const { currentValue: _currentValue, ...withoutDefault } = descriptor; + return [ + { + ...withoutDefault, + options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => option), + }, + ]; + }), + ); + if (snapshot.daybreakEnabled !== true) return offered; + return withConfiguredSelectDefault(offered, "cyberAccessProgram", (options) => + ["daybreakBlue", "daybreakRed"].find((program) => + options.some((option) => option.id === program), + ), + ); +} + /** * Codex has no static default capability set, so a bare custom slug borrows * the first built-in's descriptors; an entry with its own capabilities keeps @@ -523,10 +677,57 @@ export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(fu ); const initialize = yield* client.request("initialize", buildCodexInitializeParams()); yield* client.notify("initialized", undefined); - return { client, initialize }; + return { client, initialize, pid: child.pid }; }); +// Codex runs git (ssh for ssh URLs) for plugin marketplaces at launch and exits without waiting +// for it, so stopping a short probe mid-fetch strands ssh in an SSH-agent request. +const CODEX_STARTUP_WORK_GRACE = Duration.minutes(1); + +const codexProcessGroupIsBusy = Effect.fn("codexProcessGroupIsBusy")( + function* (pid: number) { + const { stdout } = yield* spawnAndCollect( + "pgrep", + ChildProcess.make("pgrep", ["-g", `${pid}`]), + ); + return stdout.split("\n").some((line) => line.trim() !== "" && Number(line) !== pid); + }, + Effect.orElseSucceed(() => false), +); + +const stopCodexAfterStartupWork = (pid: number, processScope: Scope.Closeable) => + codexProcessGroupIsBusy(pid).pipe( + Effect.repeat({ schedule: Schedule.spaced("500 millis"), while: (busy) => busy }), + Effect.timeoutOption(CODEX_STARTUP_WORK_GRACE), + Effect.ensuring(Scope.close(processScope, Exit.void)), + ); + +// Usage is an enrichment: a failure or a slow answer degrades to "no usage this +// probe" rather than costing the account and models. +const readCodexRateLimits = ( + client: CodexClient.CodexAppServerClient["Service"], + deadlineMs: number, +) => + withCodexDiscoveryDeadline(client.request("account/rateLimits/read", null), deadlineMs).pipe( + Effect.map((response): CodexRateLimitsProbe => + response + ? { + snapshot: response.rateLimits, + rateLimitsByLimitId: response.rateLimitsByLimitId, + resetCredits: response.rateLimitResetCredits, + accountId: response.accountId, + } + : { failure: "Codex did not answer the usage request." }, + ), + Effect.catch((error) => + Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe( + Effect.as({ failure: codexRateLimitsFailureMessage(error) }), + ), + ), + ); + const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: { + readonly probeTimeoutMs: number; readonly binaryPath: string; readonly homePath?: string; readonly launchArgs?: string; @@ -535,7 +736,22 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun readonly skipNativeUsage?: boolean; }) { const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now); - const { client, initialize } = yield* withCodexAppServerClient(input); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const processScope = yield* Scope.make(); + let pid: number | undefined; + // Returning the snapshot must not wait for Codex's own startup work. + yield* Effect.addFinalizer(() => + pid === undefined + ? Scope.close(processScope, Exit.void) + : stopCodexAfterStartupWork(pid, processScope).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.forkDetach, + Effect.asVoid, + ), + ); + const opened = yield* withCodexAppServerClient(input).pipe(Scope.provide(processScope)); + pid = opened.pid; + const { client, initialize } = opened; const versionMatch = initialize.userAgent.match(/\/([^\s]+)/); const version = versionMatch ? versionMatch[1] : undefined; @@ -551,8 +767,8 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun } // Optional discovery must finish before the outer timeout can discard the account result. - const deadlineMs = spawnedAtMs + CODEX_AUTH_PROBE_TIMEOUT_MS - CODEX_DISCOVERY_MARGIN_MS; - const [skillsResponse, models, serviceTier, rateLimits] = yield* Effect.all( + const deadlineMs = spawnedAtMs + input.probeTimeoutMs - CODEX_DISCOVERY_MARGIN_MS; + const [skillsResponse, models, { config, nativeUsage, rateLimits }] = yield* Effect.all( [ withCodexDiscoveryDeadline(client.request("skills/list", { cwds: [input.cwd] }), deadlineMs), accountResponse.account?.type === "chatgpt" @@ -569,44 +785,43 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun deadlineMs, CODEX_CONFIG_PROBE_TIMEOUT_MS, ).pipe( - Effect.map((response) => response?.config.service_tier ?? undefined), Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined))), + Effect.flatMap((config) => { + // Only a confirmed native route may probe or publish the login's quota. + const nativeUsage = + !input.skipNativeUsage && + config !== undefined && + codexRoutesSpendNativeQuota(accountResponse, config.config); + const readUsage: Effect.Effect = nativeUsage + ? readCodexRateLimits(client, deadlineMs) + : Effect.undefined; + return readUsage.pipe( + Effect.map((rateLimits) => ({ + config: config?.config, + nativeUsage, + rateLimits, + })), + ); + }), ), - // Usage is an enrichment: a failure or a slow answer degrades to "no - // usage this probe" rather than costing the account and models. - input.skipNativeUsage - ? Effect.undefined - : withCodexDiscoveryDeadline( - client.request("account/rateLimits/read", null), - deadlineMs, - RATE_LIMITS_PROBE_TIMEOUT_MS, - ).pipe( - Effect.map((response): CodexRateLimitsProbe => - response - ? { - snapshot: response.rateLimits, - rateLimitsByLimitId: response.rateLimitsByLimitId, - resetCredits: response.rateLimitResetCredits, - accountId: response.accountId, - } - : { failure: "Codex did not answer the usage request." }, - ), - Effect.catch((error) => - Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe( - Effect.as({ failure: codexRateLimitsFailureMessage(error) }), - ), - ), - ), ], { concurrency: "unbounded" }, ); + const cyberAccess = Option.getOrUndefined(decodeCodexCyberAccessConfig(config)); return { account: accountResponse, + endpoint: config ? codexCustomEndpoint(config) : undefined, + nativeUsage, ...(rateLimits ? { rateLimits } : {}), version, models, - serviceTier, + serviceTier: config?.service_tier ?? undefined, + daybreakEnabled: config === undefined ? undefined : cyberAccess?.daybreak === true, + // An unread config cannot rule out an API key with the programs turned off. + cyberAccessProgramsUnavailable: + accountResponse.account?.type === "apiKey" && + (config === undefined || cyberAccess?.features?.api_key_cyber_access_programs === false), skills: skillsResponse ? parseCodexSkillsListResponse(skillsResponse, input.cwd) : [], } satisfies CodexAppServerProviderSnapshot; }); @@ -637,7 +852,12 @@ const probeCodexCliVersion = Effect.fn("probeCodexCliVersion")( if (result.code !== 0) return null; return CODEX_CLI_VERSION_PATTERN.exec(result.stdout)?.[1] ?? null; }, - Effect.timeoutOption(Duration.millis(DEFAULT_TIMEOUT_MS)), + (effect, input) => + effect.pipe( + Effect.timeoutOption( + resolveProviderProbeTimeoutMs("codex", DEFAULT_TIMEOUT_MS, input.environment), + ), + ), Effect.map(Option.getOrNull), Effect.catch((cause) => Effect.logDebug("Codex --version fallback failed.", { cause }).pipe(Effect.as(null)), @@ -659,6 +879,52 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functi return parseCodexSkillsListResponse(skillsResponse, input.cwd); }); +// Long enough for a burst of workspace switches; short because the helper holds the user's +// binary open, and Windows refuses to overwrite or delete a running executable. +const CODEX_SKILLS_HELPER_IDLE_TTL = "30 seconds"; + +/** Reuses one app-server per launch identity; each read passes its cwd and rescans from disk. */ +export const makeCodexSkillsProbe = Effect.fn("makeCodexSkillsProbe")(function* () { + const helpers = yield* RcMap.make({ + lookup: (launch: { + readonly binaryPath: string; + readonly homePath?: string; + readonly launchArgs?: string; + readonly environment: NodeJS.ProcessEnv; + }) => + withCodexAppServerClient({ ...launch, cwd: process.cwd() }).pipe( + Effect.map(({ client }) => client), + ), + idleTimeToLive: CODEX_SKILLS_HELPER_IDLE_TTL, + }); + return Effect.fn("CodexSkillsProbe.probe")(function* (input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly launchArgs?: string; + readonly cwd: string; + readonly environment?: NodeJS.ProcessEnv; + }) { + const { cwd, ...rest } = input; + const launch = { + ...rest, + environment: providerProbeEnvironment(rest.environment ?? process.env), + }; + // Retire helpers for a previous binary, home, credentials, or launch options. + const stale = Array.from(yield* RcMap.keys(helpers)).filter( + (key) => !Equal.equals(key, launch), + ); + yield* Effect.forEach(stale, (key) => RcMap.invalidate(helpers, key), { discard: true }); + const skillsResponse = yield* RcMap.get(helpers, launch).pipe( + Effect.flatMap((client) => client.request("skills/list", { cwds: [cwd], forceReload: true })), + Effect.scoped, + // RcMap keeps a failed spawn, and a dead helper keeps failing; drop it so the retry respawns. + Effect.onError(() => RcMap.invalidate(helpers, launch)), + Effect.retry({ times: 1 }), + ); + return parseCodexSkillsListResponse(skillsResponse, cwd); + }); +}); + const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => appendCustomCodexModels([], codexSettings.customModels); @@ -701,7 +967,12 @@ const makePendingCodexProvider = Effect.fn("CodexProvider.makePendingCodexProvid }); }); -function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): { +const quotePath = Schema.encodeSync(Schema.fromJsonString(Schema.String)); + +function accountProbeStatus( + { account, rateLimits }: CodexAppServerProviderSnapshot, + codexHome: string | undefined, +): { readonly status: Exclude; readonly auth: ServerProvider["auth"]; readonly message?: string; @@ -729,7 +1000,9 @@ function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnaps return { status: "error", auth: { status: "unauthenticated" }, - message: "Codex CLI is not authenticated. Run `codex login` and try again.", + message: codexHome + ? `Codex CLI is not authenticated. Run \`codex login\` with CODEX_HOME set to ${quotePath(codexHome)} and try again.` + : "Codex CLI is not authenticated. Run `codex login` and try again.", }; } @@ -739,6 +1012,7 @@ function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnaps export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( codexSettings: CodexSettings, probe: (input: { + readonly probeTimeoutMs: number; readonly binaryPath: string; readonly homePath?: string; readonly launchArgs?: string; @@ -778,7 +1052,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu }); } + const probeTimeoutMs = resolveProviderProbeTimeoutMs( + "codex", + CODEX_AUTH_PROBE_TIMEOUT_MS, + resolvedEnvironment, + ); const probeResult = yield* probe({ + probeTimeoutMs, binaryPath: codexSettings.binaryPath, homePath: codexSettings.homePath, launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment), @@ -787,7 +1067,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu ...(managedAuth ? { skipNativeUsage: true } : {}), }).pipe( // Process teardown can outlast the work budget without discarding a completed snapshot. - Effect.timeoutOption(Duration.millis(CODEX_AUTH_PROBE_TIMEOUT_MS)), + Effect.timeoutOption(Duration.millis(probeTimeoutMs)), Effect.scoped, Effect.result, ); @@ -844,9 +1124,15 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu const snapshot = probeResult.success.value; const accountStatus = managedAuth ? { status: "ready" as const, auth: managedAuth, message: undefined } - : accountProbeStatus(snapshot); + : accountProbeStatus( + snapshot, + codexSettings.homePath + ? expandHomePath(codexSettings.homePath, yield* HostProcess.HomeDirectory) + : undefined, + ); + // Sign-in guidance still applies when Codex itself says it needs an OpenAI login. const usageLimits = - snapshot.account.account?.type === "apiKey" + !snapshot.nativeUsage && !accountStatus.message ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }) : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits ? makeUnavailableUsageLimits({ @@ -870,6 +1156,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels), applyPreferredCodexDefaultModel, (models) => applyConfiguredCodexServiceTier(models, snapshot.serviceTier), + (models) => applyConfiguredCodexCyberAccess(models, snapshot), ), skills: snapshot.skills, slashCommands: [ @@ -889,7 +1176,9 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu installed: true, version: snapshot.version ?? null, status: snapshot.models === undefined ? "warning" : accountStatus.status, - auth: accountStatus.auth, + auth: snapshot.endpoint + ? { ...accountStatus.auth, endpoint: snapshot.endpoint } + : accountStatus.auth, ...(accountStatus.message ? { message: accountStatus.message } : snapshot.models === undefined diff --git a/apps/server/src/provider/CodexThreadRevert.test.ts b/apps/server/src/provider/CodexThreadRevert.test.ts index e48caf0940..f268719154 100644 --- a/apps/server/src/provider/CodexThreadRevert.test.ts +++ b/apps/server/src/provider/CodexThreadRevert.test.ts @@ -68,7 +68,6 @@ it.effect("finds the revert boundary across pages of newest-first turns", () => ], }), ), - Effect.scoped, ), ); @@ -87,6 +86,5 @@ it.effect("rejects repeated cursors instead of looping or reverting incomplete h entries: [...page(1, null, 3, ["newest"], "again"), ...page(2, "again", 2, [], "again")], }), ), - Effect.scoped, ), ); diff --git a/apps/server/src/provider/DocumentText.ts b/apps/server/src/provider/DocumentText.ts index 83aa014257..d0e53121ae 100644 --- a/apps/server/src/provider/DocumentText.ts +++ b/apps/server/src/provider/DocumentText.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off -- the isolated parser process is an external runtime boundary. import * as NodeChildProcess from "node:child_process"; import * as NodeURL from "node:url"; +import * as Cache from "effect/Cache"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -48,13 +49,17 @@ const make = Effect.gen(function* () { const isExecutable = yield* HostProcess.IsExecutable; const environment = yield* HostProcess.Environment; const clock = yield* Clock.Clock; - const lock = yield* Semaphore.make(1); + // A large DOCX worker peaks near 270 MiB RSS, so two slots bound parser memory near 540 MiB. + const lock = yield* Semaphore.make(2); const failed = new Map(); + // A cancelled extraction can still be publishing while its retry runs in the other slot. + let attempt = 0; // In a bundle import.meta.url is bin.mjs; development and tests use this source module. const entry = NodeURL.fileURLToPath( new URL(import.meta.url.endsWith(".ts") ? "../bin.ts" : "./bin.mjs", import.meta.url), ); - const extract = Effect.fn("DocumentText.extract")(function* (path: string, extension: string) { + const extract = Effect.fn("DocumentText.extract")(function* (path: string) { + const extension = path.split(".").at(-1)!.toLowerCase(); const sidecar = `${path}.txt`; if (yield* fs.exists(sidecar)) return sidecar; if ((failed.get(path) ?? 0) > clock.currentTimeMillisUnsafe()) return; @@ -94,7 +99,7 @@ const make = Effect.gen(function* () { return Effect.logWarning("Document text extraction failed.", { extension }); }), ); - const pending = `${sidecar}.part`; + const pending = `${sidecar}.${attempt++}.part`; yield* fs .writeFileString(pending, content) .pipe( @@ -104,13 +109,14 @@ const make = Effect.gen(function* () { ); return sidecar; }, lock.withPermits(1)); + const extracting = yield* Cache.make({ capacity: Infinity, timeToLive: 0, lookup: extract }); const ensure = Effect.fn("DocumentText.ensure")( function* (path: string) { const extension = path.split(".").at(-1)?.toLowerCase(); if (!extension || !extensions.has(extension)) return; const sidecar = `${path}.txt`; if (yield* fs.exists(sidecar)) return sidecar; - return yield* extract(path, extension); + return yield* Cache.get(extracting, path); }, Effect.orElseSucceed(() => undefined), ); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 3747ff032d..447745fc67 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -383,7 +383,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { const helper = { fs: { readTextFile: false, writeTextFile: false }, terminal: false, - session: { notices: {} }, + session: { notices: {}, compaction: {} }, }; expect( (yield* h.readRequests) @@ -397,7 +397,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { { fs: { readTextFile: true, writeTextFile: false }, terminal: false, - session: { notices: {} }, + session: { notices: {}, compaction: {} }, elicitation: { form: {} }, }, ]); @@ -426,7 +426,13 @@ it.layer(layerTest)("AntigravityDriver", (it) => { modelSelection, runtimePolicy: cliPolicy, }); - expect(h.launches.at(-1)?.args).toEqual(["acp"]); + expect(h.launches.at(-1)?.args).toEqual([ + "acp", + "--gemini-dir", + h.profileDirectory, + "--app-data-dir", + "antigravity-acp", + ]); expect( (yield* h.readRequests) .slice(requestsBefore) @@ -438,7 +444,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { .map((request) => request.params?.value), ).toEqual(["default"]); } - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -458,7 +464,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(h.acquisitions).toHaveLength(2); expect(h.releases).toEqual([h.first.version, h.signedOut.version]); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () => @@ -475,7 +481,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(h.acquisitions).toHaveLength(2); expect(h.releases).toEqual([h.first.version]); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -496,7 +502,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(after.models).toEqual(before.models); expect(after.auth).toEqual(before.auth); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -533,7 +539,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(after.auth).toEqual(before.auth); expect(JSON.stringify(after)).not.toContain("sk-secret-123"); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -571,6 +577,6 @@ it.layer(layerTest)("AntigravityDriver", (it) => { ); expect(yield* fs.exists(directories.runtimeTemp)).toBe(false); expect(yield* fs.exists(legacyRoot)).toBe(false); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 7bb1f25b67..75bca5acc8 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -434,6 +434,7 @@ export const AntigravityDriver: ProviderDriver< Effect.provideService(HttpClient.HttpClient, httpClient), ); const provider = yield* makeAntigravityProvider(settings, { + environment: processEnvironment, stampIdentity: classifyModels, probe, probeUsage: usage.probe, @@ -462,6 +463,11 @@ export const AntigravityDriver: ProviderDriver< makeRuntime, withProcess: authFlow.withProcess, defaultModel, + supportsNativeGoals: provider.snapshot.getSnapshot.pipe( + Effect.map( + (snapshot) => snapshot.slashCommands?.some((command) => command.name === "goal") === true, + ), + ), profileDirectory, onSessionStarted: provider.onSessionStarted, onSessionEvent: (event) => { diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 5060d8a24e..c81b38a00d 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -273,15 +273,43 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); - it.effect("rejects an oversized skill instead of returning an incomplete catalog", () => + it.effect("does not spend the scan budget on skill bodies", () => Effect.gen(function* () { const path = yield* Path.Path; const input = yield* makeWorkspace(); - const skillPath = yield* writeSkill( - path.join(input.cwd, ".agents", "skills", "oversized"), - `---\nname: oversized\ndescription: Read a large skill.\n---\n${"x".repeat(1_000_000)}`, + const root = path.join(input.userHome, ".gemini", "config", "skills"); + const expected = []; + for (let index = 0; index < 9; index += 1) { + const name = `large-${index}`; + const description = `Large skill ${index}. ${"y".repeat(2_000)}`; + const skillPath = yield* writeSkill( + path.join(root, name), + `---\nname: ${name}\ndescription: ${description}\n---\n${"x".repeat(950_000)}`, + ); + expected.push({ name, description, path: skillPath, scope: "user", enabled: true }); + } + + assert.deepEqual(yield* discoverAntigravitySkills(input), expected); + }), + ); + + it.effect("rejects frontmatter that does not close within the per-skill limit", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const input = yield* makeWorkspace(); + const root = path.join(input.cwd, ".agents", "skills"); + const largeBodyPath = yield* writeSkill( + path.join(root, "large-body"), + `---\nname: large-body\n---\n${"x".repeat(2_000_000)}`, ); + assert.deepEqual(yield* discoverAntigravitySkills(input), [ + { name: "large-body", path: largeBodyPath, scope: "project", enabled: true }, + ]); + const skillPath = yield* writeSkill( + path.join(root, "oversized"), + `---\nname: oversized\ndescription: ${"x".repeat(1_000_000)}\n---\n`, + ); const result = yield* discoverAntigravitySkills(input).pipe(Effect.result); assert.equal(result._tag, "Failure"); if (result._tag === "Failure") { @@ -291,7 +319,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); - it.effect("bounds the total read size across skills", () => + it.effect("bounds the total frontmatter read size across skills", () => Effect.gen(function* () { const path = yield* Path.Path; const input = yield* makeWorkspace(); @@ -299,7 +327,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { for (let index = 0; index < 9; index += 1) { yield* writeSkill( path.join(root, `large-${index}`), - `---\nname: large-${index}\n---\n${"x".repeat(900_000)}`, + `---\nname: large-${index}\ndescription: ${"x".repeat(900_000)}\n---\n`, ); } diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 19e9d8d293..96e1fe6110 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -37,6 +37,8 @@ export function antigravityUserSkillDirectories( const MAX_SKILL_BYTES = 1_000_000; const MAX_SCAN_BYTES = 8_000_000; const MAX_SCAN_ENTRIES = 10_000; +// Typical frontmatter fits in one chunk, so most skills cost about this much of the scan budget. +const SKILL_READ_CHUNK_BYTES = 1024; const SkillFrontmatter = Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)), @@ -106,7 +108,29 @@ function skillPathSortKey(entry: string) { ); } -const readSkill = Effect.fn("readAntigravitySkill")(function* ( +const DASH = 0x2d; + +/** Finds the byte offset after the second `---`, as parseSkillFrontmatter's indexOf calls do. */ +function makeFrontmatterEndFinder() { + let bytesSeen = 0; + let dashes = 0; + let markers = 0; + return (chunk: Uint8Array) => { + for (const byte of chunk) { + bytesSeen += 1; + dashes = byte === DASH ? dashes + 1 : 0; + if (dashes === 3) { + dashes = 0; + markers += 1; + if (markers === 2) return bytesSeen; + } + } + return undefined; + }; +} + +/** Reads through the frontmatter only, so skill bodies do not spend the scan budget. */ +const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* ( skillPath: string, budget: ScanBudget, ) { @@ -115,26 +139,27 @@ const readSkill = Effect.fn("readAntigravitySkill")(function* ( if (info?.type !== "File") return undefined; const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes); - if (info.size > BigInt(byteLimit)) { - return yield* new AntigravitySkillsProbeError({ - reason: "scan-budget-exhausted", - path: skillPath, - }); - } + const findFrontmatterEnd = makeFrontmatterEndFinder(); + let frontmatterEnd: number | undefined; const chunks = yield* readIfPresent( - fileSystem.stream(skillPath, { bytesToRead: byteLimit + 1 }).pipe(Stream.runCollect), + fileSystem + .stream(skillPath, { bytesToRead: byteLimit + 1, chunkSize: SKILL_READ_CHUNK_BYTES }) + .pipe( + Stream.takeUntil((chunk) => (frontmatterEnd = findFrontmatterEnd(chunk)) !== undefined), + Stream.runCollect, + ), skillPath, ); if (chunks === undefined) return undefined; const bytes = Buffer.concat(chunks); - if (bytes.byteLength > byteLimit) { + budget.remainingBytes -= bytes.byteLength; + if ((frontmatterEnd ?? bytes.byteLength) > byteLimit) { return yield* new AntigravitySkillsProbeError({ reason: "scan-budget-exhausted", path: skillPath, }); } - budget.remainingBytes -= bytes.byteLength; - return bytes.toString("utf8"); + return bytes.toString("utf8", 0, frontmatterEnd); }); /** Keep read errors typed so workspace snapshots cannot cache partial results. */ @@ -187,7 +212,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( if (skillFileName !== undefined) { if (!skillFileName.endsWith(".md")) return; const skillPath = path.join(directory, skillFileName); - const contents = yield* readSkill(skillPath, budget); + const contents = yield* readSkillFrontmatter(skillPath, budget); if (contents === undefined) return; const skill = parseSkillFrontmatter(contents, skillFileName); if (!skill || skillsByName.has(skill.name)) return; diff --git a/apps/server/src/provider/Drivers/AntigravityUsage.ts b/apps/server/src/provider/Drivers/AntigravityUsage.ts index 5cb55ed77a..2eb9744a3e 100644 --- a/apps/server/src/provider/Drivers/AntigravityUsage.ts +++ b/apps/server/src/provider/Drivers/AntigravityUsage.ts @@ -15,7 +15,11 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import { resolveAntigravityInstanceDirectories } from "../antigravityAuthSupport.ts"; -import { makeAntigravityUsageCache, readAntigravityUsage } from "./antigravityUsageReader.ts"; +import { + antigravityRateModel, + makeAntigravityUsageCache, + readAntigravityUsage, +} from "./antigravityUsageReader.ts"; export class AntigravityUsage extends Context.Service< AntigravityUsage, @@ -123,6 +127,7 @@ export const layer = Layer.effect(AntigravityUsage, make); export const antigravityUsageReader: ProviderUsageReader = { kind: "scan", provider: "antigravity", + rateModel: antigravityRateModel, scan: ({ instances, windowStartMs }) => AntigravityUsage.pipe(Effect.flatMap((usage) => usage.scan({ instances, windowStartMs }))), }; diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index 3ada122976..5bedffe924 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -1,13 +1,16 @@ import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; +import type * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +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 { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; @@ -36,6 +39,10 @@ import { import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider"; import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog"; import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts"; +import { + makeClaudeCodeModelRoutes, + resolveClaudeModelSettingsKey, +} from "../ClaudeCodeModelRoutes.ts"; import { defaultProviderContinuationIdentity, type ProviderDriver, @@ -146,6 +153,26 @@ export const ClaudeDriver: ProviderDriver 0 || + processEnv.CLAUDE_CONFIG_DIR !== (yield* HostProcess.Environment).CLAUDE_CONFIG_DIR; + // Only a successful probe records routes, so a failed one never sends turns back to slugs + // the backend rejects. + const modelRoutes = yield* makeClaudeCodeModelRoutes( + (cwd) => + resolveClaudeModelSettingsKey( + customHome ? ["project", "local"] : ["user", "project", "local"], + cwd, + ).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), + stateDir, + ); + // Retain reports until the registry subscribes; end its listener on teardown. + const workspaceRescans = yield* Queue.unbounded(); + yield* Effect.addFinalizer(() => Queue.end(workspaceRescans)); const orchestrationAdapter = yield* createClaudeAdapterV2( { instanceId, @@ -158,7 +185,9 @@ export const ClaudeDriver: ProviderDriver snapshot.applyUsageLimits(update), + onSessionInit: (cwd) => Queue.offer(workspaceRescans, cwd).pipe(Effect.asVoid), modelCatalog, + routeModelCatalog: modelRoutes.route, }, ).pipe( Effect.mapError( @@ -175,6 +204,7 @@ export const ClaudeDriver: ProviderDriver Ref.set(lastGoodCapabilities, capabilities)), + Effect.tap(({ capabilities }) => + Ref.set(lastGoodCapabilities, capabilities).pipe( + Effect.andThen(modelRoutes.record(capabilities.models ?? [])), + ), + ), + Effect.ensuring(modelRoutes.settle), Effect.catch((error) => Ref.getAndSet(lastGoodCapabilities, undefined).pipe( Effect.flatMap((capabilities) => @@ -262,6 +297,8 @@ export const ClaudeDriver: ProviderDriver - Effect.gen(function* () { - const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt; - yield* Cache.invalidateAll(capabilitiesProbeCache); - const refreshed = yield* snapshot.refresh; - const after = refreshed.usageLimits?.checkedAt; - if ( - outcome === "reset" && - (after === undefined || - after === before || - refreshed.usageLimits?.unavailable?.reason === "probeFailed") - ) { - return yield* new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: - "The reset was applied, but Claude could not confirm the new limits. Refresh to check.", - }); - } - }), + ResetCreditCoordinator.refreshAfterRedemption({ + outcome, + getSnapshot: snapshot.getSnapshot, + refresh: Cache.invalidateAll(capabilitiesProbeCache).pipe( + Effect.andThen(snapshot.refresh), + ), + }).pipe( + Effect.filterOrFail( + (confirmed) => confirmed, + () => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: + "The reset was applied, but Claude could not confirm the new limits. Refresh to check.", + }), + ), + ), ), ); @@ -383,6 +419,7 @@ export const ClaudeDriver: ProviderDriver snapshot.getSnapshot.pipe( Effect.flatMap((machineSnapshot) => diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index e1319caf69..b6dc61470e 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -9,6 +9,9 @@ const NPM_DIR = "C:\\Users\\dev\\AppData\\Roaming\\npm"; const NPM_SHIM = `${NPM_DIR}\\claude.cmd`; const NPM_PACKAGE_EXE = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`; const NPM_PACKAGE_CLI = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\cli.js`; +const WINGET_DIR = "C:\\Users\\dev\\AppData\\Local\\Microsoft\\WinGet"; +const WINGET_SHIM = `${WINGET_DIR}\\Links\\claude.cmd`; +const WINGET_EXE = `${WINGET_DIR}\\Packages\\Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe\\claude.exe`; function withWindowsResolution(input: { readonly resolvedCommand: string | undefined; @@ -37,6 +40,16 @@ describe("resolveClaudeSdkExecutablePath", () => { }), ); + it.effect("follows the WinGet launcher to the package's native binary", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ resolvedCommand: WINGET_SHIM, existingFiles: [WINGET_EXE] }), + ), + ).toBe(WINGET_EXE); + }), + ); + it.effect("follows .bat and .ps1 launcher shims the same way", () => Effect.gen(function* () { for (const shim of [`${NPM_DIR}\\claude.bat`, `${NPM_DIR}\\claude.ps1`]) { diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 5e4cbb4db6..5797066446 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -13,10 +13,14 @@ const WINDOWS_SHIM_EXTENSIONS: ReadonlySet = new Set([".cmd", ".bat", ". export const isWindowsClaudeLauncherShimPath = (filePath: string): boolean => WINDOWS_SHIM_EXTENSIONS.has(NodePath.win32.extname(filePath).toLowerCase()); -/** New packages provide bin/claude.exe; older packages need a JavaScript runtime for cli.js. */ -const NPM_PACKAGE_ENTRY_CANDIDATES = [ +/** + * npm: new packages provide bin/claude.exe; older ones need a JavaScript runtime for cli.js. + * WinGet: Links\claude.cmd forwards to the package's native executable under ..\Packages. + */ +const PACKAGE_ENTRY_CANDIDATES = [ ["node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"], ["node_modules", "@anthropic-ai", "claude-code", "cli.js"], + ["..", "Packages", "Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe", "claude.exe"], ] as const; export type ExecutableFileCheck = (filePath: string) => boolean; @@ -53,7 +57,7 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta } const shimDirectory = NodePath.win32.dirname(resolved); - for (const entrySegments of NPM_PACKAGE_ENTRY_CANDIDATES) { + for (const entrySegments of PACKAGE_ENTRY_CANDIDATES) { const candidate = NodePath.win32.join(shimDirectory, ...entrySegments); if (isFile(candidate)) { return candidate; diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts index 8042a7f16e..1dfb94bb91 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.ts @@ -100,6 +100,49 @@ export const hasClaudeManagedMcpConfig = Effect.fn("hasClaudeManagedMcpConfig")( return yield* fileSystem.exists(managedMcpConfigPath).pipe(Effect.orElseSucceed(() => false)); }); +// A worktree's .git file points at
/.git/worktrees/, whose commondir leads back to +//
/.git. A bare repository has no main checkout, so its worktree keeps its own file. +// Untraced because claudeLocalSettingsDirectory already owns the span. +const mainCheckoutRoot = Effect.fnUntraced(function* (checkout: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + return yield* fileSystem.readFileString(path.join(checkout, ".git")).pipe( + Effect.flatMap((pointer) => { + const gitDir = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim(); + if (gitDir === undefined) return Effect.succeed(checkout); + const worktreeGitDir = path.resolve(checkout, gitDir); + return fileSystem.readFileString(path.join(worktreeGitDir, "commondir")).pipe( + Effect.map((commonDir) => { + const common = path.resolve(worktreeGitDir, commonDir.trim()); + return path.basename(common) === ".git" ? path.dirname(common) : checkout; + }), + ); + }), + Effect.orElseSucceed(() => checkout), + ); +}); + +// Claude Code keeps .claude/settings.local.json at the repository root, or in cwd outside a +// repository, on Windows, or when the root is home. Its owner check is skipped, so callers must +// stay safe when Claude Code ignores the root file. +export const claudeLocalSettingsDirectory = Effect.fn("claudeLocalSettingsDirectory")(function* ( + cwd: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + if ((yield* HostProcess.Platform) === "win32") return cwd; + for (let directory = cwd; ; directory = path.dirname(directory)) { + const isCheckout = yield* fileSystem + .exists(path.join(directory, ".git")) + .pipe(Effect.orElseSucceed(() => false)); + if (isCheckout) { + const root = yield* mainCheckoutRoot(directory); + return root === (yield* HostProcess.HomeDirectory) ? cwd : root; + } + if (path.dirname(directory) === directory) return cwd; + } +}); + export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")( function* ( config: Pick, diff --git a/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts b/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts index 7897fe9b75..33f9f901c8 100644 --- a/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts @@ -24,6 +24,8 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as Sink from "effect/Sink"; +import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { makeClaudeMaintenanceResolution } from "./ClaudeMaintenance.ts"; @@ -42,19 +44,31 @@ const snapshot: ServerProvider = { }; const fixture = Effect.fn("ClaudeMaintenance.test.fixture")(function* ( - npm = false, + install: "native" | "xdgNative" | "npm" | "wrapper" = "native", platform: NodeJS.Platform = "linux", programFiles?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const directory = yield* fs.makeTempDirectoryScoped(); - const binaryPath = npm - ? path.join(directory, "lib/node_modules/@anthropic-ai/claude-code/cli.js") - : path.join(directory, ".local/bin", platform === "win32" ? "claude.exe" : "claude"); - yield* fs.makeDirectory(path.dirname(binaryPath), { recursive: true }); - yield* fs.writeFileString(binaryPath, "#!/bin/sh\n"); - yield* fs.chmod(binaryPath, 0o755); + const binaryPath = + install === "npm" + ? path.join(directory, "lib/node_modules/@anthropic-ai/claude-code/cli.js") + : path.join(directory, ".local/bin", platform === "win32" ? "claude.exe" : "claude"); + // Unix native installs link the launcher to a versioned binary; Windows places a real .exe. + const realBinaryPath = + install === "native" && platform !== "win32" + ? path.join(directory, ".local/share/claude/versions/2.1.314") + : install === "xdgNative" + ? path.join(directory, "xdg/data/claude/versions/2.1.314") + : binaryPath; + yield* fs.makeDirectory(path.dirname(realBinaryPath), { recursive: true }); + yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n"); + yield* fs.chmod(realBinaryPath, 0o755); + if (realBinaryPath !== binaryPath) { + yield* fs.makeDirectory(path.dirname(binaryPath), { recursive: true }); + yield* fs.symlink(realBinaryPath, binaryPath); + } const configDirectory = path.join(directory, "config"); yield* fs.makeDirectory(configDirectory); const settingsPath = path.join(configDirectory, "settings.json"); @@ -65,6 +79,13 @@ const fixture = Effect.fn("ClaudeMaintenance.test.fixture")(function* ( : platform === "darwin" ? "/Library/Application Support/ClaudeCode" : "/etc/claude-code"; + const npmPath = path.join(directory, "bin/npm"); + if (install === "npm") { + yield* fs.makeDirectory(path.dirname(npmPath), { recursive: true }); + yield* fs.writeFileString(npmPath, "#!/bin/sh\n"); + yield* fs.chmod(npmPath, 0o755); + } + const npmProbes: Array> = []; let installationReads = 0; const testFs = FileSystem.makeNoop({ ...fs, @@ -93,11 +114,37 @@ const fixture = Effect.fn("ClaudeMaintenance.test.fixture")(function* ( managed, managedDirectory, settingsPath, + npmProbes, installationReads: () => installationReads, - makeResolution: makeClaudeMaintenanceResolution({ binaryPath, env: { PATH: "" } }).pipe( + makeResolution: makeClaudeMaintenanceResolution({ + binaryPath, + env: { PATH: install === "npm" ? path.dirname(npmPath) : "" }, + }).pipe( Effect.provideService( ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("version checks must not run a subprocess")), + ChildProcessSpawner.make((command) => { + if (!ChildProcess.isStandardCommand(command) || command.command !== npmPath) { + return Effect.die("version checks may only ask npm"); + } + npmProbes.push(command.args.map(String)); + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.encodeText( + Stream.make(JSON.stringify({ "@anthropic-ai/claude-code": { latest: "2.1.316" } })), + ), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + }), ), Effect.provideService(FileSystem.FileSystem, testFs), Effect.provideService(HostProcess.Platform, platform), @@ -194,7 +241,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { }, ])("advertises the installable version for $name", (row) => Effect.gen(function* () { - const f = yield* fixture(row.npm); + const f = yield* fixture(row.npm ? "npm" : "native"); if (row.settings) yield* f.fs.writeFileString(f.settingsPath, row.settings); const requests: string[] = []; const client = HttpClient.make((request) => { @@ -221,13 +268,18 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { status: row.advisory, latestVersion: row.expected, }); - expect(requests).toHaveLength(1); - expect(requests[0]).toMatch( - row.npm ? /registry\.npmjs\.org/ : new RegExp(`claude-code-releases/${row.channel}$`), - ); + // npm installs ask `npm outdated`, which applies npm's release-age settings. + const lookups = row.npm ? f.npmProbes : requests; + expect(lookups).toHaveLength(1); + if (row.npm) { + expect(requests).toEqual([]); + expect(f.npmProbes[0]?.[0]).toBe("outdated"); + } else { + expect(requests[0]).toMatch(new RegExp(`claude-code-releases/${row.channel}$`)); + } yield* enrich; - expect(requests).toHaveLength(1); - }).pipe(Effect.scoped), + expect(lookups).toHaveLength(1); + }), ); it.effect.each([ @@ -239,7 +291,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { "separates channel caches and honors $name managed overrides and feed invalidation", (row) => Effect.gen(function* () { - const f = yield* fixture(false, row.platform, row.programFiles); + const f = yield* fixture("native", row.platform, row.programFiles); const requests: string[] = []; const client = HttpClient.make((request) => { requests.push(request.url); @@ -285,7 +337,27 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { ); yield* check; expect(requests).toHaveLength(3); - }).pipe(Effect.scoped), + }), + ); + + it.effect.each([ + { name: "a wrapper script", install: "wrapper", lockKey: undefined }, + { + name: "a native install under XDG_DATA_HOME", + install: "xdgNative", + lockKey: "claudeAgent-native", + }, + ] as const)("resolves the native launcher path for $name", (row) => + Effect.gen(function* () { + const f = yield* fixture(row.install); + const resolve = yield* f.makeResolution.pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("resolution must not look up a version")), + ), + ); + expect((yield* resolve()).update?.lockKey).toBe(row.lockKey); + }), ); it.effect("automatic refresh rereads the native channel while preserving both caches", () => @@ -331,6 +403,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { }).pipe( Effect.provide( Layer.mock(ProviderHost.ProviderHost)({ + awaitServerReady: Effect.void, paths: { cwd: f.directory, baseDir: f.directory, @@ -371,7 +444,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { ]); expect(f.installationReads()).toBe(1); } - }).pipe(Effect.scoped), + }), ); it.effect("bounds stalled feed bodies and skips disabled update checks", () => @@ -401,6 +474,6 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { yield* TestClock.adjust("4 seconds"); expect((yield* Fiber.join(pending)).versionAdvisory?.status).toBe("unknown"); expect(requests).toBe(1); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/provider/Drivers/ClaudeMaintenance.ts b/apps/server/src/provider/Drivers/ClaudeMaintenance.ts index e278c25d6d..cb225d1fde 100644 --- a/apps/server/src/provider/Drivers/ClaudeMaintenance.ts +++ b/apps/server/src/provider/Drivers/ClaudeMaintenance.ts @@ -30,14 +30,17 @@ const update = makePackageManagedProviderMaintenanceResolver({ mise: { tool: "claude" }, nativeUpdate: { args: ["update"], + // On Unix the native launcher links into ${XDG_DATA_HOME:-~/.local/share}/claude/versions; a + // plain file at ~/.local/bin/claude is a wrapper whose owner `claude update` cannot see. isCommandPath: (commandPath) => { const normalized = normalizeCommandPath(commandPath); return ( - normalized.endsWith("/.local/bin/claude") || normalized.endsWith("/.local/bin/claude.exe") || - normalized.includes("/.local/share/claude/") + normalized.includes("/.local/share/claude/") || + normalized.includes("/claude/versions/") ); }, + requiresCommandPath: true, }, }); diff --git a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts index 6ce141eec7..bdf2ed1cae 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts @@ -22,12 +22,14 @@ export interface ClaudeSkillDispatch { export function planClaudeSkillDispatch( prompt: string, skills: ReadonlyMap, + /** Mentions before this offset, such as inline handoff history, stay plain text. */ + mentionsFrom = 0, ): ClaudeSkillDispatch | undefined { const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => { const name = match[2] ?? ""; const skill = skills.get(name); - if (!skill) return []; const start = (match.index ?? 0) + (match[1]?.length ?? 0); + if (!skill || start < mentionsFrom) return []; return [{ name, skill, start, end: (match.index ?? 0) + match[0].length }]; }); const last = mentions.at(-1); diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts index b4ce31cac8..349294baa8 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts @@ -3,10 +3,19 @@ import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; -import { discoverClaudeSkills } from "./ClaudeSkills.ts"; +import { discoverClaudeSkills as discoverSkills } from "./ClaudeSkills.ts"; import { planClaudeSkillDispatch } from "./ClaudeSkillDispatch.ts"; +// Windows makes the managed directory fixture-controlled without reading host policy or skills. +const discoverClaudeSkills = ( + ...[config, cwd, environment = {}]: Parameters +) => + discoverSkills(config, cwd, environment).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + ); + const writeSkill = Effect.fn(function* ( skillsDir: string, directoryName: string, @@ -354,6 +363,320 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); + it.effect("discovers skills from the current account's claude.ai synced plugins", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const synced = path.join(configDir, "plugins", "synced"); + const organization = "11111111-2222-4333-8444-555555555555"; + const writeBucket = Effect.fn(function* (account: string, skillSuffix = "") { + const bucket = path.join(synced, `${organization}_${account}`); + const plugins = [ + { + pluginId: "plugin_01pstack", + name: "pstack", + directory: "pstack", + skill: "poteto-mode", + }, + { + pluginId: "plugin_01design", + name: "0f6a7c9e-1111-4222-8333-444444444444", + generation: 2, + directory: "0f6a7c9e-1111-4222-8333-444444444444~g2", + prefix: "design", + skill: "design-critique", + }, + ]; + for (const plugin of plugins) { + const pluginDir = path.join(bucket, plugin.directory); + yield* writeSkill(path.join(pluginDir, "skills"), plugin.skill + skillSuffix, "# Synced"); + yield* fs.makeDirectory(path.join(pluginDir, ".claude-plugin")); + yield* fs.writeFileString( + path.join(pluginDir, ".claude-plugin", "plugin.json"), + JSON.stringify({ name: plugin.prefix ?? plugin.name }), + ); + } + yield* fs.writeFileString( + path.join(bucket, "manifest.json"), + JSON.stringify({ + lastUpdated: 1761990000000, + plugins: plugins.map(({ pluginId, name, generation }) => ({ + pluginId, + name, + ...(generation ? { generation } : {}), + })), + }), + ); + yield* fs.writeFileString(path.join(synced, `.bucket-${organization}_${account}`), ""); + return bucket; + }); + const bucket = yield* writeBucket("66666666-7777-4888-9999-aaaaaaaaaaaa"); + yield* writeBucket("77777777-8888-4999-aaaa-bbbbbbbbbbbb", "-other-account"); + yield* fs.writeFileString( + path.join(configDir, ".claude.json"), + JSON.stringify({ + oauthAccount: { + organizationUuid: organization, + accountUuid: "66666666-7777-4888-9999-aaaaaaaaaaaa", + }, + }), + ); + + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: configDir }, undefined, {})).map((skill) => [ + skill.name, + skill.path, + ]), + [ + [ + "design:design-critique", + path.join( + bucket, + "0f6a7c9e-1111-4222-8333-444444444444~g2", + "skills", + "design-critique", + "SKILL.md", + ), + ], + ["pstack:poteto-mode", path.join(bucket, "pstack", "skills", "poteto-mode", "SKILL.md")], + ], + ); + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: configDir }, undefined, { + CLAUDE_CODE_PLUGIN_CACHE_DIR: path.join(configDir, "relocated-cache"), + })).map((skill) => skill.name), + ["design:design-critique", "pstack:poteto-mode"], + ); + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: configDir }, undefined, { + CLAUDE_CODE_OAUTH_TOKEN: "token", + CLAUDE_CODE_ACCOUNT_UUID: "77777777-8888-4999-aaaa-bbbbbbbbbbbb", + })).map((skill) => skill.name), + ["design:design-critique-other-account", "pstack:poteto-mode-other-account"], + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"pstack@synced":false}}', + ); + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: configDir }, undefined, {})).map( + (skill) => skill.name, + ), + ["design:design-critique"], + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"syncClaudeAiPlugins":false}', + ); + assert.deepEqual(yield* discoverClaudeSkills({ homePath: configDir }, undefined, {}), []); + }), + ); + + it.effect("gives a synced namespace to an installed plugin, then the first synced row", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const bucketName = "11111111-2222-4333-8444-555555555555_unbound"; + const synced = path.join(configDir, "plugins", "synced"); + const bucket = path.join(synced, bucketName); + for (const [directory, prefix, skill] of [ + ["pstack", "pstack", "poteto-mode"], + ["pstack-copy", "pstack", "copied"], + ["tools", "tools", "synced-tool"], + ["a_b", undefined, "renamed"], + ["PSTACK", "PSTACK", "shouted"], + ] as const) { + yield* writeSkill(path.join(bucket, directory, "skills"), skill, "# Synced"); + if (prefix === undefined) continue; + yield* fs.makeDirectory(path.join(bucket, directory, ".claude-plugin")); + yield* fs.writeFileString( + path.join(bucket, directory, ".claude-plugin", "plugin.json"), + JSON.stringify({ name: prefix }), + ); + } + yield* fs.writeFileString( + path.join(bucket, "manifest.json"), + JSON.stringify({ + plugins: ["pstack", "pstack-copy", "tools", "a:b. ", "PSTACK", "no-id"].map( + (name, index) => (name === "no-id" ? { name } : { pluginId: `plugin_0${index}`, name }), + ), + }), + ); + yield* fs.writeFileString(path.join(synced, `.bucket-${bucketName}`), ""); + const installed = path.join(configDir, "plugins", "cache", "shop", "tools"); + yield* writeSkill(path.join(installed, "skills"), "installed-tool", "# Installed"); + yield* fs.writeFileString( + path.join(configDir, "plugins", "installed_plugins.json"), + JSON.stringify({ + plugins: { + "tools@shop": [{ scope: "user", installPath: installed }], + "pstack@shop": [{ scope: "user", installPath: path.join(configDir, "missing") }], + }, + }), + ); + const names = (enabled: boolean) => + Effect.gen(function* () { + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + JSON.stringify({ enabledPlugins: { "tools@shop": enabled, "pstack@shop": true } }), + ); + const skills = yield* discoverClaudeSkills({ homePath: configDir }, undefined, { + CLAUDE_CODE_ORGANIZATION_UUID: "11111111-2222-4333-8444-555555555555", + CLAUDE_CODE_ACCOUNT_UUID: "not-a-uuid", + }); + return skills.map((skill) => skill.name); + }); + + assert.deepEqual(yield* names(true), [ + "a_b:renamed", + "pstack:poteto-mode", + "tools:installed-tool", + ]); + assert.deepEqual(yield* names(false), [ + "a_b:renamed", + "pstack:poteto-mode", + "tools:synced-tool", + ]); + yield* writeSkill(path.join(bucket, "no-id", "skills"), "unlisted", "# Synced"); + assert.notInclude( + (yield* discoverClaudeSkills({ homePath: configDir }, undefined, { + CLAUDE_CODE_ORGANIZATION_UUID: "11111111-2222-4333-8444-555555555555", + })).map((skill) => skill.name), + "no-id:unlisted", + ); + }), + ); + + it.effect("hides synced plugins from local settings but not shared project settings", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const configDir = path.join(tempDir, "claude-home"); + const workspace = path.join(tempDir, "workspace"); + const bucketName = + "11111111-2222-4333-8444-555555555555_66666666-7777-4888-9999-aaaaaaaaaaaa"; + const synced = path.join(configDir, "plugins", "synced"); + yield* writeSkill(path.join(synced, bucketName, "pstack", "skills"), "poteto-mode", "# S"); + yield* fs.writeFileString( + path.join(synced, bucketName, "manifest.json"), + '{"plugins":[{"pluginId":"plugin_01pstack","name":"pstack"}]}', + ); + yield* fs.writeFileString(path.join(synced, `.bucket-${bucketName}`), ""); + yield* fs.makeDirectory(path.join(workspace, ".claude"), { recursive: true }); + yield* fs.writeFileString( + path.join(workspace, ".claude", "settings.json"), + '{"syncClaudeAiPlugins":false}', + ); + const environment = { + CLAUDE_CODE_ORGANIZATION_UUID: "11111111-2222-4333-8444-555555555555", + CLAUDE_CODE_ACCOUNT_UUID: "66666666-7777-4888-9999-AAAAAAAAAAAA", + }; + const names = Effect.map( + discoverClaudeSkills({ homePath: configDir }, workspace, environment), + (skills) => skills.map((skill) => skill.name), + ); + assert.deepEqual(yield* names, ["pstack:poteto-mode"]); + yield* fs.writeFileString( + path.join(workspace, ".claude", "settings.local.json"), + '{"syncClaudeAiPlugins":false}', + ); + assert.deepEqual(yield* names, []); + }), + ); + + it.effect("discovers inline plugins from CLAUDE_CODE_PLUGIN_DIRS over installed namesakes", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspace = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const configDir = path.join(workspace, "config"); + const named = path.join(workspace, "named"); + const unnamed = path.join(workspace, "unnamed"); + const inherited = path.join(workspace, "inherited"); + const muted = path.join(workspace, "muted"); + const installed = path.join(workspace, "installed-acme"); + yield* fs.makeDirectory(path.join(named, ".claude-plugin"), { recursive: true }); + yield* fs.writeFileString( + path.join(named, ".claude-plugin", "plugin.json"), + '{"name":"acme"}', + ); + yield* writeSkill(path.join(named, "skills"), "qa", "---\ndescription: QA a ticket\n---\n"); + yield* writeSkill(path.join(installed, "skills"), "old", "# Old"); + yield* writeSkill(path.join(unnamed, "skills"), "lint", "# Lint"); + yield* writeSkill(path.join(muted, "skills"), "hidden", "# Hidden"); + const quiet = path.join(workspace, "quiet"); + yield* fs.makeDirectory(path.join(quiet, ".claude-plugin"), { recursive: true }); + yield* fs.writeFileString( + path.join(quiet, ".claude-plugin", "plugin.json"), + '{"name":"quiet","defaultEnabled":false}', + ); + yield* writeSkill(path.join(quiet, "skills"), "hush", "# Hush"); + const bundle = path.join(workspace, "bundle"); + yield* fs.makeDirectory(path.join(bundle, "tools", ".claude-plugin"), { recursive: true }); + yield* fs.writeFileString( + path.join(bundle, "tools", ".claude-plugin", "plugin.json"), + '{"name":"tools"}', + ); + yield* writeSkill(path.join(bundle, "tools", "skills"), "fmt", "# Fmt"); + yield* writeSkill(path.join(bundle, "loose", "skills"), "ignored", "# Ignored"); + yield* writeSkill(path.join(inherited, "skills"), "stale", "# Stale"); + yield* writeSkill(path.join(workspace, "relative", "skills"), "skipped", "# Skipped"); + yield* fs.makeDirectory(path.join(configDir, "plugins"), { recursive: true }); + yield* fs.writeFileString( + path.join(configDir, "plugins", "installed_plugins.json"), + JSON.stringify({ plugins: { "acme@shop": [{ scope: "user", installPath: installed }] } }), + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + JSON.stringify({ + enabledPlugins: { "acme@shop": true, "muted@inline": false }, + env: { + CLAUDE_CODE_PLUGIN_DIRS: [named, "relative", ` ${unnamed} `, muted, quiet, bundle].join( + ";", + ), + }, + }), + ); + + const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace, { + CLAUDE_CODE_PLUGIN_DIRS: inherited, + }); + assert.deepEqual( + skills.map(({ name, scope, description }) => ({ name, scope, description })), + [ + { name: "acme:qa", scope: "user", description: "QA a ticket" }, + { name: "tools:fmt", scope: "user", description: undefined }, + { name: "unnamed:lint", scope: "user", description: undefined }, + ], + ); + + // Managed enabledPlugins entries lock their plugin name against inline copies. + const programFiles = path.join(workspace, "program-files"); + yield* fs.makeDirectory(path.join(programFiles, "ClaudeCode"), { recursive: true }); + yield* fs.writeFileString( + path.join(programFiles, "ClaudeCode", "managed-settings.json"), + '{"enabledPlugins":{"acme@shop":true}}', + ); + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: path.join(workspace, "empty") }, workspace, { + CLAUDE_CODE_PLUGIN_DIRS: [named, unnamed].join(";"), + ProgramFiles: programFiles, + })).map((skill) => skill.name), + ["unnamed:lint"], + ); + + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: path.join(workspace, "empty") }, workspace, { + CLAUDE_CODE_PLUGIN_DIRS: inherited, + })).map((skill) => skill.name), + ["inherited:stale"], + ); + }), + ); + it.effect("discovers user and project skills with frontmatter metadata", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -464,7 +787,7 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); - it.effect("prefers user skills on name collisions even with a stray .agents copy", () => + it.effect("prefers managed then user skills on collisions, even with a stray .agents copy", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -499,6 +822,62 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { description: "User deploy.", }, ]); + + const programFiles = path.join(tempDir, "Program Files"); + const programData = path.join(tempDir, "ProgramData"); + yield* writeSkill( + path.join(programData, "ClaudeCode", ".claude", "skills"), + "legacy-only", + "# Legacy skills must not be discovered", + ); + yield* fs.writeFileString( + path.join(programData, "ClaudeCode", "managed-settings.json"), + '{"skillOverrides":{"deploy":"off"}}', + ); + for (const ProgramFiles of [undefined, "", programFiles]) { + const legacySkills = yield* discoverClaudeSkills({ homePath: configDir }, workspace, { + PROGRAMDATA: programData, + ...(ProgramFiles !== undefined ? { ProgramFiles } : {}), + }); + assert.deepEqual( + legacySkills, + skills.map((skill) => ({ ...skill, enabled: false })), + ); + } + yield* writeSkill( + path.join(programFiles, "ClaudeCode", ".claude", "skills"), + "deploy", + ["---", "name: deploy", "description: Managed deploy.", "---"].join("\n"), + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"skillOverrides":{"deploy":"off"}}', + ); + yield* fs.writeFileString( + path.join(programFiles, "ClaudeCode", "managed-settings.json"), + '{"skillOverrides":{"deploy":"on"}}', + ); + const managedSkills = yield* discoverClaudeSkills({ homePath: configDir }, workspace, { + ProgramFiles: programFiles, + PROGRAMDATA: programData, + }); + + assert.deepEqual(managedSkills, [ + { + name: "deploy", + path: path.join(programFiles, "ClaudeCode", ".claude", "skills", "deploy", "SKILL.md"), + enabled: true, + scope: "user", + description: "Managed deploy.", + }, + ]); + assert.deepEqual( + yield* discoverClaudeSkills({ homePath: configDir }, workspace, { + PROGRAMFILES: ` ${programFiles} `, + PROGRAMDATA: programData, + }), + managedSkills, + ); }), ); diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index ada8a39e1e..4fdd3565d1 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -12,6 +12,8 @@ import { parse as parseYamlDocument } from "yaml"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { claudeAccountConfigPath, readClaudeOauthAccount } from "../claudeResetCredits.ts"; + type ClaudeSkillScope = "user" | "project"; type ClaudeSkillRoot = { @@ -104,19 +106,41 @@ function parseSkillFrontmatter(contents: string): SkillFrontmatter { }; } -function claudeManagedSettingsPath( +// A caller-supplied environment is a plain object, without Windows' case-insensitive keys. +function windowsEnvironmentValue(environment: NodeJS.ProcessEnv, name: string) { + const key = name.toLowerCase(); + return Object.entries(environment) + .find(([candidate]) => candidate.toLowerCase() === key)?.[1] + ?.trim(); +} + +function claudeManagedDirectory( path: Path.Path, platform: NodeJS.Platform, environment: NodeJS.ProcessEnv, ): string | undefined { if (platform === "darwin") { - return "/Library/Application Support/ClaudeCode/managed-settings.json"; + return "/Library/Application Support/ClaudeCode"; } if (platform === "win32") { - const programData = environment.PROGRAMDATA?.trim(); - return programData ? path.join(programData, "ClaudeCode", "managed-settings.json") : undefined; + const programFiles = windowsEnvironmentValue(environment, "ProgramFiles"); + return programFiles ? path.join(programFiles, "ClaudeCode") : undefined; } - return "/etc/claude-code/managed-settings.json"; + return "/etc/claude-code"; +} + +function claudeManagedSettingsPaths( + path: Path.Path, + platform: NodeJS.Platform, + environment: NodeJS.ProcessEnv, +): ReadonlyArray { + const managedDirectory = claudeManagedDirectory(path, platform, environment); + const programData = + platform === "win32" ? windowsEnvironmentValue(environment, "ProgramData") : undefined; + return [ + ...(programData ? [path.join(programData, "ClaudeCode", "managed-settings.json")] : []), + ...(managedDirectory ? [path.join(managedDirectory, "managed-settings.json")] : []), + ]; } /** Claude Code settings files, lowest precedence first. */ @@ -128,7 +152,6 @@ function claudeSettingsPaths( environment: NodeJS.ProcessEnv, repositoryRoot?: string, ): ReadonlyArray { - const managedPath = claudeManagedSettingsPath(path, platform, environment); const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined; return [ path.join(configDirPath, "settings.json"), @@ -139,7 +162,7 @@ function claudeSettingsPaths( ] : []), ...(root ? [path.join(root, ".claude", "settings.local.json")] : []), - ...(managedPath ? [managedPath] : []), + ...claudeManagedSettingsPaths(path, platform, environment), ]; } @@ -216,6 +239,7 @@ const SkillSettings = fromLenientJson( Schema.Struct({ skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)), enabledPlugins: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + syncClaudeAiPlugins: Schema.optional(Schema.Unknown), }), ); const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings); @@ -247,7 +271,12 @@ const readSkillSettings = Effect.fn("readSkillSettings")(function* ( const platform = yield* HostProcess.Platform; const overridesByName = new Map(); const enabledPlugins = new Map(); + const managedPluginNames = new Set(); + const managedPaths = new Set(claudeManagedSettingsPaths(path, platform, environment)); + let syncedPluginsHidden = false; const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd); + const projectSettingsPath = + cwd === undefined ? undefined : path.join(cwd, ".claude", "settings.json"); for (const settingsPath of claudeSettingsPaths( path, @@ -279,14 +308,26 @@ const readSkillSettings = Effect.fn("readSkillSettings")(function* ( for (const [key, enabled] of Object.entries(parsed?.enabledPlugins ?? {})) { if (typeof enabled === "boolean") { enabledPlugins.set(key, enabled); + if (managedPaths.has(settingsPath) && key.includes("@")) { + managedPluginNames.add(pluginNameKey(key.slice(0, key.indexOf("@")))); + } } else { // Extended formats replace lower-precedence values without enabling the plugin here. enabledPlugins.delete(key); } } + // Claude ignores this switch in shared project settings, and honors only false. + if (parsed?.syncClaudeAiPlugins === false && settingsPath !== projectSettingsPath) { + syncedPluginsHidden = true; + } } - return { skillOverrides: overridesByName, enabledPlugins }; + return { + skillOverrides: overridesByName, + enabledPlugins, + managedPluginNames, + syncedPluginsHidden, + }; }); const InstalledPlugins = Schema.fromJsonString( @@ -303,18 +344,188 @@ const PluginManifest = Schema.fromJsonString( Schema.Struct({ name: Schema.optional(Schema.NonEmptyString), skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])), + defaultEnabled: Schema.optional(Schema.Unknown), + }), +); + +const SyncedPlugins = Schema.fromJsonString( + Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }), +); +const decodeSyncedPlugin = Schema.decodeUnknownOption( + Schema.Struct({ + pluginId: Schema.String, + name: Schema.String, + generation: Schema.optional(Schema.Number), }), ); +const ACCOUNT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i; + +/** Claude compares plugin names case-insensitively. */ +function pluginNameKey(name: string): string { + return name.normalize("NFC").toLowerCase(); +} + +/** Claude's folder for a synced row: reserved characters become `_`, trailing dots and spaces go. */ +function syncedPluginDirectoryName(name: string): string { + const replaced = name.replace(/[<>:"|?*\\/]/g, "_"); + let end = replaced.length; + while (end > 0 && (replaced[end - 1] === "." || replaced[end - 1] === " ")) end--; + return replaced.slice(0, end); +} function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean { const relative = path.relative(directory, candidate); return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); } +const readPluginManifest = Effect.fn("readPluginManifest")(function* (pluginPath: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + return yield* fileSystem + .readFileString(path.join(pluginPath, ".claude-plugin", "plugin.json")) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)), + Effect.orElseSucceed(() => undefined), + ); +}); + +const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* ( + installPath: string, + scope: ClaudeSkillScope, + prefix: string, + manifest: typeof PluginManifest.Type | undefined, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const roots: Array = []; + const defaultDirectory = path.join(installPath, "skills"); + const hasDefaultDirectory = yield* fileSystem + .exists(defaultDirectory) + .pipe(Effect.orElseSucceed(() => false)); + if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix }); + const declared = manifest?.skills; + if (declared === undefined && !hasDefaultDirectory) { + const hasRootSkill = yield* fileSystem + .exists(path.join(installPath, "SKILL.md")) + .pipe(Effect.orElseSucceed(() => false)); + if (hasRootSkill) roots.push({ directory: installPath, scope, prefix }); + } + + const canonicalInstallPath = yield* fileSystem + .realPath(installPath) + .pipe(Effect.orElseSucceed(() => undefined)); + for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) { + const directory = path.resolve(installPath, relative); + if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) { + continue; + } + const canonicalDirectory = yield* fileSystem + .realPath(directory) + .pipe(Effect.orElseSucceed(() => undefined)); + // The native loader rejects manifest roots that escape through a symlink, too. + if ( + canonicalDirectory !== undefined && + isInsideDirectory(path, canonicalInstallPath, canonicalDirectory) + ) { + roots.push({ directory, scope, prefix }); + } + } + return roots; +}); + +/** The `_` folder Claude syncs the signed-in account's claude.ai plugins into. */ +const resolveSyncedPluginBucket = Effect.fn("resolveSyncedPluginBucket")(function* ( + config: Pick, + configDirPath: string, + environment: NodeJS.ProcessEnv, +) { + const accountConfigPath = yield* claudeAccountConfigPath( + config.homePath.trim() || environment.CLAUDE_CONFIG_DIR?.trim() ? configDirPath : undefined, + ); + const account = yield* readClaudeOauthAccount(accountConfigPath); + const organizationId = environment.CLAUDE_CODE_ORGANIZATION_UUID ?? account?.organizationUuid; + // A stored claude.ai login names its own account; an injected token uses the env account. + const environmentAccountId = environment.CLAUDE_CODE_ACCOUNT_UUID; + const accountId = + account !== undefined && !environment.CLAUDE_CODE_OAUTH_TOKEN + ? typeof account.accountUuid === "string" + ? account.accountUuid + : undefined + : environmentAccountId && ACCOUNT_UUID_PATTERN.test(environmentAccountId) + ? environmentAccountId + : "unbound"; + if ( + !organizationId || + !accountId || + !ACCOUNT_UUID_PATTERN.test(organizationId) || + (accountId !== "unbound" && !ACCOUNT_UUID_PATTERN.test(accountId)) + ) { + return undefined; + } + return `${organizationId.toLowerCase()}_${accountId.toLowerCase()}`; +}); + +/** A plugin folder itself, or else the manifest-bearing plugins directly inside it. */ +const expandInlinePluginDirectory = Effect.fn("expandInlinePluginDirectory")(function* ( + directory: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const exists = (candidate: string) => + fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false)); + for (const component of [path.join(".claude-plugin", "plugin.json"), "skills", "SKILL.md"]) { + if (yield* exists(path.join(directory, component))) return [directory]; + } + const children = yield* fileSystem + .readDirectory(directory) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + return yield* Effect.filter( + [...children].sort().map((child) => path.join(directory, child)), + (child) => exists(path.join(child, ".claude-plugin", "plugin.json")), + ); +}); + +/** Plugin folders Claude Code loads inline from CLAUDE_CODE_PLUGIN_DIRS, and their plugin names. */ +const discoverInlinePluginSkillRoots = Effect.fn("discoverInlinePluginSkillRoots")(function* ( + pluginDirectories: string | undefined, + enabledPlugins: ReadonlyMap, + managedPluginNames: ReadonlySet, +) { + const path = yield* Path.Path; + const home = yield* HostProcess.HomeDirectory; + const platform = yield* HostProcess.Platform; + const roots: Array = []; + const names = new Set(); + const seen = new Set(); + for (const entry of (pluginDirectories ?? "").split(platform === "win32" ? ";" : ":")) { + const directory = expandHomePath(entry.trim(), home); + // Claude skips relative entries rather than resolving them against its cwd. + if (!directory || !path.isAbsolute(directory)) continue; + for (const installPath of yield* expandInlinePluginDirectory(path.resolve(directory))) { + if (seen.has(installPath)) continue; + seen.add(installPath); + const manifest = yield* readPluginManifest(installPath); + const prefix = manifest?.name ?? path.basename(installPath); + // A `@inline` setting wins; otherwise the manifest's `defaultEnabled` decides. + const setting = enabledPlugins.get(`${prefix}@inline`); + if (setting === false || (setting === undefined && manifest?.defaultEnabled === false)) { + continue; + } + // Managed enabledPlugins entries, true or false, lock the name against inline copies. + if (managedPluginNames.has(pluginNameKey(prefix))) continue; + names.add(pluginNameKey(prefix)); + roots.push(...(yield* pluginSkillRoots(installPath, "user", prefix, manifest))); + } + } + return { roots, names }; +}); + const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* ( configDirPath: string, cwd: string | undefined, enabledPlugins: ReadonlyMap, + inlinePluginNames: ReadonlySet, + syncedBucket: string | undefined, environment: NodeJS.ProcessEnv, ) { const fileSystem = yield* FileSystem.FileSystem; @@ -330,8 +541,9 @@ const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)), Effect.orElseSucceed(() => undefined), ); - if (installed === undefined) return []; const roots: Array = []; + // An enabled inline plugin replaces installed and synced plugins of the same name. + const claimedPluginNames = new Set(inlinePluginNames); // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical. const workspace = cwd === undefined @@ -342,7 +554,7 @@ const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* const repositoryRoot = workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace); - for (const [key, entries] of Object.entries(installed.plugins).sort()) { + for (const [key, entries] of Object.entries(installed?.plugins ?? {}).sort()) { if (enabledPlugins.get(key) !== true) continue; const applicable = yield* Effect.filter( entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))), @@ -369,47 +581,48 @@ const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* if (!install) continue; const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project"; const installPath = path.resolve(cwd ?? ".", install.installPath); - const manifest = yield* fileSystem - .readFileString(path.join(installPath, ".claude-plugin", "plugin.json")) - .pipe( - Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)), - Effect.orElseSucceed(() => undefined), - ); + const manifest = yield* readPluginManifest(installPath); const prefix = manifest?.name ?? key.split("@")[0]; - if (!prefix) continue; - - const defaultDirectory = path.join(installPath, "skills"); - const hasDefaultDirectory = yield* fileSystem - .exists(defaultDirectory) - .pipe(Effect.orElseSucceed(() => false)); - if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix }); - const declared = manifest?.skills; - if (declared === undefined && !hasDefaultDirectory) { - const hasRootSkill = yield* fileSystem - .exists(path.join(installPath, "SKILL.md")) - .pipe(Effect.orElseSucceed(() => false)); - if (hasRootSkill) roots.push({ directory: installPath, scope, prefix }); - } - - const canonicalInstallPath = yield* fileSystem - .realPath(installPath) - .pipe(Effect.orElseSucceed(() => undefined)); - for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) { - const directory = path.resolve(installPath, relative); - if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) { - continue; - } - const canonicalDirectory = yield* fileSystem - .realPath(directory) - .pipe(Effect.orElseSucceed(() => undefined)); - // The native loader rejects manifest roots that escape through a symlink, too. - if ( - canonicalDirectory !== undefined && - isInsideDirectory(path, canonicalInstallPath, canonicalDirectory) - ) { - roots.push({ directory, scope, prefix }); - } - } + if (!prefix || inlinePluginNames.has(pluginNameKey(prefix))) continue; + // A registry record whose install is gone loads nothing and claims no namespace. + if (Option.isSome(existing)) claimedPluginNames.add(pluginNameKey(prefix)); + roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest))); + } + if (syncedBucket === undefined) return roots; + + const syncedPath = path.join(configDirPath, "plugins", "synced"); + const bucketPath = path.join(syncedPath, syncedBucket); + const disabledSyncedPlugins = new Set( + [...enabledPlugins].flatMap(([pluginKey, enabled]) => + !enabled && pluginKey.endsWith("@synced") ? [pluginNameKey(pluginKey.slice(0, -7))] : [], + ), + ); + const hasBucketMarker = yield* fileSystem + .exists(path.join(syncedPath, `.bucket-${syncedBucket}`)) + .pipe(Effect.orElseSucceed(() => false)); + if (!hasBucketMarker) return roots; + const synced = yield* fileSystem.readFileString(path.join(bucketPath, "manifest.json")).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(SyncedPlugins)), + Effect.orElseSucceed(() => undefined), + ); + for (const row of synced?.plugins ?? []) { + const plugin = Option.getOrUndefined(decodeSyncedPlugin(row)); + const directoryName = plugin === undefined ? "" : syncedPluginDirectoryName(plugin.name); + if (!plugin || !directoryName || directoryName.startsWith(".")) continue; + const generation = plugin.generation; + const pluginPath = path.join( + bucketPath, + generation !== undefined && Number.isInteger(generation) && generation >= 2 + ? `${directoryName}~g${generation}` + : directoryName, + ); + const manifest = yield* readPluginManifest(pluginPath); + const prefix = manifest?.name ?? directoryName; + // An installed plugin of the same name, then the first synced row, holds the namespace. + const key = pluginNameKey(prefix); + if (claimedPluginNames.has(key) || disabledSyncedPlugins.has(key)) continue; + claimedPluginNames.add(key); + roots.push(...(yield* pluginSkillRoots(pluginPath, "user", prefix, manifest))); } return roots; }); @@ -436,6 +649,7 @@ const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(funct const SettingsEnv = Schema.Struct({ ANTHROPIC_BASE_URL: Schema.optional(Schema.String), CLAUDE_CODE_ENTRYPOINT: Schema.optional(Schema.String), + CLAUDE_CODE_PLUGIN_DIRS: Schema.optional(Schema.String), // Unquoted JSON values must not fail the decode and drop ANTHROPIC_BASE_URL with them. CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: Schema.optional(Schema.Unknown), CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS: Schema.optional(Schema.Unknown), @@ -503,7 +717,7 @@ export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray & Partial>, cwd?: string, @@ -511,14 +725,34 @@ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* ): Effect.fn.Return, never, FileSystem.FileSystem | Path.Path> { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd); - const { skillOverrides, enabledPlugins } = yield* readSkillSettings( - configDirPath, - cwd, - environment ?? process.env, + const env = environment ?? process.env; + const configDirPath = yield* resolveClaudeConfigDirPath(config, env, cwd); + const { skillOverrides, enabledPlugins, managedPluginNames, syncedPluginsHidden } = + yield* readSkillSettings(configDirPath, cwd, env); + const managedDirectory = claudeManagedDirectory(path, yield* HostProcess.Platform, env); + // Most installs have no synced folder; skip reading `.claude.json` for them. + const hasSyncedPlugins = + !syncedPluginsHidden && + (yield* fileSystem + .exists(path.join(configDirPath, "plugins", "synced")) + .pipe(Effect.orElseSucceed(() => false))); + const syncedBucket = hasSyncedPlugins + ? yield* resolveSyncedPluginBucket(config, configDirPath, env) + : undefined; + // Claude applies its settings `env` over the inherited environment. + const inlinePluginDirectories = + (yield* readClaudeSettingsEnv(config, cwd, env)).CLAUDE_CODE_PLUGIN_DIRS ?? + env.CLAUDE_CODE_PLUGIN_DIRS; + const inlinePlugins = yield* discoverInlinePluginSkillRoots( + inlinePluginDirectories, + enabledPlugins, + managedPluginNames, ); const roots: ReadonlyArray = [ + ...(managedDirectory + ? [{ directory: path.join(managedDirectory, ".claude", "skills"), scope: "user" as const }] + : []), { directory: path.join(configDirPath, "skills"), scope: "user" }, ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []), ...claudeLaunchArgDirectories(config.launchArgs) @@ -527,11 +761,14 @@ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* directory: path.join(path.resolve(cwd ?? ".", directory), ".claude", "skills"), scope: "project" as const, })), + ...inlinePlugins.roots, ...(yield* discoverPluginSkillRoots( configDirPath, cwd, enabledPlugins, - environment ?? process.env, + inlinePlugins.names, + syncedBucket, + env, )), ]; diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 868dc9c0af..1462d05134 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -17,9 +17,11 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; +import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -40,6 +42,7 @@ import { CodexDriver } from "./CodexDriver.ts"; import * as CodexAdapterV2 from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as PortScanner from "../../preview/PortScanner.ts"; import * as ProviderCredentialStore from "../ProviderCredentialStore.ts"; import * as ProviderHostLive from "../ProviderHostLive.ts"; @@ -49,6 +52,7 @@ const layerDeps = ServerConfig.layerTest(process.cwd(), { Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(IdAllocator.layer), Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge(PortScanner.layerTest), Layer.provideMerge( Layer.mock(CodexAdapterV2.CodexAppServerClientFactory)({ open: () => Effect.die("Maintenance resolution must not open a Codex session"), @@ -372,10 +376,7 @@ it.layer(layerTest)("CodexDriver", (it) => { lockKey: "codex-native", env: { CODEX_HOME: sharedHome }, }); - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); it.effect.skipIf(windowsHost)( @@ -429,10 +430,7 @@ it.layer(layerTest)("CodexDriver", (it) => { env: { CODEX_HOME: installHome }, }); } - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); it.effect.skipIf(windowsHost)("derives the standalone update home from either command path", () => @@ -476,7 +474,85 @@ it.layer(layerTest)("CodexDriver", (it) => { CODEX_HOME: fixture.home, }); } - }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), + ); + + // regression: #23937 `codex update` installs the native channel's release, which can lag npm. + it.effect.skipIf(windowsHost)( + "does not advertise npm's latest Codex to a standalone install", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs + .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" }) + .pipe(Effect.flatMap((directory) => fs.realPath(directory))); + const home = NodePath.join(tempDir, "codex-home"); + const binaryPath = NodePath.join(home, "packages", "standalone", "current", "bin", "codex"); + yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true }); + yield* fs.writeFileString(binaryPath, "#!/bin/sh\n"); + yield* fs.chmod(binaryPath, 0o755); + // npm's latest tag is ahead of the native channel, as during a staggered release. + const npmView = ChildProcessSpawner.make((command) => { + if (!ChildProcess.isStandardCommand(command) || command.args[0] !== "view") { + return Effect.die("Version lookup must not run a provider or updater"); + } + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.encodeText(Stream.make('"0.164.0"')), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + }); + const instance = yield* CodexDriver.create({ + instanceId: ProviderInstanceId.make("codex-standalone-latest"), + displayName: "Codex standalone", + enabled: false, + environment: [], + config: { ...CodexDriver.defaultConfig(), binaryPath, homePath: home }, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, npmView), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + request.url === "https://releases.openai.com/codex/channels/latest" + ? Response.json({ tag_name: "rust-v0.163.0", assets: [] }) + : new Response(null, { status: 404 }), + ), + ), + ), + ), + ); + const capabilities = yield* instance.snapshot.resolveMaintenance(); + expect(capabilities.update?.lockKey).toBe("codex-native"); + + const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe( + Effect.provideServiceEffect( + ProviderLatestVersions.ProviderLatestVersions, + ProviderLatestVersions.make(), + ), + ); + expect(latestVersion).toBe("0.163.0"); + expect( + createProviderVersionAdvisory({ + driver: CodexDriver.driverKind, + currentVersion: "0.163.0", + latestVersion, + maintenanceCapabilities: capabilities, + }).status, + ).not.toBe("behind_latest"); + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); it.effect("uses each instance's environment CODEX_HOME for continuation", () => @@ -494,7 +570,36 @@ it.layer(layerTest)("CodexDriver", (it) => { }); expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`); } - }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), + ); + + it.effect.skipIf(windowsHost)( + "shares state from the environment CODEX_HOME in a shadow home", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs + .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" }) + .pipe(Effect.flatMap((directory) => fs.realPath(directory))); + const codexHome = NodePath.join(tempDir, "custom-codex"); + const shadowHome = NodePath.join(tempDir, "shadow"); + yield* fs.makeDirectory(codexHome, { recursive: true }); + yield* fs.writeFileString(NodePath.join(codexHome, "config.toml"), 'model = "custom"\n'); + const instance = yield* CodexDriver.create({ + instanceId: ProviderInstanceId.make("env-shadow"), + displayName: "env-shadow", + enabled: false, + environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }], + config: { ...CodexDriver.defaultConfig(), shadowHomePath: shadowHome }, + }).pipe(Effect.provideService(HostProcess.HomeDirectory, NodePath.join(tempDir, "user"))); + expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`); + expect(yield* fs.readLink(NodePath.join(shadowHome, "config.toml"))).toBe( + NodePath.join(codexHome, "config.toml"), + ); + expect(yield* fs.readLink(NodePath.join(shadowHome, "sessions"))).toBe( + NodePath.join(codexHome, "sessions"), + ); + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); for (const fixture of [ @@ -570,10 +675,7 @@ it.layer(layerTest)("CodexDriver", (it) => { } else { expect(update).toBeNull(); } - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); } @@ -627,6 +729,7 @@ it.layer(layerTest)("CodexDriver", (it) => { const shimDir = NodePath.join(tempDir, fixture.dataRoot, "shims"); const npmPrefix = NodePath.join(tempDir, "mise", "installs", "node", "24.13.0"); const npmBin = NodePath.join(npmPrefix, "bin"); + const npmPath = NodePath.join(npmBin, "npm"); const npmEntry = NodePath.join( npmPrefix, "lib", @@ -636,7 +739,7 @@ it.layer(layerTest)("CodexDriver", (it) => { "bin", "codex.js", ); - for (const file of [brewPath, misePath, npmEntry]) { + for (const file of [brewPath, misePath, npmPath, npmEntry]) { yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true }); yield* fs.writeFileString(file, "#!/bin/sh\n"); yield* fs.chmod(file, 0o755); @@ -651,12 +754,20 @@ it.layer(layerTest)("CodexDriver", (it) => { ].join(NodePath.delimiter); const probes: Array> = []; const metadataSpawner = ChildProcessSpawner.make((command) => { - if (!ChildProcess.isStandardCommand(command) || command.command !== brewPath) { + const isNpmOutdated = + ChildProcess.isStandardCommand(command) && + command.command === npmPath && + command.args[0] === "outdated"; + if ( + !ChildProcess.isStandardCommand(command) || + (command.command !== brewPath && !isNpmOutdated) + ) { return Effect.die("Provider resolution must not execute a provider or updater"); } - probes.push(command.args.map(String)); - const stdout = - command.args[0] === "--prefix" + if (!isNpmOutdated) probes.push(command.args.map(String)); + const stdout = isNpmOutdated + ? JSON.stringify({ "@openai/codex": { latest: "0.153.4" } }) + : command.args[0] === "--prefix" ? brewPrefix : JSON.stringify({ formulae: [{ versions: { stable: "2026.9.1" } }] }); return Effect.succeed( @@ -722,7 +833,57 @@ it.layer(layerTest)("CodexDriver", (it) => { } else { expect(capabilities.update).toBeNull(); } - }).pipe(Effect.scoped), + }), { skip: windowsHost }, ); + + it.effect("probes again when auth.json in the Codex home changes", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const codexHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-auth-watch-" }); + const watchedPath = yield* Deferred.make(); + const homeEvents = yield* Queue.unbounded(); + const probes = yield* Queue.unbounded(); + yield* CodexDriver.create({ + instanceId: ProviderInstanceId.make("codex-auth-watch"), + displayName: "Codex auth watch", + enabled: true, + environment: [], + config: { ...CodexDriver.defaultConfig(), homePath: codexHome }, + }).pipe( + // OS watchers can miss events written right after they start, so the test supplies them. + Effect.provideService(FileSystem.FileSystem, { + ...fs, + watch: (path) => + Stream.unwrap( + Deferred.succeed(watchedPath, path).pipe(Effect.as(Stream.fromQueue(homeEvents))), + ), + }), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + (ChildProcess.isStandardCommand(command) && command.args.includes("app-server") + ? Queue.offer(probes, undefined) + : Effect.void + ).pipe( + Effect.andThen( + PlatformError.badArgument({ + module: "ChildProcessSpawner", + method: "spawn", + description: "The fixture has no Codex executable", + }), + ), + ), + ), + ), + ); + expect(yield* Deferred.await(watchedPath)).toBe(codexHome); + yield* Queue.take(probes); + + yield* Queue.offer(homeEvents, { _tag: "Update", path: "auth.json" }); + yield* TestClock.adjust("250 millis"); + + yield* Queue.take(probes); + }), + ); }); diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index dee8a04aee..03245ba46d 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -1,12 +1,16 @@ +import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import type * as Signature from "effect/crypto/Signature"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; -import { HttpClient } from "effect/http"; +import * as Stream from "effect/Stream"; +import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import type * as CodexUsageHistory from "../../usage/CodexUsageHistory.ts"; @@ -25,7 +29,7 @@ import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts"; import { checkCodexProviderStatus, makePendingCodexProvider, - probeCodexSkillsForCwd, + makeCodexSkillsProbe, withCodexAppServerClient, } from "../CodexProvider.ts"; import { resolveCodexLaunchArgs } from "../codexLaunchArgs.ts"; @@ -40,6 +44,7 @@ import { makeCachedProviderMaintenanceResolution, makePackageManagedProviderMaintenanceResolver, resolveProviderMaintenanceCapabilitiesEffect, + type ProviderMaintenanceCapabilities, } from "@t3tools/provider-core/server/maintenanceResolver"; import { haveProviderSnapshotSettingsChanged, @@ -96,6 +101,31 @@ function makeCodexMaintenanceResolver(sharedHomePath: string) { }); } +// `codex update` installs this channel's release, which can lag npm's latest tag. +const CODEX_NATIVE_CHANNEL = "https://releases.openai.com/codex/channels/latest"; +const CodexNativeRelease = Schema.Struct({ tag_name: Schema.String }); + +function withCodexNativeLatestVersion( + capabilities: ProviderMaintenanceCapabilities, + http: HttpClient.HttpClient, +): ProviderMaintenanceCapabilities { + if (capabilities.update?.lockKey !== `${DRIVER_KIND}-native`) return capabilities; + return { + ...capabilities, + latestVersion: null, + latestVersionCacheKey: CODEX_NATIVE_CHANNEL, + lookupLatestVersion: http.get(CODEX_NATIVE_CHANNEL).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.json), + Effect.flatMap(Schema.decodeUnknownEffect(CodexNativeRelease)), + Effect.map((release) => /^rust-v(\d+\.\d+\.\d+)$/.exec(release.tag_name)?.[1] ?? null), + Effect.timeoutOption("4 seconds"), + Effect.map(Option.getOrNull), + Effect.orElseSucceed(() => null), + ), + }; +} + export type CodexDriverEnv = | CodexAdapterV2DriverEnv | ProviderHost.ProviderHost @@ -160,11 +190,11 @@ export const CodexDriver: ProviderDriver< yield* HostProcess.Environment, ); const environmentHome = processEnv.CODEX_HOME; - const homeLayout = yield* resolveCodexHomeLayout( - !config.homePath.trim() && !config.shadowHomePath.trim() && environmentHome?.trim() + const homeConfig = + !config.homePath.trim() && environmentHome?.trim() ? { ...config, homePath: environmentHome } - : config, - ); + : config; + const homeLayout = yield* resolveCodexHomeLayout(homeConfig); const continuationIdentity = codexContinuationIdentity(homeLayout); const stampIdentity = withInstanceIdentity({ instanceId, @@ -190,7 +220,7 @@ export const CodexDriver: ProviderDriver< binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory), homePath: homeLayout.effectiveHomePath ?? "", } satisfies CodexSettings; - const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( + const resolveInstallation = yield* makeCachedProviderMaintenanceResolution( resolveProviderMaintenanceCapabilitiesEffect( makeCodexMaintenanceResolver(homeLayout.sharedHomePath), { @@ -203,6 +233,10 @@ export const CodexDriver: ProviderDriver< Effect.provideService(Path.Path, pathService), ), ); + const resolveMaintenance: typeof resolveInstallation = (options) => + resolveInstallation(options).pipe( + Effect.map((capabilities) => withCodexNativeLatestVersion(capabilities, httpClient)), + ); const orchestrationAdapter = yield* createCodexAdapterV2( { @@ -211,10 +245,13 @@ export const CodexDriver: ProviderDriver< accentColor, environment, enabled, - config, + config: homeConfig, }, { onUsageLimits: (update) => snapshot.applyUsageLimits(update), + models: Effect.suspend(() => snapshot.getSnapshot).pipe( + Effect.map((value) => value.models), + ), compatibility: installation.compatibility, }, ).pipe( @@ -284,22 +321,21 @@ export const CodexDriver: ProviderDriver< processEnv, snapshot.getSnapshot.pipe(Effect.map((value) => value.models)), ); + const probeSkills = yield* makeCodexSkillsProbe().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); const snapshotForCwd = (cwd: string) => !effectiveConfig.enabled ? snapshot.getSnapshot : Effect.all([ snapshot.getSnapshot, - probeCodexSkillsForCwd({ + probeSkills({ binaryPath: effectiveConfig.binaryPath, homePath: effectiveConfig.homePath, launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), cwd, environment: processEnv, - }).pipe( - Effect.scoped, - Effect.timeout("20 seconds"), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ), + }).pipe(Effect.timeout(resolveProviderProbeTimeoutMs("codex", 20_000, processEnv))), ]).pipe( Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })), Effect.mapError( @@ -345,32 +381,37 @@ export const CodexDriver: ProviderDriver< cause, }), ), - // The windows just changed; re-probe so the snapshot says so. A - // failed probe republishes the pre-redemption limits rather than - // marking them failed, so "confirmed" means `checkedAt` moved past - // what was published before the redemption started. Effect.tap((outcome) => - Effect.gen(function* () { - const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt; - const refreshed = yield* snapshot.refresh; - const after = refreshed.usageLimits?.checkedAt; - if ( - outcome === "reset" && - (after === undefined || - after === before || - refreshed.usageLimits?.unavailable?.reason === "probeFailed") - ) { - return yield* new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: - "The reset was applied, but Codex could not confirm the new limits. Refresh to check.", - }); - } - }), + ResetCreditCoordinator.refreshAfterRedemption({ + outcome, + getSnapshot: snapshot.getSnapshot, + refresh: snapshot.refresh, + }).pipe( + Effect.filterOrFail( + (confirmed) => confirmed, + () => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: + "The reset was applied, but Codex could not confirm the new limits. Refresh to check.", + }), + ), + ), ), ); + // `codex login` and `codex logout` rewrite auth.json outside T3. + if (effectiveConfig.enabled) { + yield* fileSystem.watch(accountKey).pipe( + Stream.filter((event) => pathService.basename(event.path) === "auth.json"), + Stream.debounce(Duration.millis(250)), + Stream.runForEach(() => snapshot.refresh.pipe(Effect.ignoreCause({ log: true }))), + Effect.catchReason("PlatformError", "NotFound", () => Effect.void), + Effect.ignoreCause({ log: true }), + Effect.forkScoped, + ); + } return { instanceId, driverKind: DRIVER_KIND, diff --git a/apps/server/src/provider/Drivers/CodexManagedProvider.ts b/apps/server/src/provider/Drivers/CodexManagedProvider.ts index ab5e7add55..f182245f88 100644 --- a/apps/server/src/provider/Drivers/CodexManagedProvider.ts +++ b/apps/server/src/provider/Drivers/CodexManagedProvider.ts @@ -242,8 +242,10 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu const resolveRuntime = runtime.auth.controller.withAccess!(runtime.resolve); // Launch settings bind the refresh command to the signed-in profile. The registry // already wraps openSession in withAccess, so resolve without re-entering it. + const models = snapshot.getSnapshot.pipe(Effect.map((value) => value.models)); const orchestrationAdapter = yield* createCodexAdapterV2(input, { onUsageLimits: (update) => snapshot.applyUsageLimits(update), + models, resolveRuntime: runtime.resolve, }).pipe( Effect.mapError( @@ -259,7 +261,7 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu const nativeGeneration = yield* makeCodexTextGeneration( config, undefined, - snapshot.getSnapshot.pipe(Effect.map((value) => value.models)), + models, resolveRuntime, ); const protect = (operation: string, effect: Effect.Effect) => diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 4d473f50c9..532233f7fa 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -129,18 +129,19 @@ const MODEL_IDS: Record = { }; // Effort and routing variants share the base model's price. -function withRateModel(record: UsageRecord): UsageRecord { - const base = record.model.replace( - /-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, - "", - ); - const rateModel = /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(record.model) +export const antigravityRateModel = (model: string) => { + const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, ""); + return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model) ? "gemini-3.5-flash" - : record.model === "gemini-3.7-flash-safety-le" + : model === "gemini-3.7-flash-safety-le" ? "gemini-3.7-flash" : base === "gemini-3-flash" ? "gemini-3-flash-preview" : base; +}; + +function withRateModel(record: UsageRecord): UsageRecord { + const rateModel = antigravityRateModel(record.model); return rateModel === record.model ? record : { ...record, rateModel }; } diff --git a/apps/server/src/provider/Drivers/claudeUsage.test.ts b/apps/server/src/provider/Drivers/claudeUsage.test.ts index 6f457f4f4c..bc10ba5b7b 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.test.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; +import { parseRateTable, priceUsage } from "../../usage/usagePricing.ts"; import { claudeUsageFormat, parseClaudeLine } from "./claudeUsage.ts"; function claudeLine(overrides: { @@ -115,7 +116,8 @@ describe("Claude advisor iterations", () => { model: "claude-fable-5-1", input_tokens: 54204, cache_read_input_tokens: 0, - cache_creation_input_tokens: 0, + cache_creation_input_tokens: 500, + cache_creation: { ephemeral_5m_input_tokens: 200, ephemeral_1h_input_tokens: 300 }, output_tokens: 4229, }, { @@ -160,10 +162,11 @@ describe("Claude advisor iterations", () => { totals: { uncachedInputTokens: 54204, cachedInputTokens: 0, - cacheCreationTokens: 0, + cacheCreationTokens: 500, outputTokens: 4229, reasoningTokens: 0, }, + cacheCreation1hTokens: 300, dedupeKey: expect.any(String), }, ]; @@ -216,3 +219,44 @@ describe("Claude advisor iterations", () => { expect(parse(unusable).map((record) => record.model)).toEqual(["claude-opus-5-5"]); }); }); + +describe("Claude cache write pricing", () => { + it("prices one-hour cache writes at the one-hour rate and the rest at the five-minute rate", () => { + const model = "claude-opus-4-5-20251101"; + const rates = parseRateTable({ + [model]: { + litellm_provider: "anthropic", + input_cost_per_token: 5e-6, + output_cost_per_token: 25e-6, + cache_read_input_token_cost: 5e-7, + cache_creation_input_token_cost: 6.25e-6, + cache_creation_input_token_cost_above_1hr: 1e-5, + }, + }); + const [record] = parseClaudeLine( + JSON.stringify({ + type: "assistant", + timestamp: "2026-08-07T04:05:13.944Z", + sessionId: "s", + message: { + id: "msg_ttl", + model, + usage: { + input_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 1_000_000, + cache_creation: { + ephemeral_5m_input_tokens: 400_000, + ephemeral_1h_input_tokens: 600_000, + }, + output_tokens: 0, + }, + }, + }), + ); + + if (record === undefined) throw new Error("expected a usage record"); + // 0.4M x $6.25/M + 0.6M x $10/M + expect(priceUsage(rates, record).costUsd).toBeCloseTo(8.5, 9); + }); +}); diff --git a/apps/server/src/provider/Drivers/claudeUsage.ts b/apps/server/src/provider/Drivers/claudeUsage.ts index aca7696d31..713b358842 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.ts @@ -16,9 +16,9 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; export const CLAUDE_SYNTHETIC_MODEL = ""; /** - * T3 Code writes one record per assistant *content block*, and every one of those records repeats - * the same complete `usage` object for the parent message. Summing them overcounts by roughly - * 2.4x on a real workload, so the caller must drop repeats by `dedupeKey` and keep the first. + * Claude Code repeats a message's `dedupeKey` for each assistant content block. + * Subagent blocks can progress from stream-start to final usage, so callers + * must count each key once using the maximum of each token channel. */ export function parseClaudeLine(line: string): readonly UsageRecord[] { let parsed: unknown; @@ -30,6 +30,13 @@ export function parseClaudeLine(line: string): readonly UsageRecord[] { return parseClaudeRecord(parsed); } +function cacheCreation1h(usage: Record): { cacheCreation1hTokens?: number } { + const split = usage["cache_creation"]; + if (typeof split !== "object" || split === null) return {}; + const tokens = tokenCount((split as Record)["ephemeral_1h_input_tokens"]); + return tokens > 0 ? { cacheCreation1hTokens: tokens } : {}; +} + function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { if (typeof parsed !== "object" || parsed === null) return []; @@ -70,6 +77,7 @@ function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { // Anthropic folds thinking tokens into output and does not break them out. reasoningTokens: 0, }, + ...cacheCreation1h(usageRecord), reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null, speed: usageRecord["speed"] === "fast" ? "fast" : "standard", dedupeKey, @@ -101,6 +109,7 @@ function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { outputTokens: tokenCount(advisor["output_tokens"]), reasoningTokens: 0, }, + ...cacheCreation1h(advisor), reportedCostUsd: null, speed: executor.speed, dedupeKey: dedupeKey === null ? null : `${dedupeKey}:advisor:${index}`, diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index 74812bafb5..1cdbe05d07 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -450,6 +450,61 @@ describe("parseCodexLine", () => { expect(state.malformedRecords).toBe(0); }); + it("bills request-ledger usage through resumed context counters and compaction", () => { + const state = initialCodexScanState(); + const request = (response_id: string, usage: unknown) => + JSON.stringify({ + type: "token_usage_record", + timestamp: "2026-08-01T05:17:45.000Z", + payload: { response_id, usage }, + }); + parseCodexLine(sessionMeta, state); + parseCodexLine(turnContext, state); + parseCodexLine(counted(counters(100, 20), counters(1000, 200)), state); + // Resume restores older context counters, while the request ledger continues. + expect( + parseCodexLine(request("response-1", counters(80, 10)), state)?.totals.outputTokens, + ).toBe(10); + expect(parseCodexLine(counted(counters(80, 10), counters(580, 110)), state)).toBeNull(); + // Rate-limit refreshes repeat the snapshot without another request. + expect(parseCodexLine(counted(counters(80, 10), counters(580, 110)), state)).toBeNull(); + expect( + parseCodexLine(request("compaction", counters(90, 15)), state)?.totals.outputTokens, + ).toBe(15); + parseCodexLine(turnContext, state); + expect( + parseCodexLine(counted({ ...counters(0, 0), total_tokens: 40 }, counters(580, 110)), state), + ).toBeNull(); + expect(parseCodexLine(request("response-2", counters(30, 5)), state)?.totals.outputTokens).toBe( + 5, + ); + expect(parseCodexLine(counted(counters(30, 5), counters(610, 115)), state)).toBeNull(); + expect(state.malformedRecords).toBe(0); + // A later turn from an older CLI can still report usage through snapshots alone. + parseCodexLine(turnContext, state); + expect( + parseCodexLine(counted(counters(20, 2), counters(630, 117)), state)?.totals.outputTokens, + ).toBe(2); + expect( + parseCodexLine(request("interrupted", counters(40, 4)), state)?.totals.outputTokens, + ).toBe(4); + parseCodexLine(turnContext, state); + expect( + parseCodexLine(counted(counters(10, 1), counters(680, 122)), state)?.totals.outputTokens, + ).toBe(1); + expect(parseCodexLine(request("", counters(15, 3)), state)).toBeNull(); + parseCodexLine(turnContext, state); + const transition = parseCodexRecords(request("upgraded", counters(25, 5)), state); + expect(transition.map((record) => record.totals.outputTokens)).toEqual([3, 5]); + expect(parseCodexLine(counted(counters(25, 5), counters(720, 130)), state)).toBeNull(); + expect(parseCodexLine(request("", counters(10, 1)), state)).toBeNull(); + expect( + parseCodexLine(counted(counters(10, 1), counters(730, 131)), state)?.totals.outputTokens, + ).toBe(1); + expect(parseCodexLine(counted(counters(10, 1), counters(730, 131)), state)).toBeNull(); + expect(state.malformedRecords).toBe(0); + }); + it("does not bill a context-window estimate or lose the following real request", () => { const state = initialCodexScanState(); parseCodexLine(turnContext, state); @@ -498,6 +553,134 @@ describe("parseCodexLine", () => { expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); }); + const later = (line: string) => line.replace("05:17:49.919Z", "07:17:49.919Z"); + it.each([ + { + name: "bills a later request that continues from an earlier snapshot", + tail: [ + later(counted(counters(20, 4), counters(130, 26))), + later(counted(counters(5, 1), counters(135, 27))), + ], + processed: [120, 12, 35, 24, 6], + skipped: 0, + }, + { + name: "does not bill a re-emitted earlier snapshot again", + tail: [counted(counters(10, 2), counters(110, 22))], + processed: [120, 12, 35, 0], + skipped: 1, + }, + ])("$name when cumulative counters rewind", ({ tail, processed, skipped }) => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + const billed = [ + counted(counters(100, 20), counters(100, 20)), + counted(counters(10, 2), counters(110, 22)), + counted(counters(30, 5), counters(140, 27)), + ...tail, + ].map((line) => { + const record = parseCodexLine(line, state); + return record === null ? 0 : totalTokens(record.totals); + }); + + expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + processed, + skipped, + }); + }); + + const at = (time: string, line: string) => line.replace("05:17:49.919Z", `${time}.000Z`); + const anonymousRequest = (time: string, usage: unknown) => + JSON.stringify({ + type: "token_usage_record", + timestamp: `2026-08-01T${time}.000Z`, + payload: { usage }, + }); + it.each([ + { + name: "does not bill an older snapshot re-emitted after requests without cumulative counters", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4))), + at("10:00:10", counted(counters(30, 6))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + ], + processed: [120, 24, 36, 0], + skipped: 1, + }, + { + name: "bills a rewind that follows a request without cumulative counters", + lines: [ + at("10:00:00", counted(counters(100, 20))), + at("10:00:10", counted(counters(20, 4), counters(60, 12))), + ], + processed: [120, 24], + skipped: 0, + }, + { + name: "keeps the baseline when it rejects an older snapshot, so the replay that follows is not billed", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + at("10:00:10", counted(counters(30, 6), counters(150, 30))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + at("10:00:10", counted(counters(30, 6), counters(150, 30))), + ], + processed: [120, 24, 36, 0, 0], + skipped: 1, + }, + { + name: "keeps the baseline when it rejects a lower snapshot from the baseline's own time", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:00", counted(counters(20, 4), counters(120, 24))), + at("10:00:00", counted(counters(30, 6), counters(150, 30))), + at("10:00:00", counted(counters(20, 4), counters(120, 24))), + at("10:00:00", counted(counters(30, 6), counters(150, 30))), + ], + processed: [120, 24, 36, 0, 0], + skipped: 1, + }, + { + name: "does not bill replayed snapshots against a cached baseline of unknown age", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + at("10:00:10", counted(counters(30, 6), counters(150, 30))), + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + ], + undatedAfter: 3, + processed: [120, 24, 36, 0, 0], + skipped: 1, + }, + { + name: "warns about the anonymous request a rewound snapshot does not report", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + anonymousRequest("10:00:05", counters(40, 8)), + anonymousRequest("10:00:06", counters(20, 4)), + at("10:00:07", counted(counters(20, 4), counters(60, 12))), + at("10:00:08", counted(counters(10, 2), counters(70, 14))), + ], + processed: [120, 0, 0, 24, 12], + skipped: 1, + }, + ])("$name", ({ lines, undatedAfter, processed, skipped }) => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + const billed = lines.map((line, index) => { + if (index === undatedAfter) delete state.latestCumulativeAtMs; + const record = parseCodexLine(line, state); + return record === null ? 0 : totalTokens(record.totals); + }); + + expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + processed, + skipped, + }); + }); + it("ignores a replay of the current sequence's first request without rewinding the baseline", () => { const state = initialCodexScanState(); parseCodexLine(turnContext, state); diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index 90f7c78b84..a2977d3080 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -54,9 +54,15 @@ function readCodexTokenUsage(value: unknown): CodexTokenUsage | null { return isCodexTokenUsage(usage) ? usage : null; } +// Every move of the baseline dates it, so an older snapshot re-emitted later is never a rewind. +function dateCodexBaseline(state: CodexScanState, timestampMs: number) { + state.latestCumulativeAtMs = Math.max(state.latestCumulativeAtMs ?? timestampMs, timestampMs); +} + // A zeroed baseline rebases the counters, so the sequence start measured against it is forgotten. -function rebaseCodexUsage(state: CodexScanState, cumulative: CodexTokenUsage) { +function rebaseCodexUsage(state: CodexScanState, cumulative: CodexTokenUsage, timestampMs: number) { state.lastCumulativeUsage = cumulative; + dateCodexBaseline(state, timestampMs); delete state.unreportedRequests; if (cumulative.input_tokens + cumulative.output_tokens === 0) delete state.sequenceStartSignature; } @@ -111,6 +117,18 @@ function unreportedRequests( ); } +// A rewound snapshot vouches only for the request it reports, so the anonymous requests read before +// it can be neither billed nor ruled out as that request's prefix. +function discardedRequests( + pending: readonly CodexUnreportedRequest[] | undefined, + last: CodexTokenUsage, +) { + const final = pending?.at(-1); + if (pending === undefined || final === undefined) return 0; + const reported = CODEX_USAGE_FIELDS.every((key) => final.usage[key] === last[key]); + return pending.length - (reported ? 1 : 0); +} + /** * Codex `token_count` events carry no model or service tier, so both are carried forward: the model * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`. @@ -121,12 +139,14 @@ export const CodexScanState = Schema.Struct({ sessionId: Schema.mutableKey(Schema.String), lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)), lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)), - // Optional so scan states cached before this field existed stay valid. + // Optional so scan states cached before these fields existed stay valid. sequenceStartSignature: Schema.mutableKey(Schema.optionalKey(Schema.String)), + latestCumulativeAtMs: Schema.mutableKey(Schema.optionalKey(Schema.Finite)), // `token_usage_record` usage since the last cumulative snapshot, one entry per record. unreportedRequests: Schema.mutableKey( Schema.optionalKey(Schema.mutable(Schema.Array(CodexUnreportedRequest))), ), + requestLedgerActive: Schema.mutableKey(Schema.optionalKey(Schema.Boolean)), malformedRecords: Schema.mutableKey(TokenCount), sawSessionMeta: Schema.mutableKey(Schema.Boolean), modelProvider: Schema.mutableKey(Schema.String), @@ -181,8 +201,8 @@ function isForkCopy(state: CodexScanState, timestampMs: number): boolean { } /** - * Cumulative counters validate request deltas. Older events without cumulative counters use - * normalized consecutive-request deduplication. + * Identified request-ledger entries report spending independently of context snapshots. + * Legacy snapshots validate request deltas against cumulative counters. */ export function parseCodexLine(line: string, state: CodexScanState): readonly UsageRecord[] { let parsed: unknown; @@ -221,6 +241,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag } if (record["type"] === "turn_context") { + state.requestLedgerActive = false; if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"]; // Model carry is useful for usage, but history recovery needs this context's own identity. state.turnId = @@ -232,13 +253,32 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag return []; } - // Several of these may sit between two snapshots, so they only explain a gap in the counters. + // Request ledgers include spending that context snapshots can omit. if (record["type"] === "token_usage_record") { const timestampMs = parseTimestampMs(record["timestamp"]); const usage = readCodexTokenUsage(payloadRecord["usage"]); if (timestampMs === null || usage === null || state.model.length === 0) return []; // Copied history is already billed in the parent. if (isForkCopy(state, timestampMs)) return []; + const responseId = payloadRecord["response_id"]; + if (typeof responseId === "string" && responseId.length > 0) { + const pending = state.unreportedRequests ?? []; + state.requestLedgerActive = true; + for (const request of pending) { + state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, request.usage); + } + state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, usage); + dateCodexBaseline(state, timestampMs); + delete state.unreportedRequests; + return [ + ...pending.map((request) => codexRequestRecord(state, request.usage, request)), + { + ...codexRequestRecord(state, usage, codexAttribution(state, timestampMs)), + dedupeKey: JSON.stringify(["codex", state.sessionId, responseId]), + }, + ]; + } + state.requestLedgerActive = false; (state.unreportedRequests ??= []).push({ ...codexAttribution(state, timestampMs), usage }); return []; } @@ -270,18 +310,26 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag if (isForkCopy(state, timestampMs)) { // Copied history is already billed in the parent, but establishes the child's baseline. const signature = last === null ? null : JSON.stringify(last); - if (cumulative !== null) rebaseCodexUsage(state, cumulative); + if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs); else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) { state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last); + dateCodexBaseline(state, timestampMs); } state.lastUsageSignature = signature; return []; } + // Context snapshots can rewind on resume and omit compaction spending; identified requests are authoritative. + if (state.requestLedgerActive) { + if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs); + return []; + } + const previous = state.lastCumulativeUsage; + const latestCumulativeAtMs = state.latestCumulativeAtMs; const pending = state.unreportedRequests; // A valid snapshot remains the next baseline even when its paired request is malformed. - if (cumulative !== null) rebaseCodexUsage(state, cumulative); + if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs); if (last === null || (hasCumulative && cumulative === null)) { state.malformedRecords += 1; return []; @@ -316,12 +364,20 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // Only the same event is a replay; a later request can restart with identical counters. if (restarted && sequenceStart === state.sequenceStartSignature) { state.lastCumulativeUsage = previous; + // The retained baseline keeps its own age; one of unknown age must not take the replay's. + if (latestCumulativeAtMs === undefined) delete state.latestCumulativeAtMs; return []; } - // Forks and paginated continuations can inherit totals without copying a counter snapshot. - // Only bill the latest request, and require the unseen prefix to be valid usage too. + // Forks and paginated continuations can inherit totals without copying a counter snapshot, and + // a later request can continue from an earlier snapshot; a re-emitted old snapshot is not later. + // Only bill the latest request, and require the unseen prefix to be valid usage too. A baseline + // of unknown age (a scan state cached before every move dated it) cannot order the snapshot. + const lowered = + previous !== null && CODEX_USAGE_FIELDS.some((key) => cumulative[key] < previous[key]); + const rewound = + lowered && latestCumulativeAtMs !== undefined && timestampMs > latestCumulativeAtMs; const reconciled = - previous === null + previous === null || rewound ? readCodexTokenUsage( Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, cumulative[key] - last[key]])), ) !== null @@ -329,10 +385,24 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag if (!restarted && !reconciled) { const bridged = unreportedRequests(previous, cumulative, last, pending); if (bridged === null) { + // A rejected snapshot from before the baseline's time is a replay, not the next baseline. + // At the baseline's own time only lower counters are one; zeroed counters still rebase. + const replayed = + latestCumulativeAtMs !== undefined && + (timestampMs < latestCumulativeAtMs || + (timestampMs === latestCumulativeAtMs && + lowered && + cumulative.input_tokens + cumulative.output_tokens > 0)); + if (replayed) { + state.lastCumulativeUsage = previous; + if (pending !== undefined) state.unreportedRequests = pending; + } state.malformedRecords += 1; return []; } unreported = bridged; + } else if (!restarted && rewound) { + state.malformedRecords += discardedRequests(pending, last); } if (restarted) state.sequenceStartSignature = sequenceStart; } else { @@ -344,6 +414,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag return []; } state.lastCumulativeUsage = advanced; + dateCodexBaseline(state, timestampMs); } state.lastUsageSignature = signature; @@ -418,6 +489,7 @@ export const codexUsageFormat: TranscriptUsageFormat = { session_id: true, model_provider: true, turn_id: true, + response_id: true, model: true, thread_settings: { service_tier: true }, forked_from_id: true, @@ -481,10 +553,7 @@ export const codexUsageReader: ProviderUsageReader< const path = yield* Path.Path; const environmentHome = environment.CODEX_HOME?.trim(); const layout = yield* resolveCodexHomeLayout( - config.setupMode !== "managed" && - !config.homePath.trim() && - !config.shadowHomePath.trim() && - environmentHome + config.setupMode !== "managed" && !config.homePath.trim() && environmentHome ? { ...config, homePath: environmentHome } : config, ); diff --git a/apps/server/src/provider/EventNdjsonLogger.test.ts b/apps/server/src/provider/EventNdjsonLogger.test.ts index 3cb7870f3f..0bb55b9bcb 100644 --- a/apps/server/src/provider/EventNdjsonLogger.test.ts +++ b/apps/server/src/provider/EventNdjsonLogger.test.ts @@ -120,42 +120,6 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { }), ); - it.effect("shares one thread writer across native and canonical streams", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - - try { - const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 }); - const native = store.logger("native"); - const canonical = store.logger("canonical"); - const threadId = ThreadId.make("thread-shared"); - - yield* native.write({ id: "native-event" }, threadId); - yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId); - yield* store.close(); - - const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-shared"), "utf8") - .trim() - .split("\n") - .map(parseLogLine); - - assert.deepEqual( - lines.map(({ stream, payload }) => ({ stream, payload })), - [ - { stream: "NTIVE", payload: '{"id":"native-event"}' }, - { - stream: "CANON", - payload: '{"type":"item.completed","id":"canonical-event"}', - }, - ], - ); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - it.effect("keeps long thread ids that share a prefix in separate files", () => Effect.gen(function* () { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); @@ -291,6 +255,65 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { }), ); + it.effect("drops Cursor streaming deltas while keeping its lifecycle updates", () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); + const basePath = NodePath.join(tempDir, "events.log"); + const threadId = ThreadId.make("cursor-deltas"); + const cursorUpdate = (update: object) => ({ + provider: "cursor", + kind: "protocol", + event: { + direction: "incoming", + stage: "decoded", + payload: { type: "interaction.update", runId: "run-1", update }, + }, + }); + const toolCall = { type: "shell", args: { command: "ls" } }; + const transient = [ + { type: "text-delta", text: "Hel" }, + { type: "thinking-delta", text: "Hmm" }, + { type: "token-delta", tokens: 3 }, + { type: "shell-output-delta", event: { stdout: "a.ts\n" } }, + { type: "partial-tool-call", callId: "call-1", modelCallId: "m-1", toolCall }, + { + type: "tool-call-delta", + callId: "call-1", + modelCallId: "m-1", + taskUpdate: { type: "text-delta", text: "Sub" }, + }, + ].map(cursorUpdate); + const retained = [ + { type: "tool-call-started", callId: "call-1", modelCallId: "m-1", toolCall }, + { + type: "tool-call-delta", + callId: "call-1", + modelCallId: "m-1", + taskUpdate: { type: "tool-call-completed", callId: "call-2", toolCall }, + }, + { type: "tool-call-completed", callId: "call-1", modelCallId: "m-1", toolCall }, + { type: "turn-ended" }, + ].map(cursorUpdate); + + try { + const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 }); + const native = store.logger("native"); + for (const event of [...transient, ...retained]) { + yield* native.write(event, threadId); + } + yield* store.close(); + + const records = NodeFS.readFileSync(ownedLogPath(basePath, "cursor-deltas"), "utf8") + .trim() + .split("\n") + .map((line) => decodeUnknownJson(parseLogLine(line).payload)); + assert.deepEqual(records, retained); + } finally { + NodeFS.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + it.effect("bounds oversized records while retaining failure details", () => Effect.gen(function* () { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); diff --git a/apps/server/src/provider/EventNdjsonLogger.ts b/apps/server/src/provider/EventNdjsonLogger.ts index 6a1d3844b2..5a7b357857 100644 --- a/apps/server/src/provider/EventNdjsonLogger.ts +++ b/apps/server/src/provider/EventNdjsonLogger.ts @@ -63,6 +63,13 @@ const transientNativeMethods = new Set([ "turn/diff/updated", ]); const transientAcpUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]); +const transientCursorUpdates = new Set([ + "text-delta", + "thinking-delta", + "token-delta", + "shell-output-delta", + "partial-tool-call", +]); export type EventNdjsonStream = "native" | "canonical" | "orchestration"; @@ -219,6 +226,18 @@ export function shouldPersistProviderEvent(stream: EventNdjsonStream, event: unk } } + if (nativeType === "interaction.update") { + let update = Reflect.get(nativeEvent, "update"); + if (typeof update !== "object" || update === null) return true; + // Subagent updates arrive wrapped; keep the wrapper when it carries a lifecycle record. + if (Reflect.get(update, "type") === "tool-call-delta") { + update = Reflect.get(update, "taskUpdate"); + if (typeof update !== "object" || update === null) return true; + } + const updateType = Reflect.get(update, "type"); + return typeof updateType !== "string" || !transientCursorUpdates.has(updateType); + } + const payload = Reflect.get(nativeEvent, "payload"); if (typeof payload !== "object" || payload === null) return true; diff --git a/apps/server/src/provider/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.ts index 9be799112c..3f28649f49 100644 --- a/apps/server/src/provider/GrokProvider.test.ts +++ b/apps/server/src/provider/GrokProvider.test.ts @@ -478,8 +478,8 @@ describe("Grok usage limits", () => { }; it("shows zero usage for complete weekly and monthly periods with no percentage", () => { - for (const [currentPeriod, kind, label, resetsAt] of [ - [weeklyPeriod, "weekly", "Weekly", "2026-09-18T03:10:30.159Z"], + for (const [currentPeriod, kind, label, resetsAt, windowDurationMins] of [ + [weeklyPeriod, "weekly", "Weekly", "2026-09-18T03:10:30.159Z", 7 * 24 * 60], [ { type: "USAGE_PERIOD_TYPE_MONTHLY", @@ -489,12 +489,15 @@ describe("Grok usage limits", () => { "monthly", "Monthly", "2026-10-01T00:00:00.000Z", + 30 * 24 * 60, ], ] as const) { const response = { config: { currentPeriod } }; expect .soft(grokUsageResponseToLimits(response, checkedAt).windows) - .toEqual([{ id: "subscription", kind, label, usedPercent: 0, resetsAt }]); + .toEqual([ + { id: "subscription", kind, label, usedPercent: 0, resetsAt, windowDurationMins }, + ]); } }); @@ -551,6 +554,60 @@ describe("Grok usage limits", () => { ).windows, ).toEqual([{ id: "subscription", kind: "monthly", label: "Monthly", usedPercent: 100 }]); }); + + it("measures the window from the reported period bounds", () => { + const window = (type: string, start: string, end: string) => + grokUsageResponseToLimits( + { config: { creditUsagePercent: 4, currentPeriod: { type, start, end } } }, + checkedAt, + ).windows[0]; + expect( + window( + "USAGE_PERIOD_TYPE_WEEKLY", + "2026-10-14T20:51:37.352+00:00", + "2026-10-21T20:51:37.352+00:00", + ), + ).toEqual({ + id: "subscription", + kind: "weekly", + label: "Weekly", + usedPercent: 4, + resetsAt: "2026-10-21T20:51:37.352Z", + windowDurationMins: 7 * 24 * 60, + }); + expect( + window( + "USAGE_PERIOD_TYPE_MONTHLY", + "2026-02-01T00:00:00.000+00:00", + "2026-03-01T00:00:00.000+00:00", + )?.windowDurationMins, + ).toBe(28 * 24 * 60); + }); + + it("leaves the window length unknown when the period start is unusable", () => { + const end = "2026-10-21T20:51:37.352+00:00"; + for (const start of [ + undefined, + null, + 42, + "invalid", + "2026-02-30T00:00:00.000Z", + end, + "2026-10-28T20:51:37.352+00:00", + ]) { + const [window] = grokUsageResponseToLimits( + { + config: { + creditUsagePercent: 4, + currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", start, end }, + }, + }, + checkedAt, + ).windows; + expect(window?.resetsAt).toBe("2026-10-21T20:51:37.352Z"); + expect(window).not.toHaveProperty("windowDurationMins"); + } + }); }); it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("readGrokAccount", (it) => { @@ -582,7 +639,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("readGrokAccount" ), ); expect(limits.windows[0]?.usedPercent).toBe(37); - }).pipe(Effect.scoped), + }), ); it.effect( @@ -692,7 +749,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("readGrokAccount" message: "Grok could not read usage limits.", }); } - }).pipe(Effect.scoped), + }), ); it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () => diff --git a/apps/server/src/provider/ProjectSettingsOverrideSweep.ts b/apps/server/src/provider/ProjectSettingsOverrideSweep.ts index aa7d205271..06f61f9ad8 100644 --- a/apps/server/src/provider/ProjectSettingsOverrideSweep.ts +++ b/apps/server/src/provider/ProjectSettingsOverrideSweep.ts @@ -1,32 +1,41 @@ -import { type ProjectId, type ServerSettings } from "@t3tools/contracts"; +import * as NodeUtil from "node:util"; + +import { type ProjectSettingsOverrides } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as Settings from "../serverSettings.ts"; -const findOrphanedProjectIds = ( - settings: Pick, - liveProjectIds: ReadonlySet, -): ReadonlyArray => - Object.keys(settings.projectSettingsOverrides) - .map((projectId) => projectId as ProjectId) - .filter((projectId) => !liveProjectIds.has(projectId)); +export function deletedProjectOverridePatch(entry: ProjectSettingsOverrides | undefined) { + // Keep cleanup policy for deleted threads; omitting providerInstances would preserve obsolete references in the merge. + return entry?.worktreeCleanup !== undefined + ? { worktreeCleanup: entry.worktreeCleanup, providerInstances: {} } + : null; +} export const sweep = Effect.gen(function* () { const serverSettings = yield* Settings.ServerSettingsService; const projectStore = yield* ProjectStore.ProjectStoreV2; const settings = yield* serverSettings.getSettings; - const liveShells = yield* projectStore.listShells(); - const liveProjectIds = new Set(liveShells.map((shell) => shell.id)); + const projects = yield* projectStore.list({ includeDeleted: true }); + const projectsById = new Map( + projects.map((project) => [project.projectId, project]), + ); - const orphanedProjectIds = findOrphanedProjectIds(settings, liveProjectIds); - if (orphanedProjectIds.length === 0) return; + const overrides = Object.entries(settings.projectSettingsOverrides).flatMap( + ([projectId, entry]) => { + const project = projectsById.get(projectId); + if (project?.deletedAt === null) return []; + const patch = project ? deletedProjectOverridePatch(entry) : null; + if (NodeUtil.isDeepStrictEqual(entry, patch)) return []; + return [[projectId, patch] as const]; + }, + ); + if (overrides.length === 0) return; yield* serverSettings.updateSettings({ - projectSettingsOverrides: Object.fromEntries( - orphanedProjectIds.map((projectId) => [projectId, null]), - ), + projectSettingsOverrides: Object.fromEntries(overrides), }); }).pipe( Effect.asVoid, diff --git a/apps/server/src/provider/ProviderAuthService.test.ts b/apps/server/src/provider/ProviderAuthService.test.ts index 5023dc5bf4..603df5e7e4 100644 --- a/apps/server/src/provider/ProviderAuthService.test.ts +++ b/apps/server/src/provider/ProviderAuthService.test.ts @@ -743,7 +743,7 @@ it.effect("queued logout prompts resolve the current controller after provider r assert.isTrue(yield* Fiber.join(queued)); assert.isTrue(replacementLoggedOut); assert.strictEqual(harness.actions.filter((action) => action === "native-logout").length, 1); - }).pipe(Effect.scoped), + }), ); it.effect.each(["start", "logout", "prompt"] as const)( @@ -814,7 +814,7 @@ it.effect.each(["start", "logout", "prompt"] as const)( const blocked = yield* Effect.flip(harness.service.logout({ instanceId })); assert.include(blocked.detail, "shared sign-in"); assert.equal(replacementMutations, 0); - }).pipe(Effect.scoped), + }), ); it.effect.each(["selection", "drain"] as const)( @@ -855,5 +855,5 @@ it.effect.each(["selection", "drain"] as const)( assert.notInclude(harness.actions, "stop:peer-persisted"); assert.isFalse(harness.sessions.has(ThreadId.make("target-draining"))); assert.include(harness.actions, "native-logout"); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/provider/ProviderHostLive.ts b/apps/server/src/provider/ProviderHostLive.ts index 6398210599..fed07efc03 100644 --- a/apps/server/src/provider/ProviderHostLive.ts +++ b/apps/server/src/provider/ProviderHostLive.ts @@ -4,11 +4,13 @@ import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import { resolveAttachmentPath } from "../attachmentStore.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as ServerConfig from "../config.ts"; +import * as ServerLifecycleEvents from "../serverLifecycleEvents.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as DocumentText from "./DocumentText.ts"; import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; @@ -22,6 +24,10 @@ export const layer = Layer.effect( const secrets = yield* ServerSecretStore.ServerSecretStore; const digest = yield* Digest.Digest; const fileSystem = yield* FileSystem.FileSystem; + // Optional so standalone provider layers in tests probe at once. + const lifecycleEvents = yield* Effect.serviceOption( + ServerLifecycleEvents.ServerLifecycleEvents, + ); return ProviderHost.ProviderHost.of({ paths: { cwd: config.cwd, @@ -37,6 +43,10 @@ export const layer = Layer.effect( subscribe: serverSettings.subscribeChanges, }, shouldRunBackgroundWork: backgroundPolicy.shouldRunScopeWork, + ...Option.match(lifecycleEvents, { + onNone: () => ({}), + onSome: (events) => ({ awaitServerReady: events.awaitReady }), + }), resolveAttachmentPath: (attachment) => resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment }), // DocumentText owns the path-resolution span. diff --git a/apps/server/src/provider/ProviderInstallationGate.test.ts b/apps/server/src/provider/ProviderInstallationGate.test.ts new file mode 100644 index 0000000000..96d958e789 --- /dev/null +++ b/apps/server/src/provider/ProviderInstallationGate.test.ts @@ -0,0 +1,49 @@ +import { ProviderInstanceId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; + +import * as ProviderInstallationGate from "./ProviderInstallationGate.ts"; + +const INSTANCE_ID = ProviderInstanceId.make("codex"); + +it.effect("queues work that starts while an update waits for in-flight work", () => + Effect.gen(function* () { + const gate = yield* ProviderInstallationGate.ProviderInstallationGate; + const inFlightStarted = yield* Deferred.make(); + const releaseInFlight = yield* Deferred.make(); + const log: Array = []; + + const inFlight = yield* gate + .execute( + INSTANCE_ID, + Deferred.succeed(inFlightStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseInFlight)), + Effect.andThen(Effect.sync(() => log.push("in-flight work finished"))), + ), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(inFlightStarted); + // Starting immediately runs each fiber until it blocks: the update while draining in-flight + // work, by which point it holds the turnstile, and later work at the gate. + const update = yield* gate + .update( + [INSTANCE_ID], + Effect.sync(() => log.push("update ran")), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + const later = yield* gate + .execute( + INSTANCE_ID, + Effect.sync(() => log.push("later work ran")), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(releaseInFlight, undefined); + yield* Fiber.join(inFlight); + yield* Fiber.join(update); + yield* Fiber.join(later); + + assert.deepStrictEqual(log, ["in-flight work finished", "update ran", "later work ran"]); + }).pipe(Effect.provide(ProviderInstallationGate.layer)), +); diff --git a/apps/server/src/provider/ProviderInstallationGate.ts b/apps/server/src/provider/ProviderInstallationGate.ts new file mode 100644 index 0000000000..3c526f9ee8 --- /dev/null +++ b/apps/server/src/provider/ProviderInstallationGate.ts @@ -0,0 +1,73 @@ +import type { ProviderInstanceId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Semaphore from "effect/Semaphore"; + +// Executions share `room` and an update drains it. A Semaphore lets a smaller request overtake a +// waiting larger one, so an update first holds `turnstile` and new executions queue behind it. +interface InstanceGate { + readonly turnstile: Semaphore.Semaphore; + readonly room: Semaphore.Semaphore; +} + +const ROOM_PERMITS = Number.MAX_SAFE_INTEGER; + +export class ProviderInstallationGate extends Context.Service< + ProviderInstallationGate, + { + /** Runs provider work once no update of the instance's installation is running or waiting. */ + readonly execute: ( + instanceId: ProviderInstanceId, + effect: Effect.Effect, + ) => Effect.Effect; + /** Runs an installation update after the instances' in-flight work, excluding new work. */ + readonly update: ( + instanceIds: ReadonlyArray, + effect: Effect.Effect, + ) => Effect.Effect; + } +>()("t3/provider/ProviderInstallationGate") {} + +export const layer = Layer.sync(ProviderInstallationGate, () => { + // Instances are few and configured, so their gates are kept for the server's lifetime. + const gates = new Map(); + const gateFor = (instanceId: ProviderInstanceId) => + Effect.sync(() => { + const existing = gates.get(instanceId); + if (existing) return existing; + const gate = { + turnstile: Semaphore.makeUnsafe(1), + room: Semaphore.makeUnsafe(ROOM_PERMITS), + }; + gates.set(instanceId, gate); + return gate; + }); + + const execute = Effect.fn("ProviderInstallationGate.execute")(function* ( + instanceId: ProviderInstanceId, + effect: Effect.Effect, + ) { + const gate = yield* gateFor(instanceId); + yield* gate.turnstile.withPermits(1)(Effect.void); + return yield* gate.room.withPermits(1)(effect); + }); + + const update = Effect.fn("ProviderInstallationGate.update")(function* ( + instanceIds: ReadonlyArray, + effect: Effect.Effect, + ) { + // A stable order keeps two updates that share instances from deadlocking. + const instanceGates = yield* Effect.forEach(Array.from(new Set(instanceIds)).sort(), gateFor); + const drained = instanceGates.reduceRight( + (inner, gate) => gate.room.withPermits(ROOM_PERMITS)(inner), + effect, + ); + return yield* instanceGates.reduceRight( + (inner, gate) => gate.turnstile.withPermits(1)(inner), + drained, + ); + }); + + return ProviderInstallationGate.of({ execute, update }); +}); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index 9586678018..ce6416332b 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -48,9 +48,11 @@ import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistry.ts"; import { ProviderDriverError } from "./Errors.ts"; +import * as ProviderInstallationGate from "./ProviderInstallationGate.ts"; import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts"; import * as PortScanner from "../preview/PortScanner.ts"; import * as ProviderHostLive from "./ProviderHostLive.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import type { AnyProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver"; @@ -125,8 +127,12 @@ const makeTildeProviderFixtures = Effect.fn( directory: homePath, prefix: ".t3-provider-path-test-", }); + yield* fileSystem.writeFileString( + path.join(fixtureDir, "package.json"), + JSON.stringify({ type: "commonjs" }), + ); const codexPath = path.join(fixtureDir, "codex"); - const claudePath = path.join(fixtureDir, "claude"); + const claudePath = path.join(fixtureDir, "claude.mjs"); const claudeHomePath = path.join(fixtureDir, "claude-home"); const codexScriptPath = path.join(fixtureDir, "codex-script.json"); const codexFixtureDir = path.join(import.meta.dirname, "testFixtures"); @@ -200,12 +206,14 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { ), Layer.provideMerge(ProviderLatestVersions.layer), Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge(ProviderInstallationGate.layer), Layer.provideMerge(ModelManifest.layerTest), Layer.provideMerge(ResetCreditCoordinator.layerTest), ); const layerBase = ProviderHostLive.layer.pipe(Layer.provideMerge(layerBaseDeps)); const layerTest = ProviderOrchestrationAdapterInfrastructure.layer.pipe( - Layer.provide(PortScanner.layerTest), + Layer.provide(SqlitePersistence.layerMemory), + Layer.provideMerge(PortScanner.layerTest), Layer.provideMerge(layerBase), ); @@ -339,7 +347,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); - it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () => + it.effect("treats an explicit in-config enabled:false as disabling despite the envelope", () => Effect.gen(function* () { const staleId = ProviderInstanceId.make("codex_stale"); const configMap: ProviderInstanceConfigMap = { @@ -363,7 +371,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); - it.live("lists a blocked driver's instances as unavailable without running them", () => + it.effect("lists a blocked driver's instances as unavailable without running them", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("codex"); const reason = "Example Corp's policy does not allow the Codex provider."; @@ -468,6 +476,93 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); + it.live("applies the lowest maxEffortLevel across Claude's settings sources", () => + Effect.gen(function* () { + if (yield* HostProcess.isWindows) return; + + const fixtures = yield* makeTildeProviderFixtures(); + const claudeId = ProviderInstanceId.make("claude_source_effort_cap"); + const { registry } = yield* makeProviderInstanceRegistry({ + drivers: [ClaudeDriver], + configMap: { + [claudeId]: { + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + environment: [ + { + name: "T3_CLAUDE_SETTINGS_SOURCES", + // The merged `effective` settings read as exempting Opus 5; the flag tier's + // top-level cap still applies to it. + value: JSON.stringify([ + { + source: "userSettings", + settings: { modelSettings: { "claude-opus-5": { maxEffortLevel: "max" } } }, + }, + { source: "flagSettings", settings: { maxEffortLevel: "high" } }, + ]), + sensitive: false, + }, + ], + config: makeClaudeConfig({ + enabled: true, + binaryPath: fixtures.claudeBinaryPath, + homePath: fixtures.claudeHomePath, + }), + }, + }, + }); + const claude = yield* registry.getInstance(claudeId); + + const snapshot = yield* claude!.snapshot.refresh; + const maxLabel = snapshot.models + .find((model) => model.slug === "claude-opus-5") + ?.capabilities?.optionDescriptors?.flatMap((descriptor) => + descriptor.id === "effort" && descriptor.type === "select" + ? descriptor.options.filter((option) => option.id === "max") + : [], + )[0]?.label; + expect(maxLabel).toBe("Max (capped to High)"); + }).pipe(Effect.provide(layerTest)), + ); + + it.live("keeps usage and uncapped efforts when the CLI rejects get_settings", () => + Effect.gen(function* () { + if (yield* HostProcess.isWindows) return; + + const fixtures = yield* makeTildeProviderFixtures(); + const claudeId = ProviderInstanceId.make("claude_settings_unsupported"); + const { registry } = yield* makeProviderInstanceRegistry({ + drivers: [ClaudeDriver], + configMap: { + [claudeId]: { + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + environment: [{ name: "T3_CLAUDE_SETTINGS_UNSUPPORTED", value: "1", sensitive: false }], + config: makeClaudeConfig({ + enabled: true, + binaryPath: fixtures.claudeBinaryPath, + homePath: fixtures.claudeHomePath, + }), + }, + }, + }); + const claude = yield* registry.getInstance(claudeId); + + const snapshot = yield* claude!.snapshot.refresh; + const effortLabels = snapshot.models.flatMap((model) => + (model.capabilities?.optionDescriptors ?? []).flatMap((descriptor) => + descriptor.id === "effort" && descriptor.type === "select" + ? descriptor.options.map((option) => option.label) + : [], + ), + ); + expect(effortLabels).toContain("Max"); + expect(effortLabels.some((label) => label.includes("capped"))).toBe(false); + expect(snapshot.auth).toMatchObject({ status: "authenticated", email: "test@example.com" }); + expect(snapshot.usageLimits?.windows[0]?.usedPercent).toBe(100); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("scopes Claude's one-probe fallback to the logged-in organization", () => Effect.gen(function* () { if (yield* HostProcess.isWindows) return; @@ -768,7 +863,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { ); } - it.live( + it.effect( "shadows instances whose driver is not registered in this build without failing boot", () => Effect.gen(function* () { @@ -896,7 +991,7 @@ describe("ProviderInstanceRegistry secret environment", () => { { name: "BASE_URL", value: "https://example.test", sensitive: false }, ], ]); - }).pipe(Effect.scoped); + }); }); // An empty secret must not let a driver fall back to a credential the server inherited. @@ -919,7 +1014,7 @@ describe("ProviderInstanceRegistry secret environment", () => { yield* mutator.reconcile({ ...fixture.configMap }); expect(fixture.reads).toHaveLength(readsAtStartup); expect(yield* registry.listUnavailable).toHaveLength(1); - }).pipe(Effect.scoped); + }); }); it.effect("does not read the secrets of an instance its config decodes as disabled", () => { @@ -931,7 +1026,7 @@ describe("ProviderInstanceRegistry secret environment", () => { expect(fixture.reads).toEqual([]); expect(fixture.invalidated).toEqual([]); expect(fixture.created).toHaveLength(1); - }).pipe(Effect.scoped); + }); }); it.effect("re-reads secrets on reload and rebuilds only when they changed", () => { @@ -954,7 +1049,7 @@ describe("ProviderInstanceRegistry secret environment", () => { "sk-live", "sk-rotated", ]); - }).pipe(Effect.scoped); + }); }); it.effect("reads a config field typed SettingsSecretValue and rebuilds when it rotates", () => { @@ -974,7 +1069,7 @@ describe("ProviderInstanceRegistry secret environment", () => { { apiKey: "gw-live", model: "m" }, { apiKey: "gw-rotated", model: "m" }, ]); - }).pipe(Effect.scoped); + }); }); it.effect.each([ @@ -990,7 +1085,7 @@ describe("ProviderInstanceRegistry secret environment", () => { return Effect.gen(function* () { yield* fixture.make; expect(fixture.configs).toEqual([expect.objectContaining({ [field]: "provider-live" })]); - }).pipe(Effect.scoped); + }); }); it.effect("keeps a working instance live when a reload cannot read its secret", () => { @@ -1004,7 +1099,7 @@ describe("ProviderInstanceRegistry secret environment", () => { expect(yield* registry.getInstance(instanceId)).toBeDefined(); expect(yield* registry.listUnavailable).toEqual([]); expect(fixture.created).toHaveLength(1); - }).pipe(Effect.scoped); + }); }); it.effect("starts without waiting for secrets to be read", () => { @@ -1021,6 +1116,6 @@ describe("ProviderInstanceRegistry secret environment", () => { yield* PubSub.take(changes); expect(yield* registry.getInstance(instanceId)).toBeDefined(); expect(yield* registry.listUnavailable).toEqual([]); - }).pipe(Effect.scoped); + }); }); }); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index 3f4df0eb35..9ab3f56aed 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -92,9 +92,20 @@ const withoutSecretReferences = ( typeof variable.value === "string" ? [{ ...variable, value: variable.value }] : [], ); +interface CheckedSecret { + readonly reference: SecretReference; + readonly value: string; +} + +const sameReference = (a: SecretReference, b: SecretReference) => + a.provider === b.provider && a.reference === b.reference; + +// `checked` supplies its reference's value instead of the resolver, which a concurrent refresh +// may have re-read since the check. const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecrets")(function* ( driver: AnyProviderDriver | undefined, entry: ProviderInstanceConfig, + checked?: CheckedSecret, ) { const variables = entry.environment ?? []; const configFields = configSecretReferences(driver, entry); @@ -102,8 +113,15 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr ...secretReferencesIn(variables), ...configFields.map(({ reference }) => reference), ]; - const values = - references.length === 0 ? [] : yield* (yield* SecretResolver.SecretResolver).read(references); + const isChecked = (reference: SecretReference) => + checked !== undefined && sameReference(reference, checked.reference); + const toRead = references.filter((reference) => !isChecked(reference)); + const read = + toRead.length === 0 ? [] : yield* (yield* SecretResolver.SecretResolver).read(toRead); + let readIndex = 0; + const values = references.map((reference) => + isChecked(reference) ? checked?.value : read[readIndex++], + ); const unreadable: Array = []; let index = 0; // An empty secret reads as unreadable, so a driver cannot fall back to an inherited credential. @@ -130,6 +148,36 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr return { secrets, unreadable }; }); +// Replaces only the checked reference's value in the secrets a live instance already holds, so +// another reference whose read failed earlier is not read again and does not park the instance. +const carryCheckedSecret = ( + driver: AnyProviderDriver | undefined, + entry: ProviderInstanceConfig, + current: InstanceSecrets, + { reference: checked, value }: CheckedSecret, +): InstanceSecrets => { + const matches = (reference: SecretReference) => sameReference(reference, checked); + // A live instance resolved every variable in order, so slots line up with the entry's variables + // by position; names may repeat. + const variables = entry.environment ?? []; + const replacedSlots = configSecretReferences(driver, entry).filter(({ reference }) => + matches(reference), + ); + return { + environment: current.environment.map((variable, index) => { + const source = variables[index]?.value; + return source !== undefined && typeof source !== "string" && matches(source) + ? { ...variable, value } + : variable; + }), + config: current.config.map((slot) => + replacedSlots.some(({ field, key }) => field === slot.field && key === slot.key) + ? { ...slot, value } + : slot, + ), + }; +}; + /** Conflicting saved flags must preserve any explicit disable. */ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown): boolean => { const rawConfigEnabled = providerInstanceConfigEnabledFlag(entry.config); @@ -161,6 +209,7 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* { - const { driversById, parentScope, instanceId, rawInstanceId, entry, deferSecrets } = input; + const { + driversById, + parentScope, + instanceId, + rawInstanceId, + entry, + deferSecrets, + carriedSecrets, + } = input; const blocked = input.blockedReason(entry.driver); if (blocked !== undefined) { return { @@ -235,12 +292,14 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* 0) { @@ -311,9 +370,10 @@ const makeReconcile = (input: { configMap: ProviderInstanceConfigMap, rebuild?: ReadonlySet, deferSecrets?: boolean, + carried?: ReadonlyMap, ) => Effect.Effect) => { const { state, driversById, blockedReason, parentScope } = input; - return (configMap, rebuild = new Set(), deferSecrets = false) => + return (configMap, rebuild = new Set(), deferSecrets = false, carried = new Map()) => Effect.gen(function* () { const previousEntries = yield* Ref.get(state.entries); const previousUnavailable = yield* Ref.get(state.unavailable); @@ -365,6 +425,7 @@ const makeReconcile = (input: { const instanceId = ProviderInstanceId.make(rawInstanceId); const kept = previousEntries.has(instanceId) && !replacedIds.has(instanceId); return kept || + carried.has(instanceId) || parkedSnapshot(instanceId, entry) !== undefined || !(yield* isEntryEnabled(driversById, entry)) ? [] @@ -406,6 +467,7 @@ const makeReconcile = (input: { rawInstanceId, entry, deferSecrets, + carriedSecrets: carried.get(instanceId), }); if (result.kind === "live") { builtEntries.set(instanceId, result.live); @@ -503,44 +565,96 @@ export const makeProviderInstanceRegistry = Effect.fn( ); // Rebuilds an instance only when it was unavailable or its secrets changed, so a refresh does - // not restart providers whose credentials are the same. - const reloadSecrets: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reloadSecrets"] = - Effect.fn("ProviderInstanceRegistry.reloadSecrets")( - function* (instanceId) { - const configMap = yield* Ref.get(configMapRef); - const targets = yield* Effect.filter(Object.entries(configMap), ([rawInstanceId, entry]) => - (instanceId === undefined || rawInstanceId === instanceId) && - secretReferencesOf(driversById, entry).length > 0 - ? isEntryEnabled(driversById, entry) - : Effect.succeed(false), - ); - if (targets.length === 0) return; + // not restart providers whose credentials are the same. Without `checked` the cached values are + // dropped first; with it, only that reference takes the checked value and the rest carry over. + const reloadWhere = Effect.fn("ProviderInstanceRegistry.reloadWhere")( + function* ( + select: (rawInstanceId: string, entry: ProviderInstanceConfig) => boolean, + checked?: CheckedSecret, + ) { + const configMap = yield* Ref.get(configMapRef); + const targets = yield* Effect.filter(Object.entries(configMap), ([rawInstanceId, entry]) => + select(rawInstanceId, entry) && secretReferencesOf(driversById, entry).length > 0 + ? isEntryEnabled(driversById, entry) + : Effect.succeed(false), + ); + if (targets.length === 0) return []; + if (checked === undefined) { const resolver = yield* SecretResolver.SecretResolver; const references = targets.flatMap(([, entry]) => secretReferencesOf(driversById, entry)); yield* resolver.invalidate(references); yield* resolver.read(references); - const live = yield* Ref.get(entries); - const rebuild = new Set(); - for (const [rawInstanceId, entry] of targets) { - const current = live.get(ProviderInstanceId.make(rawInstanceId)); - if (current === undefined) { - rebuild.add(ProviderInstanceId.make(rawInstanceId)); - continue; + } + const live = yield* Ref.get(entries); + const rebuild = new Set(); + const carried = new Map(); + for (const [rawInstanceId, entry] of targets) { + const instanceId = ProviderInstanceId.make(rawInstanceId); + const current = live.get(instanceId); + if (current === undefined) { + rebuild.add(instanceId); + if (checked !== undefined) { + const { secrets, unreadable } = yield* readInstanceSecrets( + driversById.get(entry.driver), + entry, + checked, + ); + if (unreadable.length === 0) carried.set(instanceId, secrets); } - const { secrets, unreadable } = yield* readInstanceSecrets( + continue; + } + if (checked !== undefined) { + const secrets = carryCheckedSecret( driversById.get(entry.driver), - entry, + current.entry, + current.secrets, + checked, ); - // A failed re-read keeps the working instance and the value it already holds. - if (unreadable.length === 0 && !Equal.equals(secrets, current.secrets)) { + if (!Equal.equals(secrets, current.secrets)) { rebuild.add(current.instance.instanceId); + carried.set(current.instance.instanceId, secrets); } + continue; } - yield* reconcileWithR(configMap, rebuild); - }, - (effect) => semaphore.withPermits(1)(effect), - Effect.provideContext(driverContext), + const { secrets, unreadable } = yield* readInstanceSecrets( + driversById.get(entry.driver), + entry, + ); + // A failed re-read keeps the working instance and the value it already holds. + if (unreadable.length === 0 && !Equal.equals(secrets, current.secrets)) { + rebuild.add(current.instance.instanceId); + } + } + yield* reconcileWithR(configMap, rebuild, false, carried); + return targets.map(([rawInstanceId]) => ProviderInstanceId.make(rawInstanceId)); + }, + (effect) => semaphore.withPermits(1)(effect), + Effect.provideContext(driverContext), + ); + const reloadSecrets: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reloadSecrets"] = + (instanceId) => + reloadWhere( + (rawInstanceId) => instanceId === undefined || rawInstanceId === instanceId, + undefined, + ).pipe(Effect.asVoid); + const rebuild: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["rebuild"] = ( + instanceIds, + ) => + semaphore.withPermits(1)( + Ref.get(configMapRef).pipe( + Effect.flatMap((configMap) => reconcileWithR(configMap, new Set(instanceIds))), + Effect.provideContext(driverContext), + ), ); + const applySecret: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["applySecret"] = + (reference, value) => + reloadWhere( + (_, entry) => + secretReferencesOf(driversById, entry).some((candidate) => + sameReference(candidate, reference), + ), + { reference, value }, + ); // Reading secrets can wait on a vault unlock, so the server does not wait for it to start. yield* semaphore.withPermits(1)( @@ -592,6 +706,8 @@ export const makeProviderInstanceRegistry = Effect.fn( const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = { reconcile, reloadSecrets, + rebuild, + applySecret, }; return { registry, mutator }; diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts index dc44f0324a..a9de2878a3 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts @@ -165,6 +165,8 @@ describe("layerSettingsWatcher", () => { const mutator = Layer.succeed(ProviderInstanceRegistryMutator, { reconcile: () => Queue.offer(reconciled, undefined), reloadSecrets: () => Effect.sync(() => void reloads++), + rebuild: () => Effect.void, + applySecret: () => Effect.succeed([]), }); yield* Layer.build( layerSettingsWatcher(Stream.fromQueue(changes), initial).pipe(Layer.provide(mutator)), diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts index 256bf2e797..f1f0ba8b59 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts @@ -15,6 +15,7 @@ import type * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import type * as SqlClient from "effect/sql/SqlClient"; import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; @@ -47,7 +48,9 @@ type ProviderInstanceRegistryHydrationEnv = // Secret provider reads. | SecureRandom.SecureRandom // The Claude runner counts its CLIs as running agents for port discovery. - | PortScanner.PortDiscovery; + | PortScanner.PortDiscovery + // Adapter ids read which subagent threads predate short ids. + | SqlClient.SqlClient; export const deriveProviderInstanceConfigMap = ( settings: ServerSettings, diff --git a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts index 35eb52d3f2..a7cb5be093 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts @@ -1,5 +1,9 @@ /** Reconcile closes removed/replaced scopes before creating replacements: at most one live instance per id. */ -import type { ProviderInstanceConfigMap, ProviderInstanceId } from "@t3tools/contracts"; +import type { + ProviderInstanceConfigMap, + ProviderInstanceId, + SecretReference, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; @@ -7,6 +11,16 @@ export interface ProviderInstanceRegistryMutatorShape { readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect; /** Re-reads the secrets of every instance, or one, and rebuilds those whose secrets changed. */ readonly reloadSecrets: (instanceId?: ProviderInstanceId) => Effect.Effect; + /** Rebuilds these live instances from their current configuration and the host environment. */ + readonly rebuild: (instanceIds: ReadonlyArray) => Effect.Effect; + /** + * Rebuilds the instances that read `reference` with `value`, keeping the other secrets a live + * instance holds, and returns them. A parked instance reads its other secrets from the resolver. + */ + readonly applySecret: ( + reference: SecretReference, + value: string, + ) => Effect.Effect>; } export class ProviderInstanceRegistryMutator extends Context.Service< diff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts new file mode 100644 index 0000000000..8458b46b30 --- /dev/null +++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.test.ts @@ -0,0 +1,42 @@ +import { assert, it } from "@effect/vitest"; +import { ProviderDriverKind } from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { layerIdAllocator } from "./ProviderOrchestrationAdapterInfrastructure.ts"; + +it.effect("subagent threads stored under a legacy id keep it when re-derived", () => + Effect.gen(function* () { + const stored = { + driver: ProviderDriverKind.make("claudeAgent"), + nativeThreadId: "parent:task-1", + }; + const legacyId = IdAllocator.deriveThreadFromProviderThread(stored); + const layerStored = Layer.effectDiscard( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + INSERT INTO orchestration_v2_projection_threads ( + thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + created_at, updated_at, payload_json + ) VALUES ( + ${legacyId}, 'project-1', 'Subagent', 'claudeAgent', 'full-access', 'default', + '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', '{}' + ) + `; + }), + ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)); + const ids = yield* IdAllocator.IdAllocatorV2.pipe( + Effect.provide(layerIdAllocator.pipe(Layer.provide(layerStored))), + ); + + assert.strictEqual(ids.derive.subagentThread(stored), legacyId); + assert.match( + ids.derive.subagentThread({ ...stored, nativeThreadId: "parent:task-2" }), + /^thread:subagent:[0-9a-f]{16}$/, + ); + }), +); diff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts index 89f225b00a..b01735a7c2 100644 --- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts +++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts @@ -1,4 +1,6 @@ +import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import * as CodexAdapterV2 from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; @@ -14,11 +16,29 @@ export type ProviderOrchestrationAdapterInfrastructure = | CursorSdk.CursorSdk | IdAllocator.IdAllocatorV2; +// Subagent threads created before short ids keep their stored id when an adapter resumes them. +export const layerIdAllocator = Layer.unwrap( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ readonly threadId: string }>` + SELECT thread_id AS "threadId" FROM orchestration_v2_projection_threads + WHERE thread_id LIKE 'thread:provider:%' + `.pipe( + Effect.catch((cause) => + Effect.logWarning("orchestration-v2.legacy-subagent-thread-ids-unavailable", { + cause, + }).pipe(Effect.as([])), + ), + ); + return IdAllocator.layerWithLegacySubagentThreads(new Set(rows.map((row) => row.threadId))); + }), +); + /** Reuse the continuation worker's exact layer reference so memoization shares one queue. */ export const layer = Layer.mergeAll( ClaudeAdapterV2.layerQueryRunner, CodexAdapterV2.layerAppServerClientFactory, CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)), - IdAllocator.layer, + layerIdAllocator, ProviderContinuationRequests.layer, ); diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 2f29528a14..48922222f3 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -20,6 +20,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; 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 Scope from "effect/Scope"; @@ -38,16 +39,23 @@ import { ServerSettingsError, ServerProvider, type ServerProviderSlashCommand, + type ServerProviderUpdateState, + type ServerProviderVersionAdvisoryStatus, type ServerSettings as ContractServerSettings, } from "@t3tools/contracts"; import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { WindowsShellEnvironment } from "@t3tools/shared/shell"; import { deepMerge } from "@t3tools/shared/Struct"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; -import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts"; +import { + checkCodexProviderStatus, + mapCodexModelCapabilities, + type CodexAppServerProviderSnapshot, +} from "./CodexProvider.ts"; import { BUNDLED_CLAUDE_MODEL_CATALOG } from "./ClaudeModelCatalog.ts"; import { checkClaudeProviderStatus } from "./ClaudeProvider.ts"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; @@ -60,10 +68,12 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime"; import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import * as ProviderInstallationGate from "./ProviderInstallationGate.ts"; import * as ProviderInstanceRegistryHydration from "./ProviderInstanceRegistryHydration.ts"; import * as PortScanner from "../preview/PortScanner.ts"; import * as ServerConfig from "../config.ts"; import * as ServerSettingsModule from "../serverSettings.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { readProviderStatusCache, resolveProviderStatusCachePath, @@ -77,6 +87,7 @@ import type { import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import * as ProviderRegistry from "./ProviderRegistry.ts"; +import { ProviderDriverError } from "@t3tools/provider-core/server/errors"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); @@ -149,6 +160,135 @@ const layerBackgroundPolicyAlwaysRun = Layer.mock(BackgroundPolicy.BackgroundPol shouldRunOpportunisticWork: Effect.succeed(true), }); +const makeWorkspaceRescanHarness = Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("claude"); + const driver = ProviderDriverKind.make("claudeCode"); + const provider = { + instanceId, + driver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "1970-01-01T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const scans = yield* Queue.unbounded<{ + readonly cwd: string; + readonly result: Deferred.Deferred; + }>(); + const makeInstance = Effect.gen(function* () { + const rescans = yield* Queue.unbounded(); + const reports = yield* Queue.unbounded(); + const instance: ProviderInstance = { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: "claude:rescan-test" }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(provider), + refresh: Effect.succeed(provider), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + // A pull-based stream pulls the next report only after the registry queued the last. + workspaceRescans: Stream.fromQueue(rescans).pipe( + Stream.tap((cwd) => Queue.offer(reports, cwd)), + ), + snapshotForCwd: (cwd) => + Effect.gen(function* () { + const result = yield* Deferred.make(); + yield* Queue.offer(scans, { cwd, result }); + return yield* Deferred.await(result); + }), + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + return { instance, rescans, reports }; + }); + const first = yield* makeInstance; + const instances = yield* Ref.make([first.instance]); + const changes = yield* PubSub.unbounded(); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const services = yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: (id) => + Ref.get(instances).pipe(Effect.map((all) => all.find((i) => i.instanceId === id))), + listInstances: Ref.get(instances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }), + ), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-workspace-rescan-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ).pipe(Scope.provide(scope)); + const registry = yield* ProviderRegistry.ProviderRegistry.pipe(Effect.provide(services)); + const snapshot = (name: string): ProviderWorkspaceSnapshot => ({ + ...provider, + skills: [{ name, path: `/workspace/${name}/SKILL.md`, enabled: true }], + }); + const nextScan = Effect.fnUntraced(function* (cwd: string) { + const scan = yield* Queue.take(scans); + assert.equal(scan.cwd, cwd); + return (name: string) => Deferred.succeed(scan.result, snapshot(name)); + }); + const refresh = (cwd: string, fresh = false) => + registry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh }); + const seed = Effect.fnUntraced(function* (cwd: string) { + const pending = yield* refresh(cwd).pipe(Effect.forkChild); + const complete = yield* nextScan(cwd); + yield* complete("initial"); + yield* Fiber.join(pending); + }); + // A later requested cwd reaching the serial consumer proves the previous rescan settled, + // including when that rescan correctly publishes no change. Seed "/barrier" first; it rescans + // to the skills it was seeded with, so it never stamps workspaceRescannedAt. + const drainRescans = Effect.gen(function* () { + yield* Queue.offer(first.rescans, "/barrier"); + const complete = yield* nextScan("/barrier"); + yield* complete("initial"); + }); + const skillsOf = (cwd: string) => + Effect.map(registry.getProviders, (providers) => + providers[0]?.workspaceSnapshots?.find((s) => s.cwd === cwd)?.skills?.map((s) => s.name), + ); + const rescannedAtOf = Effect.map( + registry.getProviders, + (providers) => providers[0]?.workspaceRescannedAt, + ); + return { + first, + makeInstance, + instances, + changes, + registry, + scans, + nextScan, + refresh, + seed, + drainRescans, + skillsOf, + rescannedAtOf, + }; +}); + function selectDescriptor( id: string, label: string, @@ -334,6 +474,86 @@ const awaitPersistedProvider = ( Effect.forkScoped, ); +const codexUpdateSnapshot = (advisory: ServerProviderVersionAdvisoryStatus) => + ({ + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-06-10T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + versionAdvisory: { + status: advisory, + currentVersion: "1.0.0", + latestVersion: advisory === "unknown" ? null : advisory === "current" ? "1.0.0" : "2.0.0", + updateCommand: null, + canUpdate: true, + checkedAt: "2026-06-10T00:00:00.000Z", + message: null, + }, + }) as const satisfies ServerProvider; + +const makeUpdateState = (status: ServerProviderUpdateState["status"]) => + ({ + status, + startedAt: "2026-06-10T00:00:00.000Z", + finishedAt: status === "queued" || status === "running" ? null : "2026-06-10T00:01:00.000Z", + message: `update ${status}`, + output: null, + }) satisfies ServerProviderUpdateState; + +// One Codex instance whose probe returns whatever `snapshot` currently holds. +const buildRegistryOverSnapshot = Effect.fn("buildRegistryOverSnapshot")(function* ( + snapshot: Ref.Ref, +) { + const driver = ProviderDriverKind.make("codex"); + const instance = { + instanceId: ProviderInstanceId.make("codex"), + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ provider: driver, packageName: null }), + ), + getSnapshot: Ref.get(snapshot), + refresh: Ref.get(snapshot), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const layerInstanceRegistry = Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(instanceId === instance.instanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe), + }); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + return yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge(layerInstanceRegistry), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-update-state-" }), + ), + Layer.provideMerge(layerBackgroundPolicyAlwaysRun), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ).pipe(Scope.provide(scope)); +}); + const layerTestNodeServices = Layer.mergeAll( ProviderLatestVersions.layer, NodeServices.layer, @@ -418,6 +638,20 @@ it.layer( }), ); + it.effect("allows a slow successful Codex probe with a configured budget", () => + Effect.gen(function* () { + const fiber = yield* checkCodexProviderStatus( + defaultCodexSettings, + () => Effect.sleep("22 seconds").pipe(Effect.as(makeCodexProbeSnapshot())), + { T3CODE_CODEX_PROBE_TIMEOUT_MS: "60000" }, + ).pipe(Effect.forkChild); + yield* TestClock.adjust("22 seconds"); + const status = yield* Fiber.join(fiber); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + }), + ); + it.effect("labels the plan the usage read reports over the cached login plan", () => Effect.gen(function* () { const statusWithUsagePlan = (planType: string | null) => @@ -466,6 +700,25 @@ it.layer( }), ); + it.effect("names the instance's CODEX_HOME in the sign-in hint for a custom home", () => + Effect.gen(function* () { + const homePath = "/srv/codex-work-home"; + const status = yield* checkCodexProviderStatus( + decodeCodexSettings({ binaryPath: "codex", homePath }), + () => + Effect.succeed( + makeCodexProbeSnapshot({ + account: { account: null, requiresOpenaiAuth: true }, + }), + ), + ); + + assert.strictEqual(status.auth.status, "unauthenticated"); + assert.include(status.message ?? "", "CODEX_HOME"); + assert.include(status.message ?? "", homePath); + }), + ); + it.effect("returns ready with unknown auth when app-server does not require OpenAI auth", () => Effect.gen(function* () { const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => @@ -484,6 +737,84 @@ it.layer( }), ); + it.effect("offers cyber access only on catalog models that advertise it", () => + Effect.gen(function* () { + const catalogModel = (slug: string, cyber?: Array<"standard" | "daybreakBlue">) => ({ + slug, + name: slug, + isCustom: false, + capabilities: mapCodexModelCapabilities({ + additionalSpeedTiers: [], + ...(cyber ? { availableAccessPrograms: { cyber } } : {}), + defaultReasoningEffort: "medium", + description: slug, + displayName: slug, + hidden: false, + id: slug, + isDefault: false, + model: slug, + supportedReasoningEfforts: [], + }), + }); + const defaultPrograms = (snapshot: Partial) => + checkCodexProviderStatus(decodeCodexSettings({ customModels: ["my-model"] }), () => + Effect.succeed( + makeCodexProbeSnapshot({ + models: [ + catalogModel("both", ["standard", "daybreakBlue"]), + catalogModel("daybreak-only", ["daybreakBlue"]), + catalogModel("plain"), + ], + ...snapshot, + }), + ), + ).pipe( + Effect.map((status) => + Object.fromEntries( + status.models.map((model) => { + const descriptor = model.capabilities?.optionDescriptors?.find( + (option) => option.id === "cyberAccessProgram", + ); + return [ + model.slug, + descriptor?.type === "select" + ? (descriptor.currentValue ?? "no default") + : null, + ]; + }), + ), + ), + ); + + assert.deepStrictEqual(yield* defaultPrograms({ daybreakEnabled: false }), { + both: "standard", + "daybreak-only": "daybreakBlue", + plain: null, + "my-model": null, + }); + assert.deepStrictEqual(yield* defaultPrograms({ daybreakEnabled: true }), { + both: "daybreakBlue", + "daybreak-only": "daybreakBlue", + plain: null, + "my-model": null, + }); + // An unread config keeps the choice but cannot know Codex's default. + assert.deepStrictEqual(yield* defaultPrograms({}), { + both: "no default", + "daybreak-only": "no default", + plain: null, + "my-model": null, + }); + assert.deepStrictEqual( + yield* defaultPrograms({ + account: { account: { type: "apiKey" }, requiresOpenaiAuth: false }, + cyberAccessProgramsUnavailable: true, + }), + { both: null, "daybreak-only": null, plain: null, "my-model": null }, + ); + }), + ); + it.effect("reads the version of a Codex CLI too old to run app-server (#20351)", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; @@ -591,6 +922,86 @@ it.layer( }), ); + it.effect("shows Codex usage that answers after three seconds inside the probe budget", () => + Effect.gen(function* () { + const usageRequested = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Effect.scope; + const output = yield* Queue.unbounded(); + const send = (message: unknown) => + Queue.offer(output, encoder.encode(`${JSON.stringify(message)}\n`)); + const results: Record = { + initialize: { + userAgent: "codex_cli_rs/0.167.0", + codexHome: "/nonexistent-codex-home", + platformFamily: "unix", + platformOs: "linux", + }, + "account/read": { + account: { type: "chatgpt", email: "test@example.com", planType: "pro" }, + requiresOpenaiAuth: true, + }, + "config/read": { config: {}, origins: {} }, + "skills/list": { data: [] }, + "model/list": { data: [] }, + }; + const answer = (line: string) => { + const { id, method } = JSON.parse(line) as { id?: number; method?: string }; + if (id === undefined || method === undefined) return Effect.void; + if (method !== "account/rateLimits/read") { + return send({ id, result: results[method] ?? {} }); + } + return Deferred.succeed(usageRequested, undefined).pipe( + Effect.andThen(Effect.sleep("4 seconds")), + Effect.andThen( + send({ + id, + result: { + rateLimits: { + limitId: "codex", + planType: "pro", + primary: { usedPercent: 42, windowDurationMins: 300, resetsAt: 2e9 }, + }, + rateLimitsByLimitId: null, + rateLimitResetCredits: null, + accountId: null, + }, + }), + ), + Effect.forkIn(scope), + ); + }; + const decoder = new TextDecoder(); + let buffered = ""; + return ChildProcessSpawner.makeHandle({ + ...mockHandle({ stdout: "", stderr: "", code: 0 }), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + stdin: Sink.forEach((chunk: Uint8Array) => { + buffered += decoder.decode(chunk, { stream: true }); + const lines = buffered.split("\n"); + buffered = lines.pop() ?? ""; + return Effect.forEach(lines.filter(Boolean), answer, { discard: true }); + }), + stdout: Stream.fromQueue(output), + }); + }), + ); + const fiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.forkChild, + ); + yield* Deferred.await(usageRequested); + yield* TestClock.adjust("25 seconds"); + const status = yield* Fiber.join(fiber); + + assert.strictEqual(status.auth.status, "authenticated"); + assert.isUndefined(status.usageLimits?.unavailable); + assert.strictEqual(status.usageLimits?.windows[0]?.usedPercent, 42); + }), + ); + it.effect("does not run --version when the Codex executable cannot start", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; @@ -617,6 +1028,74 @@ it.layer( }); describe("ProviderRegistry.layer", () => { + it("marks folder catalogs pending when a machine refresh changes the machine models", () => { + const machineModel = { + slug: "opencode/big-pickle", + name: "Big Pickle", + isCustom: false, + capabilities: null, + } satisfies ServerProvider["models"][number]; + const projectModel = { ...machineModel, slug: "uni/medium-gpt", name: "Medium GPT" }; + const addedModel = { ...machineModel, slug: "opencode/new", name: "New" }; + const provider = { + instanceId: ProviderInstanceId.make("opencode"), + driver: ProviderDriverKind.make("opencode"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-03-25T00:00:00.000Z", + version: "2.0.0", + models: [machineModel], + slashCommands: [], + skills: [], + } satisfies ServerProvider; + const withCatalog = ProviderRegistry.upsertProviderWorkspaceSnapshot( + ProviderRegistry.upsertProviderWorkspaceSnapshot(provider, "/project", { + ...provider, + workspaceModels: [machineModel, projectModel], + }), + "/plain", + provider, + ); + + const unchanged = ProviderRegistry.mergeProviderSnapshot(withCatalog, provider); + assert.deepStrictEqual( + unchanged.workspaceSnapshots?.map((snapshot) => snapshot.cwd), + ["/project", "/plain"], + ); + // A machine health refresh must not read as a rescan, nor erase the last one. + const rescanned = { ...withCatalog, workspaceRescannedAt: "2026-03-25T00:01:00.000Z" }; + assert.equal( + ProviderRegistry.mergeProviderSnapshot(rescanned, provider).workspaceRescannedAt, + "2026-03-25T00:01:00.000Z", + ); + assert.equal( + ProviderRegistry.mergeProviderSnapshot(rescanned, { + ...provider, + workspaceRescannedAt: "2026-03-25T00:02:00.000Z", + }).workspaceRescannedAt, + "2026-03-25T00:02:00.000Z", + ); + assert.equal(unchanged.workspaceRescannedAt, undefined); + const changed = ProviderRegistry.mergeProviderSnapshot(withCatalog, { + ...provider, + models: [machineModel, addedModel], + }); + assert.deepStrictEqual( + changed.workspaceSnapshots?.map(({ cwd, models, modelsPending }) => ({ + cwd, + models, + modelsPending, + })), + [ + { cwd: "/project", models: [machineModel, projectModel], modelsPending: true }, + // Its folder may define a model the machine catalog just dropped. + { cwd: "/plain", models: undefined, modelsPending: true }, + ], + ); + }); + it("stores workspace skills, commands and options without changing machine metadata", () => { const provider = { instanceId: ProviderInstanceId.make("codex"), @@ -631,11 +1110,15 @@ it.layer( slashCommands: [{ name: "global" }], skills: [{ name: "global", path: "/global/SKILL.md", enabled: true }], } satisfies ServerProvider; + const projectModels = [ + { slug: "project-model", name: "Project Model", isCustom: false, capabilities: null }, + ] satisfies ServerProvider["models"]; const scopedSnapshot = { ...provider, checkedAt: "2026-03-25T00:01:00.000Z", slashCommands: [{ name: "project" }], skills: [{ name: "project", path: "/project/SKILL.md", enabled: true }], + workspaceModels: projectModels, optionDescriptors: [ { id: "agent", @@ -663,6 +1146,7 @@ it.layer( slashCommands: scopedSnapshot.slashCommands, skills: scopedSnapshot.skills, optionDescriptors: scopedSnapshot.optionDescriptors, + models: projectModels, }, ]); @@ -670,6 +1154,7 @@ it.layer( ...scopedSnapshot, slashCommands: [COMPACT_SLASH_COMMAND], slashCommandsPending: true, + workspaceModelsPending: true, } satisfies ProviderWorkspaceSnapshot; const partial = ProviderRegistry.upsertProviderWorkspaceSnapshot( result, @@ -678,6 +1163,8 @@ it.layer( ); assert.deepStrictEqual(partial.workspaceSnapshots?.[0]?.slashCommands, [{ name: "project" }]); assert.strictEqual(partial.workspaceSnapshots?.[0]?.slashCommandsPending, true); + assert.deepStrictEqual(partial.workspaceSnapshots?.[0]?.models, projectModels); + assert.strictEqual(partial.workspaceSnapshots?.[0]?.modelsPending, true); const otherProject = ProviderRegistry.upsertProviderWorkspaceSnapshot( partial, "/other-project", @@ -695,6 +1182,14 @@ it.layer( { name: "replacement" }, ]); assert.strictEqual(recovered.workspaceSnapshots?.[0]?.slashCommandsPending, undefined); + assert.deepStrictEqual(recovered.workspaceSnapshots?.[0]?.models, projectModels); + assert.strictEqual(recovered.workspaceSnapshots?.[0]?.modelsPending, undefined); + const withoutModels = ProviderRegistry.upsertProviderWorkspaceSnapshot( + recovered, + "/project", + { ...scopedSnapshot, workspaceModels: undefined }, + ); + assert.strictEqual(withoutModels.workspaceSnapshots?.[0]?.models, undefined); const { optionDescriptors, ...failedSnapshot } = scopedSnapshot; const firstFailure = ProviderRegistry.upsertProviderWorkspaceSnapshot( @@ -776,6 +1271,7 @@ it.layer( } as const satisfies ServerProvider; const refreshedProvider = { ...previousProvider, + status: "warning", checkedAt: "2026-04-14T00:01:00.000Z", models: [], slashCommands: [], @@ -883,32 +1379,36 @@ it.layer( ); }); - it("drops Grok models a completed probe no longer advertises", () => { + it.each([ + ["grok", "warning"], + ["cursor", "error"], + ["muse", "error"], + ["fx", "warning"], + ] as const)("drops %s models a completed listing no longer returns", (driver, failedStatus) => { const previousProvider = { - instanceId: ProviderInstanceId.make("grok"), - driver: ProviderDriverKind.make("grok"), + instanceId: ProviderInstanceId.make(driver), + driver: ProviderDriverKind.make(driver), status: "ready", enabled: true, installed: true, auth: { status: "authenticated" }, - checkedAt: "2026-09-30T00:00:00.000Z", - version: "1.0.44", + checkedAt: "2026-10-30T00:00:00.000Z", + version: "1.0.0", models: [ - { slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }, - { slug: "codexhub-removed", name: "Removed", isCustom: false, capabilities: null }, + { slug: "current-model", name: "Current", isCustom: false, capabilities: null }, + { slug: "retired-model", name: "Retired", isCustom: false, capabilities: null }, ], slashCommands: [], skills: [], } as const satisfies ServerProvider; const refreshedProvider = { ...previousProvider, - checkedAt: "2026-09-30T00:01:00.000Z", + checkedAt: "2026-10-30T00:01:00.000Z", models: [previousProvider.models[0]], } satisfies ServerProvider; - const acpFailedProvider = { + const failedProvider = { ...refreshedProvider, - status: "warning", - message: "Grok CLI is installed but ACP initialize failed.", + status: failedStatus, } satisfies ServerProvider; assert.deepStrictEqual( @@ -916,12 +1416,44 @@ it.layer( [previousProvider.models[0]], ); assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, acpFailedProvider).models, + ProviderRegistry.mergeProviderSnapshot(previousProvider, failedProvider).models, [...previousProvider.models], ); }); - it("retains stale OpenCode models when a refresh fails", () => { + it.each(["kiro", "claudeAgent"] as const)( + "keeps %s models a ready probe can omit", + (driver) => { + const previousProvider = { + instanceId: ProviderInstanceId.make(driver), + driver: ProviderDriverKind.make(driver), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-10-30T00:00:00.000Z", + version: "1.0.0", + models: [ + { slug: "built-in-model", name: "Built-in", isCustom: false, capabilities: null }, + { slug: "listed-model", name: "Listed", isCustom: false, capabilities: null }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const partialProvider = { + ...previousProvider, + checkedAt: "2026-10-30T00:01:00.000Z", + models: [previousProvider.models[0]], + } satisfies ServerProvider; + + assert.deepStrictEqual( + ProviderRegistry.mergeProviderSnapshot(previousProvider, partialProvider).models, + [...previousProvider.models], + ); + }, + ); + + it("retains stale OpenCode models when a refresh fails or lists none", () => { const previousProvider = { instanceId: ProviderInstanceId.make("opencode"), driver: ProviderDriverKind.make("opencode"), @@ -971,6 +1503,21 @@ it.layer( ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).skills, previousProvider.skills, ); + + const emptyCatalogProvider = { + ...refreshedProvider, + status: "warning", + message: "OpenCode 2 is running, but it did not list any models yet.", + slashCommands: [], + skills: [], + } satisfies ServerProvider; + const mergedEmptyCatalog = ProviderRegistry.mergeProviderSnapshot( + previousProvider, + emptyCatalogProvider, + ); + assert.deepStrictEqual(mergedEmptyCatalog.models, [...previousProvider.models]); + assert.deepStrictEqual(mergedEmptyCatalog.slashCommands, previousProvider.slashCommands); + assert.deepStrictEqual(mergedEmptyCatalog.skills, previousProvider.skills); }); describe("Pi model inventories", () => { @@ -1232,6 +1779,9 @@ it.layer( }), ), getSnapshot: Ref.get(currentProvider), + isAwaitingFirstCheck: Ref.get(currentProvider).pipe( + Effect.map((provider) => provider === pendingProvider), + ), refresh: Ref.get(nextProvider).pipe( Effect.tap((provider) => Ref.set(currentProvider, provider)), ), @@ -1265,6 +1815,23 @@ it.layer( ? retainedModels : [customModel, ...cachedProvider.models]; assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, expectedModels); + if (!restarted) { + const probeFields = ({ status, installed, auth, version }: ServerProvider) => ({ + status, + installed, + auth, + version, + }); + // Boot reads the probe state from the cache, not the pending snapshot, and never persists the pending one. + assert.deepStrictEqual( + probeFields((yield* registry.getProviders)[0]!), + probeFields(cachedProvider), + ); + assert.deepStrictEqual( + probeFields((yield* readProviderStatusCache(filePath))!), + probeFields(cachedProvider), + ); + } yield* registry.refreshInstance(instance.instanceId); assert.deepStrictEqual( @@ -1297,6 +1864,84 @@ it.layer( ), ), ); + it.effect("keeps a check that finished before boot over the cached status", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: cachedProvider.instanceId, + }); + const instance = { + instanceId: cachedProvider.instanceId, + driverKind: cachedProvider.driver, + continuationIdentity: { + driverKind: cachedProvider.driver, + continuationKey: "codex:instance:codex-personal", + }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: cachedProvider.driver, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(failedProvider), + isAwaitingFirstCheck: Effect.succeed(false), + refresh: Effect.succeed(failedProvider), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const layerInstanceRegistry = Layer.succeed( + ProviderInstanceRegistry.ProviderInstanceRegistry, + { + getInstance: (id) => + Effect.succeed(id === instance.instanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe), + }, + ); + + // First boot has no cache file; the second has a stale ready one. + for (const hasCache of [false, true]) { + if (hasCache) { + yield* writeProviderStatusCache({ + filePath, + provider: { ...cachedProvider, status: "ready" }, + }); + } + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + assert.strictEqual((yield* registry.getProviders)[0]?.status, failedProvider.status); + assert.strictEqual( + (yield* readProviderStatusCache(filePath))?.status, + failedProvider.status, + ); + }).pipe( + Effect.provide( + ProviderRegistry.layer.pipe( + Layer.provide(layerInstanceRegistry), + Layer.provide(layerUnusedMutator), + ), + ), + Effect.scoped, + ); + } + }).pipe( + Effect.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-codex-probed-before-boot-", + }).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ), + ), + ); }); describe("Antigravity model inventories", () => { @@ -1496,6 +2141,8 @@ it.layer( Effect.gen(function* () { const forceRefreshCalls = yield* Ref.make(0); const manifest = yield* Ref.make(ModelManifest.BUNDLED_MODEL_MANIFEST); + const updateEvents = yield* Ref.make>([]); + const hookFails = yield* Ref.make(false); const makeInstance = (name: string) => Effect.gen(function* () { const driver = ProviderDriverKind.make("codex"); @@ -1515,7 +2162,7 @@ it.layer( } as const satisfies ServerProvider; const invalidations = yield* Ref.make(0); const probes = yield* Ref.make(0); - const maintenanceReads = yield* Ref.make>([]); + const maintenanceReads = yield* Ref.make>([]); const instance = { instanceId, driverKind: driver, @@ -1540,7 +2187,25 @@ it.layer( streamChanges: Stream.empty, applyUsageLimits: () => Effect.void, }, - invalidateCaches: Ref.update(invalidations, (count) => count + 1), + invalidateCaches: Ref.update(invalidations, (count) => count + 1).pipe( + Effect.andThen( + Ref.update(updateEvents, (events) => [...events, `invalidate:${name}`]), + ), + ), + afterUpdate: Ref.update(maintenanceReads, (reads) => [ + ...reads, + "afterUpdate" as const, + ]).pipe( + Effect.andThen( + Ref.update(updateEvents, (events) => [...events, `afterUpdate:${name}`]), + ), + Effect.andThen(Ref.get(hookFails)), + Effect.flatMap((fails) => + fails + ? Effect.fail(new ProviderDriverError({ driver, instanceId, detail: "hook" })) + : Effect.void, + ), + ), orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; @@ -1623,6 +2288,30 @@ it.layer( assert.strictEqual(yield* Ref.get(second.probes), probesBefore + 1); // It never rechecks latest CLI versions. assert.strictEqual(yield* readCachedVersion("codex_second-package", "3.0.0"), "2.0.0"); + + yield* first.takeMaintenanceReads; + yield* Ref.set(updateEvents, []); + yield* registry.refreshAfterUpdate(first.instance.driverKind, first.instance.instanceId); + assert.deepStrictEqual((yield* first.takeMaintenanceReads).slice(0, 2), [ + "afterUpdate", + true, + ]); + assert.notInclude(yield* second.takeMaintenanceReads, "afterUpdate"); + // Instances sharing the replaced service must not cache its old version. + assert.strictEqual((yield* Ref.get(updateEvents))[0], "afterUpdate:codex_first"); + + // A failed hook leaves the probe to report what is running. + yield* Ref.set(hookFails, true); + const probesBeforeFailedHook = yield* Ref.get(first.probes); + const refreshed = yield* registry.refreshAfterUpdate( + first.instance.driverKind, + first.instance.instanceId, + ); + assert.strictEqual(yield* Ref.get(first.probes), probesBeforeFailedHook + 1); + assert.include( + refreshed.map((provider) => provider.instanceId), + first.instance.instanceId, + ); }).pipe( Effect.provide( ProviderRegistry.layer.pipe( @@ -1735,6 +2424,239 @@ it.layer( }), ); + it.effect( + "rebuilds only instances missing their CLI when a refresh finds a new Windows PATH", + () => { + const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows" }; + return Effect.gen(function* () { + const driver = ProviderDriverKind.make("codex"); + const makeInstance = (id: string, installed: boolean): ProviderInstance => { + const instanceId = ProviderInstanceId.make(id); + const provider = { + instanceId, + driver, + status: installed ? "ready" : "error", + enabled: true, + installed, + auth: { status: "unknown" }, + checkedAt: "1970-01-01T00:00:00.000Z", + version: null, + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + return { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: `codex:${id}` }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(provider), + refresh: Effect.succeed(provider), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + }; + const instances = [makeInstance("present", true), makeInstance("missing", false)]; + const rebuilt: Array> = []; + const changes = yield* PubSub.unbounded(); + const registry = yield* ProviderRegistry.ProviderRegistry.pipe( + Effect.provide( + ProviderRegistry.layer.pipe( + Layer.provide( + Layer.mock(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator)({ + rebuild: (ids) => Effect.sync(() => void rebuilt.push(ids)), + }), + ), + Layer.provideMerge( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: (id) => Effect.succeed(instances.find((i) => i.instanceId === id)), + listInstances: Effect.succeed(instances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }), + ), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-path-" }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ); + + yield* registry.refresh(); + + assert.strictEqual(env.PATH, "C:\\Windows;C:\\Tools"); + assert.deepStrictEqual(rebuilt, [[ProviderInstanceId.make("missing")]]); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(WindowsShellEnvironment, () => + Effect.succeed({ PATH: "C:\\Windows;C:\\Tools" }), + ), + ); + }, + ); + + it.effect("rescans a requested cwd whose snapshot is still current", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* h.seed("/workspace"); + assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]); + yield* Queue.offer(h.first.rescans, "/workspace"); + const complete = yield* h.nextScan("/workspace"); + yield* complete("hook"); + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]); + // Clients that fetched the old skills are told to fetch again. + const scannedAt = (yield* h.registry.getProviders)[0]?.workspaceSnapshots?.find( + (snapshot) => snapshot.cwd === "/workspace", + )?.checkedAt; + assert.isString(scannedAt); + assert.equal(yield* h.rescannedAtOf, scannedAt); + }), + ); + + it.effect("stamps a rescan whose awaited scan already published the change", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* h.seed("/workspace"); + const ordinary = yield* h.refresh("/workspace", true).pipe(Effect.forkChild); + const completeOrdinary = yield* h.nextScan("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + yield* Queue.take(h.first.reports); + // Let the consumer reach its wait on the running scan. + yield* TestClock.adjust(0); + yield* completeOrdinary("hook"); + yield* Fiber.join(ordinary); + const completeRescan = yield* h.nextScan("/workspace"); + yield* completeRescan("hook"); + yield* h.drainRescans; + assert.isString(yield* h.rescannedAtOf); + }), + ); + + it.effect("leaves workspaceRescannedAt unset when a rescan changes nothing", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* h.seed("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + const complete = yield* h.nextScan("/workspace"); + yield* complete("initial"); + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]); + assert.equal(yield* h.rescannedAtOf, undefined); + }), + ); + + it.effect("starts no scan for a reported cwd nobody requested", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* Queue.offer(h.first.rescans, "/unrequested"); + // The next scan being the barrier's shows the report started none. + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/unrequested"), undefined); + }), + ); + + it.effect("rescans after an initial scan in flight when the hook report arrives", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild); + const completeInitial = yield* h.nextScan("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + yield* Queue.take(h.first.reports); + // Let the consumer reach its wait on the running scan. + yield* TestClock.adjust(0); + yield* completeInitial("initial"); + // The requesting client's reply is its only copy of the scan, so the rescan must not + // supersede it. + const reply = yield* Fiber.join(initial); + assert.deepEqual( + reply[0]?.workspaceSnapshots + ?.find((s) => s.cwd === "/workspace") + ?.skills?.map((s) => s.name), + ["initial"], + ); + const completeRescan = yield* h.nextScan("/workspace"); + yield* completeRescan("hook"); + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]); + }), + ); + + it.effect("lets a fresh refresh started while a rescan waits keep its own result", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild); + const completeInitial = yield* h.nextScan("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + yield* Queue.take(h.first.reports); + // Let the consumer reach its wait on the running scan. + yield* TestClock.adjust(0); + const fresh = yield* h.refresh("/workspace", true).pipe(Effect.forkChild); + const completeFresh = yield* h.nextScan("/workspace"); + yield* completeInitial("initial"); + yield* completeFresh("fresh"); + yield* Fiber.join(initial); + const reply = yield* Fiber.join(fresh); + assert.deepEqual( + reply[0]?.workspaceSnapshots + ?.find((s) => s.cwd === "/workspace") + ?.skills?.map((s) => s.name), + ["fresh"], + ); + // The rescan joins the fresh scan, so the next scan started is the barrier's. + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["fresh"]); + }), + ); + + it.effect("ignores a queued rescan from a replaced instance", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/workspace"); + const replacement = yield* h.makeInstance; + const rebuilt = yield* h.registry.streamChanges.pipe( + Stream.filter((providers) => providers[0]?.workspaceSnapshots === undefined), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* Ref.set(h.instances, [replacement.instance]); + yield* PubSub.publish(h.changes, undefined); + yield* Fiber.join(rebuilt); + yield* h.seed("/workspace"); + yield* h.seed("/barrier"); + // The forwarder pulls the second report only after queueing the first. + yield* Queue.offerAll(h.first.rescans, ["/workspace", "/workspace"]); + yield* Queue.take(h.first.reports); + yield* Queue.take(h.first.reports); + yield* Queue.offer(replacement.rescans, "/barrier"); + // A scan started for the stale report would come before the barrier's. + const completeBarrier = yield* h.nextScan("/barrier"); + yield* completeBarrier("barrier"); + assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]); + }), + ); + it.effect("scans scanCwd and keys the workspace snapshot by cwd", () => Effect.gen(function* () { const driver = ProviderDriverKind.make("codex"); @@ -1951,6 +2873,123 @@ it.layer( }), ); + it.effect("rescans a folder whose model catalog could not be read before its TTL", () => + Effect.gen(function* () { + const driver = ProviderDriverKind.make("opencode"); + const instanceId = ProviderInstanceId.make("opencode"); + const machineModel = { + slug: "opencode/big-pickle", + name: "Big Pickle", + isCustom: false, + capabilities: null, + } satisfies ServerProvider["models"][number]; + const projectModel = { ...machineModel, slug: "uni/medium-gpt", name: "Medium GPT" }; + const provider = { + instanceId, + driver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-06-10T00:00:00.000Z", + version: "2.0.0", + models: [machineModel], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const machineProvider = yield* Ref.make(provider); + const scanResult = yield* Ref.make({ + ...provider, + slashCommandsPending: false, + workspaceModelsPending: true, + }); + const instance: ProviderInstance = { + instanceId, + driverKind: driver, + continuationIdentity: { + driverKind: driver, + continuationKey: "opencode:instance:opencode", + }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Ref.get(machineProvider), + refresh: Ref.get(machineProvider), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + snapshotForCwd: () => Ref.get(scanResult), + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + const layerInstanceRegistry = Layer.succeed( + ProviderInstanceRegistry.ProviderInstanceRegistry, + { + getInstance: (requestedId) => + Effect.succeed(requestedId === instanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe), + }, + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge(layerInstanceRegistry), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-pending-workspace-models-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const workspaceOf = Effect.map( + registry.getProviders, + (providers) => providers[0]?.workspaceSnapshots?.[0], + ); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project" }); + const unread = yield* workspaceOf; + assert.strictEqual(unread?.models, undefined); + assert.strictEqual(unread?.modelsPending, true); + + const workspaceModels = [machineModel, projectModel]; + yield* Ref.set(scanResult, { ...provider, slashCommandsPending: false, workspaceModels }); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project" }); + const recovered = yield* workspaceOf; + assert.deepStrictEqual(recovered?.models, workspaceModels); + assert.strictEqual(recovered?.modelsPending, undefined); + + // A fresh refresh whose machine models change still publishes the folder read it ran. + const addedModel = { ...machineModel, slug: "opencode/new", name: "New" }; + const nextWorkspaceModels = [machineModel, addedModel, projectModel]; + yield* Ref.set(machineProvider, { ...provider, models: [machineModel, addedModel] }); + yield* Ref.set(scanResult, { + ...provider, + slashCommandsPending: false, + workspaceModels: nextWorkspaceModels, + }); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project", fresh: true }); + const rescanned = yield* workspaceOf; + assert.deepStrictEqual(rescanned?.models, nextWorkspaceModels); + assert.strictEqual(rescanned?.modelsPending, undefined); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + it.effect("shares one in-flight pass between concurrent untargeted refreshes", () => Effect.gen(function* () { const driver = ProviderDriverKind.make("codex"); @@ -2336,6 +3375,7 @@ it.layer( } as const satisfies ServerProvider; const refreshedProvider = { ...initialProvider, + status: "warning", checkedAt: "2026-04-14T00:01:00.000Z", models: [], } satisfies ServerProvider; @@ -2804,6 +3844,67 @@ it.layer( }), ); + describe("update results across refreshes", () => { + const instanceId = ProviderInstanceId.make("codex"); + + it.effect.each([ + { status: "unchanged", advisory: "current", retired: true }, + { status: "failed", advisory: "current", retired: true }, + { status: "unchanged", advisory: "behind_latest", retired: false }, + { status: "failed", advisory: "behind_latest", retired: false }, + // The probe publishes `unknown` until the latest-version check lands. + { status: "unchanged", advisory: "unknown", retired: false }, + { status: "queued", advisory: "current", retired: false }, + { status: "running", advisory: "current", retired: false }, + { status: "succeeded", advisory: "current", retired: false }, + { status: "failed", advisory: "unknown", retired: false }, + ] as const)( + "a $status update result is retired: $retired when a refresh reports the provider $advisory", + ({ status, advisory, retired }) => + Effect.gen(function* () { + const snapshot = yield* Ref.make(codexUpdateSnapshot("behind_latest")); + const runtimeServices = yield* buildRegistryOverSnapshot(snapshot); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const state = makeUpdateState(status); + yield* registry.setProviderMaintenanceActionState({ + instanceId, + action: "update", + state, + }); + yield* Ref.set(snapshot, codexUpdateSnapshot(advisory)); + + const [refreshed] = yield* registry.refresh(ProviderDriverKind.make("codex")); + + expect(refreshed?.updateState).toEqual(retired ? undefined : state); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it.effect.each(["failed", "unchanged"] as const)( + "keeps a %s recommended-version install after a current refresh", + (status) => + Effect.gen(function* () { + const snapshot = yield* Ref.make(codexUpdateSnapshot("current")); + const runtimeServices = yield* buildRegistryOverSnapshot(snapshot); + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const state = makeUpdateState(status); + const input = { + instanceId, + action: "update" as const, + state, + targetVersion: "0.9.0", + }; + yield* registry.setProviderMaintenanceActionState(input); + const [refreshed] = yield* registry.refresh(ProviderDriverKind.make("codex")); + expect(refreshed?.updateState).toEqual(state); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + }); + it.effect("re-probes when settings change the codex binaryPath", () => Effect.gen(function* () { const firstMissing = `t3code_codex_first_`; @@ -2838,7 +3939,15 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const layerProviderRegistry = ProviderRegistry.layer.pipe( Layer.provideMerge( - ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(PortScanner.layerTest)), + ProviderInstanceRegistryHydration.layer.pipe( + Layer.provide( + Layer.mergeAll( + PortScanner.layerTest, + ProviderInstallationGate.layer, + SqlitePersistence.layerMemory, + ), + ), + ), ), Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer), Layer.provideMerge( @@ -2956,7 +4065,15 @@ it.layer( yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const layerProviderRegistry = ProviderRegistry.layer.pipe( Layer.provideMerge( - ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(PortScanner.layerTest)), + ProviderInstanceRegistryHydration.layer.pipe( + Layer.provide( + Layer.mergeAll( + PortScanner.layerTest, + ProviderInstallationGate.layer, + SqlitePersistence.layerMemory, + ), + ), + ), ), Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer), Layer.provideMerge( @@ -3091,7 +4208,15 @@ it.layer( ); readSeed = false; const services = yield* Layer.build( - ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(PortScanner.layerTest)), + ProviderInstanceRegistryHydration.layer.pipe( + Layer.provide( + Layer.mergeAll( + PortScanner.layerTest, + ProviderInstallationGate.layer, + SqlitePersistence.layerMemory, + ), + ), + ), ).pipe(Effect.provide(dependencies)); failCurrentRead = input.failCurrentRead ?? false; yield* PubSub.publish(changes, undefined); @@ -3523,6 +4648,7 @@ it.layer( ); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.label, "Claude API Key"); }).pipe( Effect.provide( layerMockSpawner((args) => { diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index f431e82cbc..59729330ad 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -1,8 +1,10 @@ import { defaultInstanceIdForDriver, isProviderWorkspaceSnapshotCurrent, + isProviderWorkspaceSnapshotPending, ProviderDriverKind, type ProviderInstanceId, + type SecretReference, type ServerProvider, type ServerProviderUpdateState, } from "@t3tools/contracts"; @@ -10,6 +12,7 @@ import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; @@ -19,6 +22,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -28,6 +32,7 @@ import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderL import * as ModelManifest from "./ModelManifest.ts"; import { applyProviderCompatibility } from "./providerCompatibility.ts"; import * as ServerConfig from "../config.ts"; +import { refreshWindowsPath } from "../os-jank.ts"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import { @@ -70,6 +75,12 @@ export class ProviderRegistry extends Context.Service< instanceId?: ProviderInstanceId, ) => Effect.Effect>; + /** Rebuilds and refreshes only the instances that read a secret, with the value the caller just read. */ + readonly applySecretAndRefresh: ( + reference: SecretReference, + value: string, + ) => Effect.Effect>; + /** Only refreshed instances can verify an update; the published list still includes every row. */ readonly refreshAfterUpdate: ( provider: ProviderDriverKind, @@ -111,6 +122,7 @@ export class ProviderRegistry extends Context.Service< readonly instanceId: ProviderInstanceId; readonly action: ProviderMaintenanceActionKind; readonly state: ServerProviderUpdateState | null; + readonly targetVersion?: string | undefined; }) => Effect.Effect>; readonly streamChanges: Stream.Stream>; @@ -159,6 +171,9 @@ export function upsertProviderWorkspaceSnapshot( ): ServerProvider { const previousSnapshot = provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd); const optionDescriptors = scopedSnapshot.optionDescriptors ?? previousSnapshot?.optionDescriptors; + const models = scopedSnapshot.workspaceModelsPending + ? previousSnapshot?.models + : scopedSnapshot.workspaceModels; const workspaceSnapshot = { cwd, checkedAt: scopedSnapshot.checkedAt, @@ -168,6 +183,8 @@ export function upsertProviderWorkspaceSnapshot( ...(scopedSnapshot.slashCommandsPending ? { slashCommandsPending: true } : {}), skills: scopedSnapshot.skills, ...(optionDescriptors === undefined ? {} : { optionDescriptors }), + ...(models === undefined ? {} : { models }), + ...(scopedSnapshot.workspaceModelsPending ? { modelsPending: true } : {}), } satisfies NonNullable[number]; return { ...provider, @@ -197,16 +214,26 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => ); } - if (provider.driver === ProviderDriverKind.make("grok")) { - // Grok reports ready only after it discovers a model list; the pending, - // ACP-failed, empty-inventory, and logged-out probes are warning/error. - return !(provider.installed && provider.status === "ready"); + if (provider.driver === ProviderDriverKind.make("kiro")) { + // Kiro is ready once `whoami` confirms the account, even when `--list-models` failed and + // the snapshot fell back to the built-in list. + return true; + } + + if (provider.driver === ProviderDriverKind.make("claudeAgent")) { + // Claude Code keeps one gateway model cache per Claude home, for one base URL at a time, so a + // ready probe can omit this instance's gateway models after another instance or a terminal + // `claude` on a different gateway rewrote that cache. + return true; } const isAntigravity = provider.driver === ProviderDriverKind.make("antigravity"); const isCodex = provider.driver === ProviderDriverKind.make("codex"); - if (!isAntigravity && !isCodex && provider.driver !== ProviderDriverKind.make("opencode")) { - return true; + const isOpenCode = provider.driver === ProviderDriverKind.make("opencode"); + if (!isAntigravity && !isCodex && !isOpenCode) { + // Any other driver must report ready only after a completed model listing, or opt out above: + // a ready list is authoritative, and warning/error probes keep the old models. + return !(provider.installed && provider.status === "ready"); } if ( @@ -221,9 +248,10 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => isAntigravity && provider.status === "warning" && provider.auth.status === "unknown"; const isPendingInitialProbe = provider.enabled && !provider.installed && provider.status === "warning"; + // A cold OpenCode server can finish its probe as a warning before it lists any models. const isIncompleteInstalledProbe = provider.installed && - (provider.status === "error" || (isCodex && provider.status === "warning")); + (provider.status === "error" || ((isCodex || isOpenCode) && provider.status === "warning")); return isPendingAntigravityAuthentication || isPendingInitialProbe || isIncompleteInstalledProbe; }; @@ -295,15 +323,27 @@ export const mergeProviderSnapshot = ( } const savedAccount = carrySavedAntigravityAccount(previousProvider, nextProvider); const { message: _uncheckedMessage, ...nextWithoutMessage } = nextProvider; + const models = mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models); + // Folder catalogs were compared with the old machine catalog, so every folder rescans. + const previousWorkspaceSnapshots = Equal.equals(models, previousProvider.models) + ? previousProvider.workspaceSnapshots + : previousProvider.workspaceSnapshots?.map((snapshot) => ({ + ...snapshot, + modelsPending: true, + })); return { ...(savedAccount?.status === "ready" ? nextWithoutMessage : nextProvider), ...savedAccount, - models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models), + models, ...(nextProvider.workspaceSnapshots !== undefined ? { workspaceSnapshots: nextProvider.workspaceSnapshots } - : previousProvider.workspaceSnapshots !== undefined - ? { workspaceSnapshots: previousProvider.workspaceSnapshots } + : previousWorkspaceSnapshots !== undefined + ? { workspaceSnapshots: previousWorkspaceSnapshots } : {}), + ...(nextProvider.workspaceRescannedAt === undefined && + previousProvider.workspaceRescannedAt !== undefined + ? { workspaceRescannedAt: previousProvider.workspaceRescannedAt } + : {}), ...(shouldRetainMissingOpenCodeMetadata(nextProvider) ? { slashCommands: @@ -385,10 +425,17 @@ export const layer = Layer.effect( } fallbackByInstance.set(source.instanceId, provider); } + // Read after the snapshots: a snapshot read as awaiting is the pre-check placeholder. + const awaitingBootInstances = new Set(); + for (const instance of bootInstances) { + if (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) { + awaitingBootInstances.add(instance); + } + } - const cachedProviders = yield* Effect.forEach( + const bootProviders = yield* Effect.forEach( bootSources, - (source) => + (source, index) => Effect.gen(function* () { const filePath = yield* resolveProviderStatusCachePath({ cacheDir: config.providerStatusCacheDir, @@ -398,11 +445,15 @@ export const layer = Layer.effect( if (fallbackProvider === undefined) { return undefined; } + // A completed check is seeded by the boot upsert instead, which persists it. + const placeholder = awaitingBootInstances.has(bootInstances[index]!) + ? fallbackProvider + : undefined; return yield* readProviderStatusCache(filePath).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.flatMap((cachedProvider) => { if (cachedProvider === undefined) { - return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined)); + return Effect.succeed(placeholder); } const correlation = { cachedProvider, @@ -415,7 +466,7 @@ export const layer = Layer.effect( cachedInstanceId: cachedProvider.instanceId ?? null, driver: source.driverKind, cachedDriver: cachedProvider.driver ?? null, - }).pipe(Effect.as(undefined as ServerProvider | undefined)); + }).pipe(Effect.as(placeholder)); } return Effect.succeed(hydrateCachedProvider(correlation)); }), @@ -440,13 +491,20 @@ export const layer = Layer.effect( ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, ); const providersRef = yield* Ref.make>( - cachedProviders.map((provider) => classifyCompatibility(provider, initialManifest)), + bootProviders.map((provider) => classifyCompatibility(provider, initialManifest)), ); const workspaceRefreshesRef = yield* Ref.make< ReadonlyMap>> >(new Map()); + const workspaceRescans = yield* Queue.unbounded<{ + readonly instance: ProviderInstance; + readonly cwd: string; + }>(); const maintenanceActionStatesRef = yield* Ref.make< - ReadonlyMap + ReadonlyMap< + ProviderInstanceId, + { readonly update?: ServerProviderUpdateState; readonly targetVersion?: string | undefined } + > >(new Map()); const liveSubsRef = yield* Ref.make>( @@ -462,7 +520,11 @@ export const layer = Layer.effect( cacheDir: config.providerStatusCacheDir, instanceId: key, }).pipe(Effect.provideService(Path.Path, path)); - const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider; + const { + workspaceSnapshots: _workspaceSnapshots, + workspaceRescannedAt: _workspaceRescannedAt, + ...machineProvider + } = provider; yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), @@ -550,14 +612,8 @@ export const layer = Layer.effect( }); const compatibilityRefreshRunning = yield* Ref.make(false); - const syncProvider = Effect.fn("syncProvider")(function* ( - provider: ServerProvider, - options?: { - readonly publish?: boolean; - }, - ) { - const providers = yield* upsertProviders([provider], options); - // Reclassify the current model after fetch; republishing the old probe could overwrite newer health results. + // Reclassify the current model after fetch; republishing the old probe could overwrite newer health results. + const refreshCompatibility = Effect.gen(function* () { if (!(yield* Ref.getAndSet(compatibilityRefreshRunning, true))) { yield* manifestService.refresh.pipe( Effect.andThen(upsertProviders([], { persist: false })), @@ -565,6 +621,30 @@ export const layer = Layer.effect( Effect.forkIn(serviceScope), ); } + }); + const syncProvider = Effect.fn("syncProvider")(function* ( + provider: ServerProvider, + options?: { + readonly publish?: boolean; + }, + ) { + // Latest-version status cannot resolve a failed recommended-version install. + if (provider.versionAdvisory?.status === "current") { + yield* Ref.update(maintenanceActionStatesRef, (previous) => { + const action = previous.get(provider.instanceId); + if ( + action?.targetVersion !== undefined || + (action?.update?.status !== "unchanged" && action?.update?.status !== "failed") + ) { + return previous; + } + const next = new Map(previous); + next.delete(provider.instanceId); + return next; + }); + } + const providers = yield* upsertProviders([provider], options); + yield* refreshCompatibility; return providers; }); @@ -573,21 +653,14 @@ export const layer = Layer.effect( readonly instanceId: ProviderInstanceId; readonly action: "update"; readonly state: ServerProviderUpdateState | null; + readonly targetVersion?: string | undefined; }) { yield* Ref.update(maintenanceActionStatesRef, (previous) => { - const previousActions = previous.get(input.instanceId); - const nextActions = { ...previousActions }; - if (input.state === null || input.state.status === "idle") { - delete nextActions[input.action]; - } else { - nextActions[input.action] = input.state; - } - const next = new Map(previous); - if (Object.keys(nextActions).length === 0) { + if (input.state === null || input.state.status === "idle") { next.delete(input.instanceId); } else { - next.set(input.instanceId, nextActions); + next.set(input.instanceId, { update: input.state, targetVersion: input.targetVersion }); } return next; }); @@ -630,6 +703,25 @@ export const layer = Layer.effect( }); type RefreshAllCompletion = Deferred.Deferred>; + // A refresh is how a user asks T3 to see a CLI installed since launch; a burst shares one probe. + // Drivers copy the environment when built, so instances still missing their CLI are rebuilt + // on the new PATH. They cannot have live sessions, and installed ones keep theirs. + const refreshHostPath = yield* refreshWindowsPath().pipe( + Effect.flatMap((changed) => + changed + ? Ref.get(providersRef).pipe( + Effect.flatMap((providers) => + instanceRegistryMutator.rebuild( + providers + .filter((provider) => provider.enabled && !provider.installed) + .map((provider) => provider.instanceId), + ), + ), + ) + : Effect.void, + ), + Effect.cachedWithTTL(Duration.seconds(10)), + ); const refreshAllInFlightRef = yield* Ref.make>( Option.none(), ); @@ -637,6 +729,7 @@ export const layer = Layer.effect( const lastFullProbeAtMs = yield* Ref.make(null); const refreshAll = Effect.fn("refreshAll")(function* () { + yield* refreshHostPath; const claimed = yield* Ref.modify( refreshAllInFlightRef, ( @@ -682,16 +775,13 @@ export const layer = Layer.effect( if (provider === undefined) { return yield* refreshAll(); } - const instance = (yield* Ref.get(liveSubsRef)).get(defaultInstanceIdForDriver(provider)); - if (!instance) { - return yield* Ref.get(providersRef); - } - return yield* refreshOneSource(instance); + return yield* refreshInstance(defaultInstanceIdForDriver(provider)); }); const refreshInstance = Effect.fn("refreshInstance")(function* ( instanceId: ProviderInstanceId, ) { + yield* refreshHostPath; yield* syncLiveSourcesAndContinue; const instance = (yield* Ref.get(liveSubsRef)).get(instanceId); if (!instance) { @@ -707,6 +797,15 @@ export const layer = Layer.effect( return yield* instanceId === undefined ? refresh() : refreshInstance(instanceId); }); + const applySecretAndRefresh = Effect.fn("applySecretAndRefresh")(function* ( + reference: SecretReference, + value: string, + ) { + const instanceIds = yield* instanceRegistryMutator.applySecret(reference, value); + yield* Effect.forEach(instanceIds, refreshInstance, { discard: true }); + return yield* Ref.get(providersRef); + }); + const refreshAfterUpdate = Effect.fn("refreshAfterUpdate")(function* ( provider: ProviderDriverKind, selectedInstanceId: ProviderInstanceId, @@ -739,6 +838,23 @@ export const layer = Layer.effect( ), ); }); + // Instances can share the replaced service, so none may invalidate before it restarts. + const selectedInstance = instances.find( + (instance) => instance.instanceId === selectedInstanceId, + ); + if (selectedInstance?.afterUpdate !== undefined) { + // The probe below reports what is running, so a failed hook needs no status of its own. + yield* selectedInstance.afterUpdate.pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.logError("provider post-update hook failed", { + instanceId: selectedInstance.instanceId, + cause: Cause.pretty(cause), + }), + ), + ); + } // Accounts can share an installation, but discovery must use each // instance's own executable, environment, and credentials. yield* Effect.forEach( @@ -848,6 +964,11 @@ export const layer = Layer.effect( yield* Stream.runForEach(source.streamChanges, (provider) => correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)), ).pipe(Effect.forkScoped); + if (instance.workspaceRescans) { + yield* Stream.runForEach(instance.workspaceRescans, (cwd) => + Queue.offer(workspaceRescans, { instance, cwd }), + ).pipe(Effect.forkScoped); + } } yield* Effect.yieldNow; @@ -857,6 +978,13 @@ export const layer = Layer.effect( Effect.gen(function* () { const source = buildSnapshotSource(instance); const provider = yield* source.getSnapshot; + // Boot shows the cached status until this instance's first check publishes a result. + if ( + awaitingBootInstances.has(instance) && + (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) + ) { + return yield* refreshCompatibility; + } yield* correlateSnapshotWithSource(source, provider).pipe( Effect.flatMap(syncProvider), ); @@ -914,7 +1042,10 @@ export const layer = Layer.effect( Scope.provide(serviceScope), ); - yield* upsertProviders(fallbackProviders, { publish: false }); + yield* upsertProviders( + fallbackProviders.filter((_, index) => !awaitingBootInstances.has(bootInstances[index]!)), + { publish: false }, + ); const instanceChanges = yield* instanceRegistry.subscribeChanges; yield* syncLiveSources; yield* Stream.runForEach( @@ -954,7 +1085,25 @@ export const layer = Layer.effect( readonly cwd: string; readonly scanCwd?: string; readonly fresh?: boolean; + // Set by an instance's own report that its workspace skills changed. + readonly rescan?: ProviderInstance; }) { + const workspaceSnapshotOf = (candidate: ServerProvider | undefined) => + candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd); + // What clients saw before the awaited scan, which may already have published the change. + const heldBeforeWait = input.rescan + ? workspaceSnapshotOf( + (yield* Ref.get(providersRef)).find( + (candidate) => candidate.instanceId === input.instanceId, + ), + ) + : undefined; + // A rescan waits for a running scan, which may have read files before the hook linked them. + // Claims are read before snapshots: a scan publishes before it releases its claim. + const runningScan = input.rescan + ? (yield* Ref.get(workspaceRefreshesRef)).get(input.rescan)?.get(input.cwd) + : undefined; + if (runningScan) yield* Deferred.await(runningScan); if (input.fresh) { yield* updateProviders((providers) => providers.map((candidate) => @@ -966,16 +1115,15 @@ export const layer = Layer.effect( } const providers = yield* Ref.get(providersRef); const provider = providers.find((candidate) => candidate.instanceId === input.instanceId); - const workspaceSnapshotOf = (candidate: ServerProvider | undefined) => - candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd); const scannedFrom = workspaceSnapshotOf(provider); const now = yield* DateTime.now; if ( !provider || !provider.enabled || (!input.fresh && + !input.rescan && scannedFrom && - !scannedFrom.slashCommandsPending && + !isProviderWorkspaceSnapshotPending(scannedFrom) && isProviderWorkspaceSnapshotCurrent(scannedFrom, DateTime.toEpochMillis(now))) ) { return providers; @@ -983,17 +1131,34 @@ export const layer = Layer.effect( // Use scan start for TTL, not checkedAt inherited from the machine health check. const scannedAt = DateTime.formatIso(now); const instance = yield* instanceRegistry.getInstance(input.instanceId); - if (!instance?.snapshotForCwd) return providers; + const snapshotForCwd = instance?.snapshotForCwd; + if (!instance || !snapshotForCwd) return providers; + // A report never enrolls a cwd nobody requested, nor outlives the instance that made it. + if (input.rescan && (input.rescan !== instance || (!runningScan && !scannedFrom))) { + return providers; + } const token = yield* Deferred.make(); + // A machine refresh can change this cwd's snapshot, so the scan publishes against the result. const refreshMachineSnapshot = input.fresh ? (instance.invalidateCaches ?? Effect.void).pipe( Effect.andThen(refreshInstance(input.instanceId)), + Effect.andThen(Ref.get(providersRef)), + Effect.map((current) => + workspaceSnapshotOf( + current.find((candidate) => candidate.instanceId === input.instanceId), + ), + ), ) - : Effect.void; + : Effect.succeed(scannedFrom); const runScan = refreshMachineSnapshot.pipe( - Effect.andThen(instance.snapshotForCwd(input.scanCwd ?? input.cwd)), + Effect.flatMap((scanBase) => + Effect.map(snapshotForCwd(input.scanCwd ?? input.cwd), (scopedSnapshot) => ({ + scanBase, + scopedSnapshot, + })), + ), // Scans fail on error; returned inventory remains valid even when provider health reports an error. - Effect.flatMap((scopedSnapshot) => + Effect.flatMap(({ scanBase, scopedSnapshot }) => instanceRegistry.getInstance(input.instanceId).pipe( Effect.flatMap((currentInstance) => { if (currentInstance !== instance) return Ref.get(providersRef); @@ -1002,18 +1167,31 @@ export const layer = Layer.effect( if (Ref.getUnsafe(workspaceRefreshesRef).get(instance)?.get(input.cwd) !== token) { return currentProviders; } - return currentProviders.map((candidate) => - candidate.instanceId === input.instanceId && - Equal.equals(workspaceSnapshotOf(candidate), scannedFrom) - ? upsertProviderWorkspaceSnapshot(candidate, input.cwd, { - ...scopedSnapshot, - checkedAt: scannedAt, - // Without driver command discovery, retain previous commands after failed health checks and retry. - slashCommandsPending: - scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error", - }) - : candidate, - ); + return currentProviders.map((candidate) => { + if ( + candidate.instanceId !== input.instanceId || + !Equal.equals(workspaceSnapshotOf(candidate), scanBase) + ) { + return candidate; + } + const scanned = upsertProviderWorkspaceSnapshot(candidate, input.cwd, { + ...scopedSnapshot, + checkedAt: scannedAt, + // Without driver command discovery, retain previous commands after failed health checks and retry. + slashCommandsPending: + scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error", + }); + // Clients keep fetched snapshots, so a changed rescan must tell them to fetch again. + const rescanned = workspaceSnapshotOf(scanned); + const held = heldBeforeWait ?? scanBase; + return input.rescan && + !( + Equal.equals(rescanned?.skills, held?.skills) && + Equal.equals(rescanned?.slashCommands, held?.slashCommands) + ) + ? { ...scanned, workspaceRescannedAt: scannedAt } + : scanned; + }); }); }), ), @@ -1056,6 +1234,11 @@ export const layer = Layer.effect( } return yield* Fiber.join(claim.scan); }); + yield* Stream.runForEach(Stream.fromQueue(workspaceRescans), ({ instance, cwd }) => + refreshWorkspaceSnapshot({ instanceId: instance.instanceId, cwd, rescan: instance }).pipe( + Effect.ignoreCause({ log: true }), + ), + ).pipe(Effect.forkScoped); const invalidateModelCaches = Effect.fn("ProviderRegistry.invalidateModelCaches")(function* ( input: Parameters[0], @@ -1107,6 +1290,8 @@ export const layer = Layer.effect( refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), reloadSecretsAndRefresh: (instanceId?: ProviderInstanceId) => reloadSecretsAndRefresh(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), + applySecretAndRefresh: (reference: SecretReference, value: string) => + applySecretAndRefresh(reference, value).pipe(Effect.catchCause(recoverRefreshFailure)), refreshWorkspaceSnapshot: (input) => refreshWorkspaceSnapshot(input).pipe(Effect.catchCause(recoverRefreshFailure)), refreshAfterUpdate, diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index f06c4f4757..5dacd1f2d9 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -15,13 +15,16 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Scope from "effect/Scope"; import * as Result from "effect/Result"; +import * as Scheduler from "effect/Scheduler"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { ChildProcessSpawner } from "effect/process"; import { describe, expect } from "vite-plus/test"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as EffectAcpErrors from "effect-acp/errors"; +import type * as EffectAcpProtocol from "effect-acp/protocol"; const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts"); @@ -44,6 +47,136 @@ const setProcessEnv = (name: string, value: string) => { }; }; +const isPromptStarted = (event: AcpSessionRuntime.AcpSessionRequestLogEvent) => + event.method === "session/prompt" && event.status === "started"; + +const isOutgoing = (tag: string) => (event: EffectAcpProtocol.AcpProtocolLogEvent) => + event.direction === "outgoing" && + event.stage === "decoded" && + typeof event.payload === "object" && + event.payload !== null && + Reflect.get(event.payload, "tag") === tag; + +// The methods the mock agent read, in order, keeping only the given ones. +const readReceived = (requestLogPath: string, methods: ReadonlyArray) => + NodeFS.readFileSync(requestLogPath, "utf8") + .split("\n") + .filter((line) => line.length > 0) + .map((line) => (JSON.parse(line) as { readonly method?: string }).method) + .filter((method) => method !== undefined && methods.includes(method)); + +// Prompts, then cancels while the prompt is held on its way out: in its started request record, +// in its outgoing protocol log record, or by its fiber yielding every few operations. The cancel +// comes on dispatch or from inside the held record. Returns the prompt's exit +// and the order in which the agent read the prompt, the cancel and the request that ends it. +const promptThenCancel = (input: { + readonly cancelBehavior: "interrupt" | "wait-for-prompt"; + readonly holdPrompt: { + readonly in: "request-log" | "protocol-log" | "scheduler"; + readonly cancelOn: "dispatch" | "log"; + }; +}) => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-")); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true })), + ); + const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); + const { holdPrompt } = input; + const promptHeld = yield* Deferred.make(); + const promptReleased = yield* Deferred.make(); + yield* Effect.addFinalizer(() => Deferred.succeed(promptReleased, undefined)); + const testScope = yield* Scope.Scope; + const runtimeMade = yield* Deferred.make(); + const cancelledFromLog = yield* Deferred.make>(); + const hold = ( + holdPrompt.cancelOn === "log" + ? Deferred.await(runtimeMade).pipe( + Effect.flatMap((made) => + made.cancel.pipe(Effect.forkIn(testScope, { startImmediately: true })), + ), + Effect.flatMap((fiber) => Deferred.succeed(cancelledFromLog, fiber)), + ) + : Effect.void + ).pipe( + Effect.andThen(Deferred.succeed(promptHeld, undefined)), + Effect.andThen(Deferred.await(promptReleased)), + ); + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + spawn: { + ...mockRuntimeOptions.spawn, + env: { + T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1", + T3_ACP_REQUEST_LOG_PATH: requestLogPath, + }, + }, + cancelBehavior: input.cancelBehavior, + interruptPromptOnCancel: false, + protocolLogging: { + logOutgoing: holdPrompt.in === "protocol-log", + logger: (event) => (isOutgoing("session/prompt")(event) ? hold : Effect.void), + }, + requestLogger: (event) => + holdPrompt.in === "request-log" && isPromptStarted(event) ? hold : Effect.void, + }); + yield* Deferred.succeed(runtimeMade, runtime); + const cancelReceived = yield* Deferred.make(); + yield* runtime.getEvents().pipe( + Stream.runForEach((event) => { + if (event._tag === "EventStreamBarrier") { + return Deferred.succeed(event.acknowledge, undefined); + } + if (event._tag === "ThoughtDelta" && event.text === "native-cancel-received") { + return Deferred.succeed(cancelReceived, undefined); + } + return Effect.void; + }), + Effect.forkChild, + ); + yield* runtime.start(); + const dispatched = yield* Deferred.make(); + const prompt = yield* runtime + .prompt({ prompt: [{ type: "text", text: "first" }] }, { dispatched }) + .pipe( + holdPrompt.in === "scheduler" + ? Effect.provideService(Scheduler.MaxOpsBeforeYield, 3) + : (effect) => effect, + Effect.forkChild, + ); + // A round trip: whatever was queued before it reaches the agent first. + const roundTrip = runtime.request("_test/environment", {}); + let cancel: Fiber.Fiber; + if (holdPrompt.in === "scheduler") { + yield* Deferred.await(dispatched); + cancel = yield* runtime.cancel.pipe(Effect.forkChild({ startImmediately: true })); + } else { + yield* Deferred.await(promptHeld); + if (holdPrompt.cancelOn === "dispatch") { + cancel = yield* Deferred.await(dispatched).pipe( + Effect.andThen(runtime.cancel), + Effect.forkChild({ startImmediately: true }), + ); + } else { + cancel = yield* Deferred.await(cancelledFromLog); + } + yield* roundTrip; + yield* Deferred.succeed(promptReleased, undefined); + } + yield* Deferred.await(cancelReceived); + yield* runtime.request("_test/finish-cancel", {}); + // The agent answers it only after reading every earlier line. + yield* roundTrip; + const received = readReceived(requestLogPath, [ + "session/prompt", + "session/cancel", + "_test/finish-cancel", + ]); + const promptExit = yield* Fiber.await(prompt); + yield* Fiber.join(cancel); + return { received, promptExit }; + }).pipe(Effect.scoped); + describe("AcpSessionRuntime", () => { it.effect.each(["session/new", "session/resume"] as const)( "buffers root metadata while %s startup is still pending", @@ -1153,6 +1286,72 @@ describe("AcpSessionRuntime", () => { ), ); + // regression: #37106 prompt sent before session/load replied + it.live("does not prompt before session/load replies after replay goes idle", () => + Effect.gen(function* () { + const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; + yield* runtime.start(); + + const result = yield* runtime.prompt({ + prompt: [{ type: "text", text: "hi" }], + }); + expect(result.stopReason).toBe("end_turn"); + }).pipe( + Effect.provide( + AcpSessionRuntime.layer({ + authMethodId: "test", + spawn: { + command: mockAgentCommand, + args: mockAgentArgs, + env: { + T3_ACP_EMIT_LOAD_REPLAY: "1", + T3_ACP_LOAD_REPLY_DELAY_MS: "500", + T3_ACP_REJECT_PROMPT_UNTIL_LOADED: "1", + }, + }, + cwd: process.cwd(), + resumeSessionId: "mock-session-1", + sessionLoadReplayIdleGap: "50 millis", + clientInfo: { name: "t3-test", version: "0.0.0" }, + }), + ), + Effect.scoped, + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ); + + it.live("treats replay idle as loaded when the agent opts in", () => + Effect.gen(function* () { + const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; + const started = yield* runtime.start(); + + expect(started.sessionSetupResult._meta).toMatchObject({ + t3SessionLoadReady: "replay_idle", + }); + }).pipe( + Effect.provide( + AcpSessionRuntime.layer({ + authMethodId: "test", + spawn: { + command: mockAgentCommand, + args: mockAgentArgs, + env: { + T3_ACP_EMIT_LOAD_REPLAY: "1", + T3_ACP_LOAD_NEVER_REPLIES: "1", + }, + }, + cwd: process.cwd(), + resumeSessionId: "mock-session-1", + sessionLoadReplayIdleGap: "50 millis", + sessionLoadReplayIdleReadiness: true, + clientInfo: { name: "t3-test", version: "0.0.0" }, + }), + ), + Effect.scoped, + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ); + it.effect("rejects invalid config option values before sending session/set_config_option", () => { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-")); const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); @@ -1239,4 +1438,104 @@ describe("AcpSessionRuntime", () => { Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))), ); }); + + it.effect.each( + (["interrupt", "wait-for-prompt"] as const).flatMap((cancelBehavior) => + ( + [ + { in: "request-log", cancelOn: "dispatch" }, + { in: "protocol-log", cancelOn: "log" }, + { in: "scheduler", cancelOn: "dispatch" }, + ] as const + ).map((holdPrompt) => ({ cancelBehavior, holdPrompt })), + ), + )( + "sends session/prompt before a cancel issued while the prompt is held in the $holdPrompt.in ($cancelBehavior, cancel on $holdPrompt.cancelOn)", + ({ cancelBehavior, holdPrompt }) => + Effect.gen(function* () { + const run = yield* promptThenCancel({ cancelBehavior, holdPrompt }); + expect(run.received).toEqual(["session/prompt", "session/cancel", "_test/finish-cancel"]); + expect(run.promptExit).toEqual( + Exit.succeed({ stopReason: "cancelled", _meta: { nativeCancel: true } }), + ); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("sends a cancel after the cancel timeout when its prompt never goes out", () => + Effect.gen(function* () { + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + interruptPromptOnCancel: false, + cancelTimeout: "5 seconds", + requestLogger: (event) => (isPromptStarted(event) ? Effect.never : Effect.void), + }); + yield* runtime.start(); + const dispatched = yield* Deferred.make(); + yield* runtime + .prompt({ prompt: [{ type: "text", text: "first" }] }, { dispatched }) + .pipe(Effect.forkChild); + yield* Deferred.await(dispatched); + const cancel = yield* runtime.cancel.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("5 seconds"); + yield* Fiber.join(cancel); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect( + "sends a cancel before the next prompt when the prompt it waited for never went out", + () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-")); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true })), + ); + const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); + let promptsStarted = 0; + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + spawn: { ...mockRuntimeOptions.spawn, env: { T3_ACP_REQUEST_LOG_PATH: requestLogPath } }, + interruptPromptOnCancel: false, + // The cancel spends a test-clock second in its outgoing record, the window in which the + // next prompt could overtake it. + protocolLogging: { + logOutgoing: true, + logger: (event) => + isOutgoing("session/cancel")(event) ? Effect.sleep("1 second") : Effect.void, + }, + requestLogger: (event) => + isPromptStarted(event) && promptsStarted++ === 0 ? Effect.never : Effect.void, + }); + yield* runtime.getEvents().pipe( + Stream.runForEach((event) => + event._tag === "EventStreamBarrier" + ? Deferred.succeed(event.acknowledge, undefined) + : Effect.void, + ), + Effect.forkChild, + ); + yield* runtime.start(); + const dispatched = yield* Deferred.make(); + const first = yield* runtime + .prompt({ prompt: [{ type: "text", text: "first" }] }, { dispatched }) + .pipe(Effect.forkChild); + yield* Deferred.await(dispatched); + const cancel = yield* runtime.cancel.pipe(Effect.forkChild({ startImmediately: true })); + const next = yield* runtime + .prompt({ prompt: [{ type: "text", text: "next" }] }) + .pipe(Effect.forkChild); + // The first prompt ends before it is queued, which releases the cancel's wait. + yield* Effect.sleep("1 second").pipe( + Effect.andThen(Fiber.interrupt(first)), + Effect.forkChild, + ); + yield* TestClock.adjust("1 second"); + yield* TestClock.adjust("1 second"); + yield* Fiber.join(cancel); + yield* Fiber.join(next); + expect(readReceived(requestLogPath, ["session/prompt", "session/cancel"])).toEqual([ + "session/cancel", + "session/prompt", + ]); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); }); diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts b/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts index 0c6bddbbf8..6b9afa7f30 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; import * as NodePath from "node:path"; import { describe, expect, it, vi } from "@effect/vitest"; @@ -813,6 +814,33 @@ describe("terminatePosixOwnedProcessTree", () => { }), ); + it.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "snapshots /proc when a process exits while its entry is being typed", + () => { + const fs = NodeModule.createRequire(import.meta.url)("node:fs") as typeof NodeFS; + const realReaddirSync = fs.readdirSync; + // Node lstat()s a dirent of unknown type; a process that exits meanwhile makes it throw. + fs.readdirSync = ((path: NodeFS.PathLike, options?: unknown) => { + if (path === "/proc" && typeof options === "object" && options !== null) { + throw Object.assign(new Error("ENOENT: no such file or directory, lstat '/proc/4563'"), { + code: "ENOENT", + syscall: "lstat", + path: "/proc/4563", + }); + } + return Reflect.apply(realReaddirSync, fs, [path, options]); + }) as typeof NodeFS.readdirSync; + NodeModule.syncBuiltinESMExports(); + try { + const snapshot = AcpSessionRuntime.makePosixProcessTreeController("linux").snapshot(); + expect(snapshot.some((entry) => entry.pid === process.pid)).toBe(true); + } finally { + fs.readdirSync = realReaddirSync; + NodeModule.syncBuiltinESMExports(); + } + }, + ); + it("fails closed where a stable POSIX identity provider is unavailable", () => { try { AcpSessionRuntime.makePosixProcessTreeController("darwin"); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 3c3d901860..dc755d1e7a 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -60,21 +60,25 @@ function makeModelRuntime( describe("Antigravity release gates", () => { it.each([ - { version: "1.4.1", filter: false, native: false, ownName: false }, - { version: "1.4.2", filter: true, native: false, ownName: false }, - { version: "1.4.4", filter: true, native: false, ownName: false }, - { version: "1.4.5", filter: true, native: true, ownName: false }, - { version: "1.4.6", filter: false, native: false, ownName: false }, - { version: "1.5.0", filter: false, native: false, ownName: false }, - { version: "1.5.1", filter: false, native: false, ownName: true }, - { version: "1.3.0", filter: false, native: false, ownName: false }, - { version: undefined, filter: false, native: false, ownName: false }, - { version: "unknown", filter: false, native: false, ownName: false }, + { version: "1.4.1", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "1.4.2", filter: true, native: false, ownName: false, advertisedAppend: false }, + { version: "1.4.4", filter: true, native: false, ownName: false, advertisedAppend: false }, + { version: "1.4.5", filter: true, native: true, ownName: false, advertisedAppend: false }, + { version: "1.4.6", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "1.5.0", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "1.5.1", filter: false, native: false, ownName: true, advertisedAppend: false }, + { version: "1.5.7", filter: false, native: false, ownName: true, advertisedAppend: true }, + { version: "1.3.0", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: undefined, filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "unknown", filter: false, native: false, ownName: false, advertisedAppend: false }, ])( - "$version: workflow filter $filter, native reads and system prompt $native, own client name $ownName", - ({ version, filter, native, ownName }) => { + "$version: workflow filter $filter, qualified reads $native, advertised system append $advertisedAppend, own client name $ownName", + ({ version, filter, native, ownName, advertisedAppend }) => { const initialize = { protocolVersion: 1, + ...(advertisedAppend + ? { agentCapabilities: { _meta: { antigravity: { systemPrompt: { append: true } } } } } + : {}), ...(version === undefined ? {} : { agentInfo: { name: "antigravity-acp", version } }), }; // Helpers send no append, so only the workflow filter can apply. @@ -83,10 +87,12 @@ describe("Antigravity release gates", () => { ); const antigravity = { ...(filter ? { disabledTools: ["run_workflow"] } : {}), - ...(native ? { systemPrompt: { append: "" } } : {}), + ...(native || advertisedAppend + ? { systemPrompt: { append: "" } } + : {}), }; expect(antigravitySessionMeta(initialize, "")).toEqual( - filter || native ? { antigravity } : undefined, + filter || native || advertisedAppend ? { antigravity } : undefined, ); expect(isQualifiedAntigravityRelease(version)).toBe(native); expect(antigravityClientInfo(version).name).toBe(ownName ? "t3-code" : "zed"); @@ -529,7 +535,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => { }), ); - it.effect.each([undefined, {}, { image: false }, { image: true }])( + it.effect.each([{ image: true }])( "keeps unsupported image formats path-only with capabilities %s", (promptCapabilities) => Effect.gen(function* () { diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index aec2a4c2b4..c0051fd0ae 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -12,6 +12,7 @@ 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 Predicate from "effect/Predicate"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -94,7 +95,15 @@ const OPEN_MODEL_ACCESS_RELEASE = [1, 5, 1] as const; */ export const antigravityAppendsSystemPrompt = ( initializeResult: EffectAcpSchema.InitializeResponse, -) => isQualifiedAntigravityRelease(initializeResult.agentInfo?.version); +) => { + if (isQualifiedAntigravityRelease(initializeResult.agentInfo?.version)) return true; + const extension = initializeResult.agentCapabilities?._meta?.antigravity; + return ( + Predicate.isObject(extension) && + Predicate.isObject(extension.systemPrompt) && + extension.systemPrompt.append === true + ); +}; export function antigravitySessionMeta( initializeResult: EffectAcpSchema.InitializeResponse, diff --git a/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts b/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts index 795e80b861..81885dc0c8 100644 --- a/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts +++ b/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts @@ -31,7 +31,7 @@ it.layer(NodeServices.layer)("retireAntigravityRuntimeTempDirs", (it) => { yield* removeRetired; expect((yield* fs.readDirectory(parent)).toSorted()).toEqual(["other-instance"]); - }).pipe(Effect.scoped), + }), ); it.effect( diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index 09b8730bd6..52e96caa08 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -158,7 +158,7 @@ describe("watchAntigravityPromptOutcome", () => { code: "QUOTA_EXHAUSTED", retryable: true, }); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("reads only this session's own unlinked log, and keeps a typed refusal", () => @@ -206,6 +206,6 @@ describe("watchAntigravityPromptOutcome", () => { code: "QUOTA_EXHAUSTED", retryable: true, }); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 309ee12afc..5bd6f7267e 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { - "claudeSystemAppendBytes": 5597, - "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 48973 + "claudeSystemAppendBytes": 5930, + "codexAdditionalContextBytes": 7324, + "mcpToolListJsonBytes": 50529 } diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index 0220f9fd15..832f2961d8 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -118,7 +118,13 @@ describe("Antigravity process environment", () => { }); expect(spawn.command).toBe("/usr/bin/agy"); - expect(spawn.args).toEqual(["acp"]); + expect(spawn.args).toEqual([ + "acp", + "--gemini-dir", + profile.geminiHome, + "--app-data-dir", + "antigravity-acp", + ]); expect(spawn.env).not.toHaveProperty("ANTIGRAVITY_HARNESS_PATH"); expect(spawn.env).toMatchObject({ GEMINI_HOME: profile.geminiHome, PATH: "/usr/bin" }); }); diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 6a926b12f7..8d78a504f9 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -467,7 +467,14 @@ export function buildAntigravityAcpSpawnInput(input: { // The agy CLI has no harness sibling and serves ACP through its `acp` subcommand. args: input.installation.harnessPath === null - ? ["acp"] + ? [ + "acp", + "--gemini-dir", + input.profile.geminiHome, + "--app-data-dir", + // The CLI joins this beneath gemini-dir, including when the value is absolute. + "antigravity-acp", + ] : input.profile.platform === "linux" ? ["--uid="] : [], diff --git a/apps/server/src/provider/antigravityCliRelease.test.ts b/apps/server/src/provider/antigravityCliRelease.test.ts new file mode 100644 index 0000000000..2e1e0010c2 --- /dev/null +++ b/apps/server/src/provider/antigravityCliRelease.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "@effect/vitest"; +import { antigravityCliTarget, parseAntigravityCliRelease } from "./antigravityCliRelease.ts"; + +const manifest = { + version: "1.5.7", + url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.7-123/darwin-arm/cli_mac_arm64.tar.gz", + sha512: "a".repeat(128), +}; + +describe("Antigravity CLI release manifests", () => { + it.each([ + ["darwin", "arm64", false, "darwin_arm64", "darwin-arm/cli_mac_arm64.tar.gz"], + ["darwin", "x64", false, "darwin_amd64", "darwin-x64/cli_mac_x64.tar.gz"], + ["linux", "arm64", false, "linux_arm64", "linux-arm/cli_linux_arm64.tar.gz"], + ["linux", "x64", false, "linux_amd64", "linux-x64/cli_linux_x64.tar.gz"], + ["linux", "arm64", true, "linux_arm64_musl", "linux-arm-musl/cli_linux_arm64_musl.tar.gz"], + ["linux", "x64", true, "linux_amd64_musl", "linux-x64-musl/cli_linux_x64_musl.tar.gz"], + ["win32", "arm64", false, "windows_arm64", "windows-arm/cli_windows_arm64.exe"], + ["win32", "x64", false, "windows_amd64", "windows-x64/cli_windows_x64.exe"], + ] as const)("selects Google's %s-%s release (musl %s)", (platform, arch, musl, target, file) => { + expect(antigravityCliTarget(platform, arch, musl)).toBe(target); + expect( + parseAntigravityCliRelease( + { + ...manifest, + url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.7-123/${file}`, + }, + platform, + arch, + musl, + ), + ).toMatchObject({ + version: "1.5.7", + format: platform === "win32" ? "executable" : "tar.gz", + executable: { name: platform === "win32" ? "agy.exe" : "antigravity" }, + }); + }); + + it.each([ + { sha512: "invalid" }, + { version: "1.4.5" }, + { url: manifest.url.replace("https:", "http:") }, + { url: manifest.url.replace("storage.googleapis.com", "storage.googleapis.com.evil.test") }, + { url: manifest.url.replace("antigravity-public", "another-bucket") }, + { url: manifest.url.replace("darwin-arm", "linux-arm") }, + { url: `${manifest.url}?redirect=elsewhere` }, + { url: manifest.url.replace("1.5.7-123", "1.5.6-123") }, + ])("rejects invalid or mismatched release metadata: %j", (change) => { + expect(parseAntigravityCliRelease({ ...manifest, ...change }, "darwin", "arm64")).toBeNull(); + }); +}); diff --git a/apps/server/src/provider/antigravityCliRelease.ts b/apps/server/src/provider/antigravityCliRelease.ts new file mode 100644 index 0000000000..3e033beb37 --- /dev/null +++ b/apps/server/src/provider/antigravityCliRelease.ts @@ -0,0 +1,60 @@ +import * as Schema from "effect/Schema"; +import { compareSemverVersions } from "@t3tools/shared/semver"; + +export const ANTIGRAVITY_CLI_MANIFEST_BASE = + "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests"; + +const Manifest = Schema.Struct({ + version: Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+$/u)), + url: Schema.String, + sha512: Schema.String.check(Schema.isPattern(/^[a-fA-F0-9]{128}$/u)), +}); +const decodeManifest = Schema.decodeUnknownOption(Manifest); + +export interface AntigravityCliReleaseAsset { + readonly version: string; + readonly url: string; + readonly sha512: string; + readonly executable: { readonly name: string }; + readonly format: "tar.gz" | "executable"; +} + +export function antigravityCliTarget(platform: NodeJS.Platform, arch: string, musl = false) { + if (!["darwin", "linux", "win32"].includes(platform) || !["x64", "arm64"].includes(arch)) { + return null; + } + const os = platform === "win32" ? "windows" : platform; + return `${os}_${arch === "x64" ? "amd64" : arch}${platform === "linux" && musl ? "_musl" : ""}`; +} + +export function parseAntigravityCliRelease( + value: unknown, + platform: NodeJS.Platform, + arch: string, + musl = false, +): AntigravityCliReleaseAsset | null { + const decoded = decodeManifest(value); + if (decoded._tag === "None" || antigravityCliTarget(platform, arch, musl) === null) return null; + const manifest = decoded.value; + if (compareSemverVersions(manifest.version, "1.5.0") < 0) return null; + const os = platform === "darwin" ? "mac" : platform === "win32" ? "windows" : "linux"; + const cpu = arch === "x64" ? "x64" : "arm64"; + const suffix = platform === "linux" && musl ? "_musl" : ""; + const extension = platform === "win32" ? "exe" : "tar.gz"; + const folder = `${platform === "win32" ? "windows" : platform}-${arch === "arm64" ? "arm" : "x64"}${suffix ? "-musl" : ""}`; + const prefix = `https://storage.googleapis.com/antigravity-public/antigravity-cli/${manifest.version}-`; + const rest = manifest.url.startsWith(prefix) ? manifest.url.slice(prefix.length) : ""; + if ( + !/^\d+\//u.test(rest) || + rest.replace(/^\d+\//u, "") !== `${folder}/cli_${os}_${cpu}${suffix}.${extension}` + ) { + return null; + } + return { + version: manifest.version, + url: manifest.url, + sha512: manifest.sha512.toLowerCase(), + executable: { name: platform === "win32" ? "agy.exe" : "antigravity" }, + format: platform === "win32" ? "executable" : "tar.gz", + }; +} diff --git a/apps/server/src/provider/antigravityRelease.ts b/apps/server/src/provider/antigravityRelease.ts index 255a927619..54702d6993 100644 --- a/apps/server/src/provider/antigravityRelease.ts +++ b/apps/server/src/provider/antigravityRelease.ts @@ -1,7 +1,3 @@ -// Hashes and sizes match the official ACP registry release. Like 1.4.2 through 1.4.4, it writes a -// run-workflow skill into the workspace unless T3 disables the tool (antigravitySessionMeta). -const ANTIGRAVITY_RELEASE_VERSION = "1.4.5"; - export interface AntigravityReleaseAsset { readonly version: string; readonly url: string; @@ -16,79 +12,3 @@ export interface AntigravityReleaseAsset { readonly bytes: number; }; } - -const releaseAssets = new Map([ - [ - "darwin-arm64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-arm64.zip", - sha256: "886fff7767d08994ca39eb02c3d01a7532c7325a94aa33aaf52d52068733284f", - archiveBytes: 97_923_855, - executable: { name: "agy_acp_server.par", bytes: 178_915_920 }, - harness: { name: "localharness_external", bytes: 122_957_936 }, - }, - ], - [ - "darwin-x64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-x86_64.zip", - sha256: "b39f3573c03b9acb9df028853f647527f1f3133f32bd77e78b796e48a205114a", - archiveBytes: 103_577_295, - executable: { name: "agy_acp_server.par", bytes: 183_127_600 }, - harness: { name: "localharness_external", bytes: 127_612_208 }, - }, - ], - [ - "linux-x64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-x86_64.zip", - sha256: "923923a0d7dc8073f66cc6f78647a3107e3a7ee2b7e1a24df8b3927b5188013b", - archiveBytes: 321_783_181, - executable: { name: "agy_acp_server.par", bytes: 826_226_766 }, - harness: { name: "localharness_external", bytes: 133_926_136 }, - }, - ], - [ - "linux-arm64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-arm64.zip", - sha256: "7d64246633ae094f67e3bbcd2d679e89048f91346d5339313336e7483f40f056", - archiveBytes: 307_829_008, - executable: { name: "agy_acp_server.par", bytes: 831_194_025 }, - harness: { name: "localharness_external", bytes: 127_512_832 }, - }, - ], - [ - "win32-x64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-x86_64.zip", - sha256: "d24f4c73c9f96d4f44384e281c855a56c72d8eaa9c5b0fad7ccb1635c6b63f50", - archiveBytes: 100_423_655, - executable: { name: "agy_acp_server.exe", bytes: 55_839_864 }, - harness: { name: "localharness_external.exe", bytes: 147_843_736 }, - }, - ], - [ - "win32-arm64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-arm64.zip", - sha256: "ab0a9aac8349e08ef289be6d16da8f89e3abe60eba5158032ef78c4a1220261c", - archiveBytes: 102_703_121, - executable: { name: "agy_acp_server.exe", bytes: 62_293_488 }, - harness: { name: "localharness_external.exe", bytes: 139_322_008 }, - }, - ], -]); - -export function resolveAntigravityReleaseAsset( - platform: NodeJS.Platform, - arch: string, -): AntigravityReleaseAsset | null { - return releaseAssets.get(`${platform}-${arch}`) ?? null; -} diff --git a/apps/server/src/provider/claudeResetCredits.ts b/apps/server/src/provider/claudeResetCredits.ts index e1dbacc34b..d2000804cf 100644 --- a/apps/server/src/provider/claudeResetCredits.ts +++ b/apps/server/src/provider/claudeResetCredits.ts @@ -23,7 +23,10 @@ const Credentials = Schema.Struct({ }); const Config = Schema.Struct({ oauthAccount: Schema.optional( - Schema.Struct({ organizationUuid: Schema.optional(Schema.String) }), + Schema.Struct({ + organizationUuid: Schema.optional(Schema.String), + accountUuid: Schema.optional(Schema.Unknown), + }), ), }); const Grant = Schema.Struct({ @@ -226,12 +229,17 @@ export const readClaudeResetCredits = Effect.fn("readClaudeResetCredits")( Effect.orElseSucceed(() => undefined), ); -export const readClaudeOrganizationId = (accountConfigPath: string) => +export const readClaudeOauthAccount = (accountConfigPath: string) => readJson(Config, accountConfigPath).pipe( - Effect.map((config) => config.oauthAccount?.organizationUuid?.trim() || undefined), + Effect.map((config) => config.oauthAccount), Effect.orElseSucceed(() => undefined), ); +export const readClaudeOrganizationId = (accountConfigPath: string) => + readClaudeOauthAccount(accountConfigPath).pipe( + Effect.map((account) => account?.organizationUuid?.trim() || undefined), + ); + export const claudeAccountConfigPath = Effect.fn("claudeAccountConfigPath")(function* ( configDir: string | undefined, ) { diff --git a/apps/server/src/provider/claudeUsageLimits.test.ts b/apps/server/src/provider/claudeUsageLimits.test.ts index f20d8b0543..b683c80f4f 100644 --- a/apps/server/src/provider/claudeUsageLimits.test.ts +++ b/apps/server/src/provider/claudeUsageLimits.test.ts @@ -199,6 +199,22 @@ describe("claudeUsageResponseToLimits", () => { ).toEqual([monthlyWindow]); }); + it("flags a $0 cap instead of reporting a monthly window", () => { + const response = { + rate_limits_available: true, + rate_limits: { + five_hour: null, + seven_day: null, + extra_usage: { is_enabled: true, used_credits: 0, monthly_limit: 0, utilization: null }, + }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits).toEqual({ + checkedAt, + windows: [], + zeroSpendCap: true, + }); + }); + it("omits disabled budgets and refuses invalid money without an enabled fallback", () => { const rateLimits = enterpriseResponse.rate_limits; const response = { diff --git a/apps/server/src/provider/claudeUsageLimits.ts b/apps/server/src/provider/claudeUsageLimits.ts index d0acf43bb4..ba1263ef70 100644 --- a/apps/server/src/provider/claudeUsageLimits.ts +++ b/apps/server/src/provider/claudeUsageLimits.ts @@ -47,8 +47,20 @@ export const makeClaudeScopedLimitNames = Ref.make({ overageIncluded: undefined, }); +const SCOPED_WINDOW_PREFIX = "seven_day_"; +const scopeToken = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, "_"); + function scopedWindowId(displayName: string): string { - return `seven_day_${displayName.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`; + return `${SCOPED_WINDOW_PREFIX}${scopeToken(displayName)}`; +} + +/** A model-scoped weekly allowance blocks only its own model; an unknown model is not blocked. */ +export function windowLimitsModel( + window: Pick, + model: string | null, +): boolean { + if (!window.id.startsWith(SCOPED_WINDOW_PREFIX)) return true; + return model !== null && scopeToken(model).includes(window.id.slice(SCOPED_WINDOW_PREFIX.length)); } function scopedWindow( @@ -202,6 +214,7 @@ export function claudeUsageResponseToLimits(input: { overageIncluded ??= entry.display_name; } const spendPercent = readSpendPercent(response.rate_limits); + const extra = response.rate_limits.extra_usage; if (spendPercent !== undefined) { windows.push({ id: "monthly_spend", @@ -211,7 +224,10 @@ export function claudeUsageResponseToLimits(input: { }); } return { - limits: makeUsageLimits({ checkedAt, windows }), + limits: { + ...makeUsageLimits({ checkedAt, windows }), + ...(extra?.is_enabled && extra.monthly_limit === 0 ? { zeroSpendCap: true } : {}), + }, names: { overageIncluded }, }; } diff --git a/apps/server/src/provider/codexLaunchArgs.test.ts b/apps/server/src/provider/codexLaunchArgs.test.ts index ce18c8f3f1..e74b29d448 100644 --- a/apps/server/src/provider/codexLaunchArgs.test.ts +++ b/apps/server/src/provider/codexLaunchArgs.test.ts @@ -2,14 +2,31 @@ import * as NodeAssert from "node:assert/strict"; import { describe, it } from "vite-plus/test"; -import { codexAppServerArgs, codexExecLaunchArgs } from "./codexLaunchArgs.ts"; +import { + codexAppServerArgs, + codexExecLaunchArgs, + codexMcpListLaunchArgs, +} from "./codexLaunchArgs.ts"; describe("codexAppServerArgs", () => { - it("preserves escaped TOML quotes in config values", () => { - NodeAssert.deepStrictEqual( - codexAppServerArgs(String.raw`--config model=\"gpt-6.1-sol\" --strict-config`), - ["app-server", "--config", 'model="gpt-6.1-sol"', "--strict-config"], - ); + it.each([ + { + name: "preserves escaped TOML quotes in config values", + launchArgs: String.raw`--config model=\"gpt-6.1-sol\" --strict-config`, + expected: ["--config", 'model="gpt-6.1-sol"', "--strict-config"], + }, + { + name: "lets launch args override the unload delay", + launchArgs: "-c thread_unload_delay_secs=1800", + expected: ["-c", "thread_unload_delay_secs=1800"], + }, + ])("asks Codex to unload unsubscribed threads immediately and $name", (row) => { + NodeAssert.deepStrictEqual(codexAppServerArgs(row.launchArgs), [ + "app-server", + "-c", + "thread_unload_delay_secs=0", + ...row.expected, + ]); }); }); @@ -21,9 +38,47 @@ describe("codexExecLaunchArgs", () => { ); }); + it("drops launch args that enable user hooks", () => { + NodeAssert.deepStrictEqual( + codexExecLaunchArgs( + "--enable hooks --enable=hooks --enable codex_hooks --enable=codex_hooks --enable foo --disable hooks", + ), + ["--enable", "foo", "--disable", "hooks"], + ); + }); + it("does not pair value-taking flags with adjacent flags", () => { NodeAssert.deepStrictEqual(codexExecLaunchArgs("--config --strict-config --enable --disable"), [ "--strict-config", ]); }); }); + +describe("codex exec and mcp list launch args", () => { + const launchArgs = + "--strict-config --oss --local-provider ollama --profile local -p=work --listen off --enable foo"; + + it("keeps the local model provider flags for codex exec", () => { + NodeAssert.deepStrictEqual(codexExecLaunchArgs(launchArgs), [ + "--strict-config", + "--oss", + "--local-provider", + "ollama", + "--profile", + "local", + "-p=work", + "--enable", + "foo", + ]); + }); + + it("keeps the selected profile and drops exec-only flags for codex mcp list", () => { + NodeAssert.deepStrictEqual(codexMcpListLaunchArgs(launchArgs), [ + "--profile", + "local", + "-p=work", + "--enable", + "foo", + ]); + }); +}); diff --git a/apps/server/src/provider/codexLaunchArgs.ts b/apps/server/src/provider/codexLaunchArgs.ts index 33def5ce9a..e49314ee83 100644 --- a/apps/server/src/provider/codexLaunchArgs.ts +++ b/apps/server/src/provider/codexLaunchArgs.ts @@ -9,31 +9,70 @@ export const resolveCodexLaunchArgs = ( const codexLaunchArgv = (launchArgs?: string): ReadonlyArray => tokenizeCliArgs(launchArgs); +// T3 unsubscribes only when it unloads a thread; Codex's own unload delay would stack on that. export const codexAppServerArgs = (launchArgs?: string) => [ "app-server", + "-c", + "thread_unload_delay_secs=0", ...codexLaunchArgv(launchArgs), ]; -export const codexExecLaunchArgs = (launchArgs?: string) => { +interface LaunchArgFilter { + readonly switches: ReadonlySet; + readonly valueFlags: ReadonlySet; + readonly inlinePrefixes: ReadonlyArray; +} + +const SHARED_VALUE_FLAGS = ["--config", "-c", "--enable", "--disable"]; +const SHARED_INLINE_PREFIXES = ["--config=", "-c=", "--enable=", "--disable="]; + +const MCP_LIST_FILTER: LaunchArgFilter = { + switches: new Set(), + valueFlags: new Set([...SHARED_VALUE_FLAGS, "--profile", "-p"]), + inlinePrefixes: [...SHARED_INLINE_PREFIXES, "--profile=", "-p="], +}; + +const EXEC_FILTER: LaunchArgFilter = { + switches: new Set(["--strict-config", "--oss"]), + valueFlags: new Set([...SHARED_VALUE_FLAGS, "--local-provider", "--profile", "-p"]), + inlinePrefixes: [...SHARED_INLINE_PREFIXES, "--local-provider=", "--profile=", "-p="], +}; + +const filterLaunchArgs = (launchArgs: string | undefined, allowed: LaunchArgFilter) => { const args = codexLaunchArgv(launchArgs); - const execArgs: Array = []; + const kept: Array = []; for (let index = 0; index < args.length; index++) { const arg = args[index]; if (arg === undefined) continue; - if (arg === "--strict-config" || arg.startsWith("--config=") || arg.startsWith("-c=")) { - execArgs.push(arg); - } else if (arg === "--config" || arg === "-c" || arg === "--enable" || arg === "--disable") { + if (allowed.switches.has(arg)) { + kept.push(arg); + } else if (allowed.valueFlags.has(arg)) { const value = args[index + 1]; if (value !== undefined && !value.startsWith("-")) { - execArgs.push(arg, value); + kept.push(arg, value); index++; } - } else if (arg.startsWith("--enable=") || arg.startsWith("--disable=")) { - execArgs.push(arg); + } else if (allowed.inlinePrefixes.some((prefix) => arg.startsWith(prefix))) { + kept.push(arg); } } - return execArgs; + return kept; +}; + +const HOOK_FEATURES = new Set(["hooks", "codex_hooks"]); + +// Feature toggles beat config overrides, so a launch arg's hook enable would undo ours. +export const codexExecLaunchArgs = (launchArgs?: string) => { + const args = filterLaunchArgs(launchArgs, EXEC_FILTER); + return args.filter((arg, index) => { + if (arg.startsWith("--enable=")) return !HOOK_FEATURES.has(arg.slice("--enable=".length)); + if (arg === "--enable") return !HOOK_FEATURES.has(args[index + 1] ?? ""); + return !(args[index - 1] === "--enable" && HOOK_FEATURES.has(arg)); + }); }; + +export const codexMcpListLaunchArgs = (launchArgs?: string) => + filterLaunchArgs(launchArgs, MCP_LIST_FILTER); diff --git a/apps/server/src/provider/codexUsageLimits.test.ts b/apps/server/src/provider/codexUsageLimits.test.ts index 9c863f54c0..3a5cae4a9d 100644 --- a/apps/server/src/provider/codexUsageLimits.test.ts +++ b/apps/server/src/provider/codexUsageLimits.test.ts @@ -1,10 +1,15 @@ +import * as DateTime from "effect/DateTime"; +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { exhaustedUsageWindow } from "@t3tools/shared/usageLimits"; import * as CodexErrors from "effect-codex-app-server/errors"; import { describe, expect, it } from "vite-plus/test"; import { + codexMessageResetAt, codexRateLimitsFailureMessage, codexRateLimitsToLimits, codexRateLimitsToUpdate, + codexTimeZone, mergeCodexRateLimits, } from "./codexUsageLimits.ts"; @@ -39,6 +44,40 @@ describe("codexRateLimitsToLimits", () => { expect(codexRateLimitsToUpdate(snapshot)).toEqual({ windows }); }); + it("keeps a seat-based workspace with a zero credit cap usable while its plan windows have room", () => { + const usageLimits = codexRateLimitsToLimits({ + checkedAt, + snapshot: { + limitId: "codex", + planType: "team", + rateLimitReachedType: null, + primary: { usedPercent: 0, resetsAt: 1_784_000_000, windowDurationMins: 300 }, + secondary: { usedPercent: 14, resetsAt: 1_784_500_000, windowDurationMins: 10080 }, + individualLimit: { remainingPercent: 0, resetsAt: 1_796_083_200 }, + }, + }); + expect( + exhaustedUsageWindow( + { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt, + models: [], + slashCommands: [], + skills: [], + usageLimits, + }, + Date.parse(checkedAt), + "gpt-6.1-sol", + ), + ).toBeUndefined(); + }); + it("maps primary and secondary onto the session and weekly windows", () => { expect( codexRateLimitsToLimits({ @@ -277,3 +316,61 @@ describe("codexUsageLimitResetAt", () => { ).toBeNull(); }); }); + +describe("codexMessageResetAt", () => { + const dhaka = DateTime.zoneMakeNamedUnsafe("Asia/Dhaka"); + const at = (iso: string) => DateTime.makeUnsafe(iso); + const failedAt = at("2026-11-07T03:00:00Z"); // 09:00 in Dhaka + + // Codex prints local time without seconds, so the parsed reset is the minute after. + it("reads Codex's same-day and dated reset text in Codex's zone", () => { + expect( + codexMessageResetAt("You’ve hit your usage limit. Try again at 3:37 PM.", failedAt, dhaka), + ).toBe("2026-11-07T09:38:00.000Z"); + expect( + codexMessageResetAt("Upgrade, or try again at Dec 1st, 2026 12:05 AM.", failedAt, dhaka), + ).toBe("2026-11-30T18:06:00.000Z"); + expect(codexMessageResetAt("Try again at 12:30 PM.", failedAt, dhaka)).toBe( + "2026-11-07T06:31:00.000Z", + ); + }); + + it("dates today's form by when Codex failed, across local midnight", () => { + expect(codexMessageResetAt("Try again at 11:59 PM.", at("2026-11-07T17:59:59Z"), dhaka)).toBe( + "2026-11-07T18:00:00.000Z", + ); + }); + + it("takes the later instant of a repeated DST hour", () => { + // 1:30 AM occurs twice in New York on Nov 1st, 2026: 05:30Z (EDT) and 06:30Z (EST). + const newYork = DateTime.zoneMakeNamedUnsafe("America/New_York"); + for (const iso of ["2026-11-01T05:15:00Z", "2026-11-01T06:15:00Z"]) { + expect(codexMessageResetAt("Try again at 1:30 AM.", at(iso), newYork)).toBe( + "2026-11-01T06:31:00.000Z", + ); + } + }); + + it("leaves the reset unknown without reset text or once it has passed", () => { + expect( + codexMessageResetAt("You’ve hit your usage limit. Try again later.", failedAt, dhaka), + ).toBeNull(); + expect( + codexMessageResetAt( + "exceeded retry limit, last status: 429 Too Many Requests", + failedAt, + dhaka, + ), + ).toBeNull(); + expect(codexMessageResetAt("Try again at 8:15 AM.", failedAt, dhaka)).toBeNull(); + }); +}); + +describe("codexTimeZone", () => { + it("uses Codex's TZ and falls back to the server's zone", () => { + const local = DateTime.zoneToString(DateTime.zoneMakeLocal()); + expect(DateTime.zoneToString(codexTimeZone({ TZ: ":Asia/Dhaka" }))).toBe("Asia/Dhaka"); + expect(DateTime.zoneToString(codexTimeZone({ TZ: "not/a-zone" }))).toBe(local); + expect(DateTime.zoneToString(codexTimeZone({}))).toBe(local); + }); +}); diff --git a/apps/server/src/provider/codexUsageLimits.ts b/apps/server/src/provider/codexUsageLimits.ts index d4f9c62111..5268523320 100644 --- a/apps/server/src/provider/codexUsageLimits.ts +++ b/apps/server/src/provider/codexUsageLimits.ts @@ -201,3 +201,51 @@ export function codexUsageLimitResetAt( null, ); } + +const CODEX_RESET_TEXT = + /[Tt]ry again at (?:([A-Z][a-z]{2}) (\d{1,2})(?:st|nd|rd|th), (\d{4}) )?(\d{1,2}):(\d{2}) ([AP]M)\./; +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** The zone Codex prints reset times in: its own `TZ`, else the server's. */ +export function codexTimeZone( + environment: Readonly>, +): DateTime.TimeZone { + return Option.getOrElse( + DateTime.zoneMakeNamed(environment.TZ?.replace(/^:/, "") ?? ""), + DateTime.zoneMakeLocal, + ); +} + +/** + * Codex writes a usage limit's reset into its error text in its own local time: + * "Try again at 3:37 PM." for today, else "try again at Nov 11th, 2026 3:37 PM.". + * It is the only reset left when a proxy such as CLIProxyAPI strips the rate-limit snapshot. + * `failedAt` is when Codex reported the failure, which fixes the date of today's form. + */ +export function codexMessageResetAt( + message: string, + failedAt: DateTime.DateTime, + zone: DateTime.TimeZone, +): string | null { + const match = CODEX_RESET_TEXT.exec(message); + if (!match) return null; + const [, month, day, year, hour, minute, meridiem] = match; + const monthIndex = month === undefined ? undefined : MONTHS.indexOf(month); + if (monthIndex === -1) return null; + const today = DateTime.toParts(DateTime.setZone(failedAt, zone)); + const reset = DateTime.makeZoned( + { + year: monthIndex === undefined ? today.year : Number(year), + month: monthIndex === undefined ? today.month : monthIndex + 1, + day: monthIndex === undefined ? today.day : Number(day), + hour: (Number(hour) % 12) + (meridiem === "PM" ? 12 : 0), + minute: Number(minute), + }, + // The repeated hour at a DST fall-back takes its later instant so a resume never fires early. + { timeZone: zone, adjustForTimeZone: true, disambiguation: "later" }, + ); + if (Option.isNone(reset)) return null; + // Codex drops the seconds, so the next minute is the first one past the reset. + const resetAt = DateTime.add(reset.value, { minutes: 1 }); + return DateTime.isGreaterThan(resetAt, failedAt) ? DateTime.formatIso(resetAt) : null; +} diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 81008be757..5957fdd3cd 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -14,9 +14,10 @@ const CELL_END = Symbol("cell-end"); type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: string }; const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]"; -// Parts the document never displays: tracked deletions and moves, field codes, phonetic guides, -// paragraph properties such as tab-stop definitions. +// Parts the document never displays: the XHTML head, tracked deletions and moves, field codes, +// phonetic guides, paragraph properties such as tab-stop definitions. const HIDDEN = new Set([ + "head", "script", "style", "binary-data", @@ -41,12 +42,43 @@ interface XmlNode { hasTextChoice?: boolean; } -function xml(source: string, odfSpaces = false, htmlEntities = false): XmlNode { +// ODF 1.3 Part 3 §6.1.2: paragraph character data turns TAB, CR and LF into spaces, collapses +// space runs and trims the ends; only , and keep literal ones. +function collapseOdfWhitespace(paragraph: XmlNode) { + let afterSpace = true; + let tail: { node: XmlNode; index: number; value: string } | undefined; + const visit = (node: XmlNode) => { + for (const [index, child] of node.children.entries()) { + if (typeof child !== "string") { + if (HIDDEN.has(child.name)) continue; + if (child.spaceCount === undefined && !["tab", "line-break", "p", "h"].includes(child.name)) + visit(child); + else { + afterSpace = false; + tail = undefined; + } + continue; + } + let value = child.replaceAll(/[ \t\r\n]+/g, " "); + if (afterSpace && value.startsWith(" ")) value = value.slice(1); + if (value) { + afterSpace = value.endsWith(" "); + tail = { node, index, value }; + } + node.children[index] = value; + } + }; + visit(paragraph); + if (tail && afterSpace) tail.node.children[tail.index] = tail.value.slice(0, -1); +} + +function xml(source: string, extension: string): XmlNode { + const odf = [".odt", ".ods", ".odp"].includes(extension); const root: XmlNode = { name: "root", attrs: {}, children: [] }; const stack = [root]; let nodes = 0; const parser = new SaxesParser(); - if (htmlEntities) Object.assign(parser.ENTITIES, characterEntities); + if (extension === ".epub") Object.assign(parser.ENTITIES, characterEntities); parser.on("opentag", (tag) => { if (++nodes > 200_000 || stack.length > 128) throw new Truncation("XML structure limit"); const node: XmlNode = { @@ -59,20 +91,25 @@ function xml(source: string, odfSpaces = false, htmlEntities = false): XmlNode { ), children: [], }; - if (odfSpaces && node.name === "s") node.spaceCount = repeatCount(node.attrs.c); + if (odf && node.name === "s") node.spaceCount = repeatCount(node.attrs.c); stack.at(-1)!.children.push(node); stack.push(node); }); parser.on("closetag", () => { const node = stack.pop()!; const parent = stack.at(-1)!; + if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); + if (extension === ".docx" && node.name === "del") { + parent.children.pop(); + return; + } // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes. // Keep one when no Choice carries text, such as a chart with a VML caption. if (node.name === "Fallback" && parent.hasTextChoice) { parent.children.pop(); return; } - if (!node.hasText) return; + if (!node.hasText && node.name !== "noBreakHyphen") return; parent.hasText = true; if (node.name === "Choice") parent.hasTextChoice = true; }); @@ -99,6 +136,7 @@ function* text(node: XmlNode): Generator { if (HIDDEN.has(node.name)) return; if (["tab", "cell"].includes(node.name)) yield "\t"; else if (["br", "line-break", "cr"].includes(node.name)) yield "\n"; + else if (node.name === "noBreakHyphen") yield "\u2011"; else if (node.spaceCount !== undefined) { yield " ".repeat(Math.min(MAX_OUTPUT, node.spaceCount)); if (node.spaceCount > MAX_OUTPUT) throw new Truncation("Space repeat limit"); @@ -108,6 +146,23 @@ function* text(node: XmlNode): Generator { else yield* text(child); } } +// SpreadsheetML `t` and `v` values are ST_Xstring: `_xHHHH_` is one UTF-16 code unit, and an +// escaped lead underscore (`_x005F_xHHHH_`) keeps the literal `_xHHHH_`. Decoded in one pass. +function* xstringText(node: XmlNode): Generator { + if (HIDDEN.has(node.name)) return; + if (node.name !== "t" && node.name !== "v") { + for (const child of children(node)) yield* xstringText(child); + return; + } + yield node.children + .filter((child) => typeof child === "string") + .join("") + .replaceAll( + /_x005[Ff]_(x[\dA-Fa-f]{4}_)|_x([\dA-Fa-f]{4})_/g, + (_, literal?: string, hex?: string) => + literal ? `_${literal}` : String.fromCharCode(Number.parseInt(hex!, 16)), + ); +} function* paragraphs(node: XmlNode): Generator { if (HIDDEN.has(node.name)) return; for (const child of node.children) { @@ -164,7 +219,7 @@ function odfValue(cell: XmlNode): string { } } function hasCellText(cell: XmlNode): boolean { - if (odfValue(cell).trim()) return true; + if (odfValue(cell).trim() || cell.name === "noBreakHyphen") return true; // Space markers can have enormous repeat counts; emptiness never requires expanding them. if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false; return cell.children.some((child) => @@ -342,6 +397,10 @@ function* rtf(source: string): Generator { ["ldblquote", "“"], ["rdblquote", "”"], ["bullet", "•"], + ["zwj", "\u200d"], + ["zwnj", "\u200c"], + ["ltrmark", "\u200e"], + ["rtlmark", "\u200f"], ["~", "\u00a0"], ["_", "\u2011"], ["-", ""], @@ -437,7 +496,7 @@ async function* document(path: string, extension: string): AsyncGenerator typeof child === "string") ?? ""; if (cell.attrs.t === "s") { const shared = strings[Number(raw)]; - if (shared) yield* inCell(text(shared)); - } else if (cell.attrs.t === "inlineStr") yield* inCell(text(cell)); + if (shared) yield* inCell(xstringText(shared)); + } else if (cell.attrs.t === "inlineStr") yield* inCell(xstringText(cell)); + else if (cell.attrs.t === "b" && (raw.trim() === "0" || raw.trim() === "1")) + yield* inCell([raw.trim() === "1" ? "true" : "false"]); else { - if (value && hasCellText(value)) yield* inCell(text(value)); + if (value && hasCellText(value)) yield* inCell(xstringText(value)); else for (const formula of all(cell, "f")) yield* inCell(text(formula)); const formatId = formats[Number(cell.attrs.s ?? 0)]?.attrs.numFmtId; const format = formatId ? customFormats.get(formatId) : undefined; diff --git a/apps/server/src/provider/managedRelease.ts b/apps/server/src/provider/managedRelease.ts new file mode 100644 index 0000000000..ca7c55e43b --- /dev/null +++ b/apps/server/src/provider/managedRelease.ts @@ -0,0 +1,29 @@ +import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver"; + +// Older pins recorded non-semver versions such as `agy_acp_server_1.1.1`; any +// other release is an update from those. +const isNewer = (candidate: string, current: string) => + parseSemver(candidate) && parseSemver(current) + ? compareSemverVersions(candidate, current) > 0 + : candidate !== current; + +/** + * Picks the release a managed installation's `start` downloads. A fresh install + * gets T3 Code's pinned release; an existing one moves to the newest known + * release above it. Null means nothing newer is known, so `start` re-checks the + * installed runtime instead of downgrading it. + */ +export function selectManagedRelease( + installedVersion: string | null, + pinned: Release | null, + upstream: Release | null, +): Release | null { + if (installedVersion === null) return pinned; + let selected: Release | null = null; + for (const candidate of [pinned, upstream]) { + if (candidate && isNewer(candidate.version, selected?.version ?? installedVersion)) { + selected = candidate; + } + } + return selected; +} diff --git a/apps/server/src/provider/model-manifest.json b/apps/server/src/provider/model-manifest.json index 7a83c12a6b..8bd6382e1d 100644 --- a/apps/server/src/provider/model-manifest.json +++ b/apps/server/src/provider/model-manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "updatedAt": "2026-11-10T17:25:47Z", + "updatedAt": "2026-11-14T15:58:47Z", "compatibility": [ { "driver": "codex", @@ -80,8 +80,9 @@ { "driver": "antigravity", "t3CodeRange": ">=0.0.42", - "recommendedRange": "=1.4.5 || =1.4.1", + "recommendedRange": ">=1.5.1 <2", "ranges": [ + { "range": ">=1.5.1 <2", "status": "supported" }, { "range": "=1.4.5", "status": "supported" }, { "range": "=1.4.1", "status": "supported" }, { "range": "=1.3.0", "status": "supported" }, @@ -99,8 +100,8 @@ "t3CodeRange": ">=0.0.46", "recommendedRange": ">=1.0.0", "ranges": [ - { "range": ">=0.80.5", "status": "supported" }, - { "range": "<0.80.5", "status": "unsupported" } + { "range": ">=0.84.3", "status": "supported" }, + { "range": "<0.84.3", "status": "unsupported" } ] }, { @@ -775,7 +776,7 @@ "aliases": ["fable", "fable-5.2", "claude-fable-5.2"], "status": "current", "profile": "fable-5", - "adapter": { "claudeCode": { "minVersion": "2.1.290" } } + "adapter": { "claudeCode": { "minVersion": "2.1.321" } } }, { "slug": "claude-fable-5-1", diff --git a/apps/server/src/provider/providerCompatibility.test.ts b/apps/server/src/provider/providerCompatibility.test.ts index 928acfb480..2f36728878 100644 --- a/apps/server/src/provider/providerCompatibility.test.ts +++ b/apps/server/src/provider/providerCompatibility.test.ts @@ -22,7 +22,6 @@ import { ProviderCompatibilityPolicy, resolveProviderCompatibility, } from "./providerCompatibility.ts"; -import { resolveAntigravityReleaseAsset } from "./antigravityRelease.ts"; import bundledManifest from "./model-manifest.json" with { type: "json" }; const decodeCompatibilityPolicies = Schema.decodeUnknownSync( @@ -133,19 +132,15 @@ describe("provider compatibility", () => { } }); - it.each([ - ["darwin", "arm64"], - ["win32", "x64"], - ] as const)( - "supports the managed Antigravity runtime for %s-%s in the bundled manifest", - (platform, arch) => { + it.each(["1.4.5", "1.5.7"])( + "supports the legacy and native Antigravity runtime %s in the bundled manifest", + (version) => { const policies = decodeCompatibilityPolicies(bundledManifest.compatibility); - const release = resolveAntigravityReleaseAsset(platform, arch); assert.strictEqual( resolveProviderCompatibility( policies, ProviderDriverKind.make("antigravity"), - `agy_acp_server_${release?.version}`, + `agy_acp_server_${version}`, )?.status, "supported", ); @@ -329,5 +324,5 @@ it.effect("a remote policy refresh preserves a newer health result on the regist ), ), ); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/provider/providerInstallation.test.ts b/apps/server/src/provider/providerInstallation.test.ts index 8a3d3316ac..d4c7467c62 100644 --- a/apps/server/src/provider/providerInstallation.test.ts +++ b/apps/server/src/provider/providerInstallation.test.ts @@ -95,6 +95,7 @@ const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* }), state: Effect.succeed({ ...state, driver: ProviderDriverKind.make("codex") }), changes: Stream.succeed({ ...state, driver: ProviderDriverKind.make("codex") }), + checkForUpdate: Effect.void, remove: (paths) => Effect.sync(() => { protectedPaths = paths ?? []; @@ -103,6 +104,7 @@ const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* }), Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused-managed-runtime", + checkForUpdate: Effect.void, start: Effect.sync(() => { calls.push("start"); return { ...state, operationId: "install-1", phase: "downloading" as const }; diff --git a/apps/server/src/provider/providerInstallation.ts b/apps/server/src/provider/providerInstallation.ts index d1be2c6433..e47f4e2165 100644 --- a/apps/server/src/provider/providerInstallation.ts +++ b/apps/server/src/provider/providerInstallation.ts @@ -186,9 +186,25 @@ const make = Effect.fn("makeProviderInstallation")(function* () { .pipe(Effect.mapError(failure(input.instanceId))); }); + // Watching an installation is when its owner can act on an update, so the lookup runs then, + // in the background, only for a managed install and unless update checks are off. const subscribe = (input: ProviderSetupInput) => Stream.unwrap( requireInstance(input.instanceId, "observe-install").pipe( + Effect.tap(() => + requireInstance(input.instanceId, "observe-install", true).pipe( + Effect.flatMap(({ installation }) => + settings.getSettings.pipe( + Effect.flatMap((current) => + current.enableProviderUpdateChecks + ? Effect.forkDetach(installation.checkForUpdate) + : Effect.void, + ), + ), + ), + Effect.ignore, + ), + ), Effect.map(({ installation }) => installation.changes), ), ); diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 719b7c01d2..f5dc623f0f 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -1,3 +1,4 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, it, assert } from "@effect/vitest"; import { ProviderDriverKind, @@ -22,6 +23,14 @@ import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; + +import * as ServerSettings from "../serverSettings.ts"; +import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; +import * as TextGeneration from "../textGeneration/TextGeneration.ts"; +import * as TextGenerators from "../textGeneration/TextGenerators.ts"; +import * as ProviderInstallationGate from "./ProviderInstallationGate.ts"; +import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import * as ProviderRegistry from "./ProviderRegistry.ts"; import * as ModelManifest from "./ModelManifest.ts"; import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts"; @@ -198,6 +207,7 @@ function makeRegistry( refresh: () => Ref.get(providersRef), refreshInstance: () => Ref.get(providersRef), reloadSecretsAndRefresh: () => Ref.get(providersRef), + applySecretAndRefresh: () => Ref.get(providersRef), refreshAfterUpdate: () => { const version = options?.installedVersionAfterUpdate; if (version === undefined) { @@ -253,6 +263,8 @@ const makeTestRunner = ( refreshInBackground: Effect.void, }), latestVersions, + // Layers memoize by reference, so a test that provides the gate shares it. + ProviderInstallationGate.layer, ), ), ), @@ -295,6 +307,7 @@ describe("providerMaintenanceRunner", () => { [ ["queued", "Waiting for another provider update to finish."], ["running", "Checking for the latest version"], + ["running", "Waiting for running provider work to finish."], ["running", "Running native-agent update"], ["running", "Verifying the installed version"], ["succeeded", "Provider updated."], @@ -559,6 +572,43 @@ describe("providerMaintenanceRunner", () => { ); }); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "runs the updater with no stdin, so a command that reads it cannot wait forever", + () => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseProvider); + const updater = yield* makeTestRunner({ + ...registry, + getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => + Effect.succeed({ + ...lifecycleFor(provider), + update: { + command: "codex update", + executable: "/bin/sh", + // An open pipe here would block a CLI that reads stdin until the update times out. + args: ["-c", "[ -c /dev/stdin ] || { echo 'stdin is an open pipe' >&2; exit 1; }"], + lockKey: "codex-native", + }, + }), + }); + + const result = yield* updater.updateProvider(CODEX_DRIVER); + // The registry reports no new version, so a command that exits 0 ends as "unchanged". + assert.strictEqual( + result.providers[0]?.updateState?.message, + "Update command completed, but 456code still detects an outdated provider version.", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + ), + ), + ), + ); + it.effect("re-resolves ownership before running and executes the fresh command", () => { const calls: Array<{ command: string; args: ReadonlyArray }> = []; const fresh: Array = []; @@ -712,6 +762,65 @@ describe("providerMaintenanceRunner", () => { ), ); + it.effect("reports the updater's error rather than a trailing hint after it", () => + Effect.forEach( + [ + { + stdout: "Current version: 2.1.310\nChecking for updates to latest version...\n", + stderr: [ + "Error: Failed to install native update", + "TelemetrySafeError: Failed to fetch version from https://downloads.claude.ai/claude-code-releases/latest after 3 attempt(s): Request failed with status code 403", + 'Try running "claude doctor" for diagnostics', + "", + ].join("\n"), + reason: "Request failed with status code 403", + hint: "claude doctor", + }, + { + stdout: "", + stderr: [ + "Failed to check for updates", + "Unable to fetch latest version from npm registry", + "", + "Possible causes:", + " • Network connectivity issues", + " • npm registry is unreachable", + " • Corporate proxy/firewall blocking npm", + "", + "Try:", + " • Check your internet connection", + " • Run with --debug flag for more details", + " • Manually check: npm view @anthropic-ai/claude-code version", + " • Check if you need to login: npm whoami", + "", + ].join("\n"), + reason: "Failed to check for updates", + hint: "npm whoami", + }, + ], + ({ stdout, stderr, reason, hint }) => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseNativeCliProvider); + const updater = yield* makeTestRunner(registry); + + const result = yield* updater.updateProvider(NATIVE_CLI_DRIVER); + const message = result.providers[0]?.updateState?.message ?? ""; + + assert.include(message, reason); + assert.notInclude(message, hint); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("0.0.0"), + layerMockSpawner(() => ({ stdout, stderr, code: 1 })), + ), + ), + ), + { discard: true }, + ), + ); + it.effect("keeps the exit code message when a failed command prints nothing", () => Effect.gen(function* () { const { registry } = yield* makeRegistry(); @@ -795,6 +904,66 @@ describe("providerMaintenanceRunner", () => { ); }); + it.effect("an interrupted update ends failed instead of running forever", () => { + const started = Deferred.makeUnsafe(); + return Effect.gen(function* () { + const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); + const updater = yield* makeTestRunner(registry); + const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(started); + yield* Fiber.interrupt(update); + const last = (yield* Ref.get(updateStatesRef)).at(-1); + assert.deepStrictEqual( + [last?.status, last?.message], + ["failed", "Update stopped before it finished."], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ + exitCode: Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), + })), + ), + ), + ); + }); + + it.effect("a request dropped while the final state is written still records it", () => { + const writing = Deferred.makeUnsafe(); + const release = Deferred.makeUnsafe(); + return Effect.gen(function* () { + const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: (input) => + input.state?.status === "succeeded" + ? Deferred.succeed(writing, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.andThen(registry.setProviderMaintenanceActionState(input)), + ) + : registry.setProviderMaintenanceActionState(input), + }); + + const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(writing); + update.interruptUnsafe(); + yield* Deferred.succeed(release, undefined); + yield* Fiber.await(update); + + assert.strictEqual((yield* Ref.get(updateStatesRef)).at(-1)?.status, "succeeded"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ stdout: "updated" })), + ), + ), + ); + }); + it.effect("prevents concurrent updates for the same provider", () => { const startedLatch: { resolve: () => void } = { resolve: () => {} }; const releaseLatch: { resolve: () => void } = { resolve: () => {} }; @@ -842,6 +1011,144 @@ describe("providerMaintenanceRunner", () => { ); }); + it.effect("holds text generation for an instance until its update finishes", () => { + const updateStarted = Deferred.makeUnsafe(); + const log: Array = []; + return Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseProvider, { + installedVersionAfterUpdate: "1.0.0", + }); + const updater = yield* makeTestRunner(registry); + const instance: ProviderInstance = { + instanceId: CODEX_INSTANCE_ID, + driverKind: CODEX_DRIVER, + continuationIdentity: { driverKind: CODEX_DRIVER, continuationKey: CODEX_INSTANCE_ID }, + displayName: undefined, + enabled: true, + snapshot: { getSnapshot: Effect.succeed(baseProvider) } as ProviderInstance["snapshot"], + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: TextGeneration.TextGeneration.of({ + generateCommitMessage: () => Effect.die("unused"), + generatePrContent: () => Effect.die("unused"), + generateBranchName: () => Effect.die("unused"), + generateReviewGuide: () => Effect.die("unused"), + generateTranscriptionPostProcessing: () => Effect.die("unused"), + generateThreadTitle: () => + Effect.sync(() => { + log.push("text generation spawned provider"); + return { title: "Generated title" }; + }), + }), + }; + const textGeneration = yield* TextGeneration.make.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({ + listInstances: Effect.succeed([instance]), + getInstance: (id) => Effect.succeed(id === CODEX_INSTANCE_ID ? instance : undefined), + }), + ServerSettings.layerTest(), + Layer.mock(TextGenerators.TextGenerators)({ runner: () => Effect.undefined }), + Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ + resolveLink: () => Effect.die("unused"), + }), + ), + ), + ); + + const update = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(updateStarted); + const generation = yield* textGeneration + .generateThreadTitle({ + cwd: "/tmp", + message: "hello", + linkedContext: "", + modelSelection: { instanceId: CODEX_INSTANCE_ID, model: "gpt-5" }, + }) + .pipe(Effect.forkScoped); + yield* TestClock.adjust("1 minute"); + const result = yield* Fiber.join(update); + yield* Fiber.join(generation); + + assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); + assert.deepStrictEqual(log, ["update command exited", "text generation spawned provider"]); + }).pipe( + Effect.provide( + Layer.mergeAll( + ProviderInstallationGate.layer, + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ + exitCode: Deferred.succeed(updateStarted, undefined).pipe( + Effect.andThen(Effect.sleep("1 minute")), + Effect.andThen(Effect.sync(() => log.push("update command exited"))), + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + })), + ), + ), + ); + }); + + it.effect("holds every instance that shares the updated installation", () => { + const CODEX_WORK_INSTANCE_ID = ProviderInstanceId.make("codex_work"); + const updateStarted = Deferred.makeUnsafe(); + const log: Array = []; + return Effect.gen(function* () { + const { registry } = yield* makeRegistry( + [ + baseProvider, + { ...baseProvider, instanceId: CODEX_WORK_INSTANCE_ID }, + baseOpenCodeProvider, + ], + { installedVersionAfterUpdate: "1.0.0" }, + ); + // OpenCode installs into the same npm prefix, so it shares the lock key but not the package. + const updater = yield* makeTestRunner(registry); + const gate = yield* ProviderInstallationGate.ProviderInstallationGate; + + const update = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(updateStarted); + const shared = yield* gate + .execute( + CODEX_WORK_INSTANCE_ID, + Effect.sync(() => log.push("shared installation ran")), + ) + .pipe(Effect.forkScoped); + const other = yield* gate + .execute( + OPENCODE_INSTANCE_ID, + Effect.sync(() => log.push("other driver ran")), + ) + .pipe(Effect.forkScoped); + yield* TestClock.adjust("1 minute"); + yield* Fiber.join(update); + yield* Fiber.join(shared); + yield* Fiber.join(other); + + assert.deepStrictEqual(log, [ + "other driver ran", + "update command exited", + "shared installation ran", + ]); + }).pipe( + Effect.provide( + Layer.mergeAll( + ProviderInstallationGate.layer, + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ + exitCode: Deferred.succeed(updateStarted, undefined).pipe( + Effect.andThen(Effect.sleep("1 minute")), + Effect.andThen(Effect.sync(() => log.push("update command exited"))), + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + })), + ), + ), + ); + }); + it.effect( "releases the running-provider marker when interrupted after queuing but before the lock run starts", () => @@ -977,6 +1284,12 @@ describe("providerMaintenanceRunner", () => { }); it.effect.each([ + { + mode: "default-precurrent", + version: "1.14.19", + installation: { installedVersion: "1.14.20" }, + status: "succeeded", + }, { mode: "default", version: "1.14.19", @@ -1032,7 +1345,11 @@ it.effect.each([ ...registry, refreshInstance: () => Ref.updateAndGet(providersRef, (providers) => - providers.map((provider) => ({ ...provider, checkedAt: "2026-04-10T00:00:01.000Z" })), + providers.map((provider) => ({ + ...provider, + ...(mode === "default-precurrent" ? installation : {}), + checkedAt: "2026-04-10T00:00:01.000Z", + })), ), getProviderMaintenanceCapabilitiesForInstance: () => Effect.succeed(pinnedCapabilities), refreshAfterUpdate: () => @@ -1058,17 +1375,27 @@ it.effect.each([ const result = yield* updater.updateProvider({ provider: OPENCODE_DRIVER, - ...(mode === "default" ? {} : { targetVersion: "1.14.20" }), + ...(mode.startsWith("default") ? {} : { targetVersion: "1.14.20" }), }); - assert.deepStrictEqual(calls, [ - `npm install -g opencode-ai@${mode === "default" ? "latest" : "1.14.20"}`, - ]); + assert.deepStrictEqual( + calls, + mode === "default-precurrent" + ? [] + : [`npm install -g opencode-ai@${mode.startsWith("default") ? "latest" : "1.14.20"}`], + ); const provider = result.providers[0]; assert.ok(provider); assert.strictEqual(provider.updateState?.status, status); + if (mode === "default" || mode === "default-precurrent" || mode === "targeted") { + assert.strictEqual( + provider.updateState?.message, + "OpenCode CLI updated. Restart the configured local OpenCode server to use the new version.", + ); + } assert.strictEqual(provider.version, version); assert.strictEqual("installedVersion" in provider, mode !== "legacy"); + if (mode === "default-precurrent") return; assert.strictEqual( provider.versionAdvisory?.status, mode === "unknown" ? "unknown" : "current", diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 7118f7eb16..79c75fbfb6 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -25,6 +25,7 @@ import * as NodeUtil from "node:util"; import * as ModelManifest from "./ModelManifest.ts"; import { resolveProviderCompatibility } from "./providerCompatibility.ts"; +import * as ProviderInstallationGate from "./ProviderInstallationGate.ts"; import * as ProviderRegistry from "./ProviderRegistry.ts"; import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts"; import { @@ -94,6 +95,18 @@ interface VerifiedProviderRefresh { const nowIso = Effect.map(DateTime.now, DateTime.formatIso); +const OPENCODE_SERVER_RESTART_MESSAGE = + "OpenCode CLI updated. Restart the configured local OpenCode server to use the new version."; + +const needsOpenCodeServerRestart = (providers: ReadonlyArray) => + providers.some( + (provider) => + provider.driver === ProviderDriverKind.make("opencode") && + provider.installedVersion != null && + provider.version != null && + provider.installedVersion !== provider.version, + ); + const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")( function* (input: { readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; @@ -111,6 +124,8 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR .spawn( ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell, + // Nothing answers an update command, so one that reads stdin must see EOF, not wait. + stdin: "ignore", ...env, }), ) @@ -250,18 +265,20 @@ function commandOutput(result: ProviderMaintenanceCommandResult): string | null return truncateText(output, UPDATE_OUTPUT_MAX_BYTES); } -// Updaters print their reason last, usually on stderr. -function lastOutputLine(result: ProviderMaintenanceCommandResult): string | null { - for (const output of [result.stderr, result.stdout]) { - const line = output +// Updaters report on stderr, but may follow their error with hints (`claude update` +// ends with "Try running claude doctor"), so prefer the last line naming an error. +function failureReason(result: ProviderMaintenanceCommandResult): string | null { + const streams = [result.stderr, result.stdout].map((output) => + output .split(/\r\n|\r|\n/) .map(toProgressLine) - .findLast(Boolean); - if (line) { - return line; - } - } - return null; + .filter((line) => line !== null), + ); + return ( + streams.map((lines) => lines.findLast((line) => /error|fail/i.test(line))).find(Boolean) ?? + streams.map((lines) => lines.at(-1)).find(Boolean) ?? + null + ); } function failureMessage(result: ProviderMaintenanceCommandResult): string { @@ -272,7 +289,7 @@ function failureMessage(result: ProviderMaintenanceCommandResult): string { result.exitCode !== null && result.exitCode !== 0 ? `Update command exited with code ${result.exitCode}` : "Update command failed"; - const reason = lastOutputLine(result); + const reason = failureReason(result); return reason ? `${summary}: ${reason}` : `${summary}.`; } @@ -307,6 +324,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate; const runMaintenanceCommand = ( update: ProviderMaintenanceCommandAction, onProgress: (line: string) => Effect.Effect, @@ -318,6 +336,28 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { onProgress, ...(update.env ? { env: update.env } : {}), }); + // Instances with other homes or accounts can still run the binary this update replaces. The + // lock key names the package manager location, so other drivers there keep their own package. + const instancesSharingInstallation = Effect.fn( + "ProviderMaintenanceRunner.instancesSharingInstallation", + )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind, lockKey: string) { + const providers = yield* providerRegistry.getProviders; + const shared = yield* Effect.forEach( + providers.filter( + (candidate) => candidate.instanceId !== instanceId && candidate.driver === provider, + ), + (candidate) => + providerRegistry + .getProviderMaintenanceCapabilitiesForInstance(candidate.instanceId, candidate.driver) + .pipe( + Effect.map((capabilities) => + capabilities.update?.lockKey === lockKey ? [candidate.instanceId] : [], + ), + ), + { concurrency: "unbounded" }, + ); + return [instanceId, ...shared.flat()]; + }); const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({ makeAlreadyRunningError: () => new ServerProviderUpdateError({ @@ -403,11 +443,14 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { }); } + const startedAtRef = yield* Ref.make(null); + const settled = yield* Ref.make(false); const setUpdateState = (state: ServerProviderUpdateState | null) => providerRegistry.setProviderMaintenanceActionState({ instanceId, action: "update", state, + targetVersion, }); const setQueuedState = setUpdateState( makeUpdateState({ @@ -420,9 +463,13 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")( function* () { + // Uninterruptible, so a dropped request cannot leave settled set without the state. const finish = (state: ServerProviderUpdateState) => - setUpdateState(state).pipe(Effect.map((providers) => ({ providers }))); - const startedAtRef = yield* Ref.make(null); + Ref.set(settled, true).pipe( + Effect.andThen(setUpdateState(state)), + Effect.map((providers) => ({ providers })), + Effect.uninterruptible, + ); const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")( function* () { @@ -527,14 +574,26 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { status: "succeeded", startedAt, finishedAt: yield* nowIso, - message: "Already up to date.", + message: needsOpenCodeServerRestart(precheck.verifiedProviders) + ? OPENCODE_SERVER_RESTART_MESSAGE + : "Already up to date.", }), ); } } - yield* setRunningMessage(`Running ${describeCommand(command)}`); - const result = yield* runMaintenanceCommand(command, setRunningMessage); + const sharingInstances = yield* instancesSharingInstallation( + instanceId, + provider, + update.lockKey, + ); + yield* setRunningMessage("Waiting for running provider work to finish."); + const result = yield* installationGate.update( + sharingInstances, + setRunningMessage(`Running ${describeCommand(command)}`).pipe( + Effect.andThen(runMaintenanceCommand(command, setRunningMessage)), + ), + ); const finishedAt = yield* nowIso; if (result.timedOut || result.exitCode !== 0) { yield* Effect.logWarning("Provider update command failed", { @@ -600,7 +659,9 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ? "Update command completed, but 456code could not verify the provider version." : stillOutdated ? "Update command completed, but 456code still detects an outdated provider version." - : "Provider updated.", + : needsOpenCodeServerRestart(verifiedProviders) + ? OPENCODE_SERVER_RESTART_MESSAGE + : "Provider updated.", output: commandOutput(result), }), ); @@ -635,6 +696,21 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { run: runProviderUpdate(), }) .pipe( + // A dropped request interrupts the update; a "running" state would spin until restart. + Effect.onInterrupt(() => + Effect.gen(function* () { + // A finished state stays, even if the request drops while it is being written. + if (yield* Ref.get(settled)) return; + yield* setUpdateState( + makeUpdateState({ + status: "failed", + startedAt: yield* Ref.get(startedAtRef), + finishedAt: yield* nowIso, + message: "Update stopped before it finished.", + }), + ); + }).pipe(Effect.ignore), + ), Effect.mapError((error) => isServerProviderUpdateError(error) ? new ServerProviderUpdateError({ diff --git a/apps/server/src/provider/resetCreditCoordinator.test.ts b/apps/server/src/provider/resetCreditCoordinator.test.ts index a7a8010a3f..b863569b06 100644 --- a/apps/server/src/provider/resetCreditCoordinator.test.ts +++ b/apps/server/src/provider/resetCreditCoordinator.test.ts @@ -3,6 +3,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Ref from "effect/Ref"; +import * as TestClock from "effect/testing/TestClock"; import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts"; @@ -100,4 +101,29 @@ describe("ResetCreditCoordinator", () => { assert.strictEqual(yield* Ref.get(peak), 2); }).pipe(Effect.provide(ResetCreditCoordinator.layerTest)), ); + + it.effect("re-probes after a reset until the limits are fresh, then gives up", () => + Effect.gen(function* () { + const stale = { usageLimits: { checkedAt: "t0", windows: [] } }; + const run = (freshFrom: number) => + Effect.gen(function* () { + const probes = yield* Ref.make(0); + const refresh = Ref.updateAndGet(probes, (n) => n + 1).pipe( + Effect.map((n) => + n >= freshFrom ? { usageLimits: { checkedAt: `t${n}`, windows: [] } } : stale, + ), + ); + const fiber = yield* ResetCreditCoordinator.refreshAfterRedemption({ + outcome: "reset", + getSnapshot: Effect.succeed(stale), + refresh, + }).pipe(Effect.forkChild); + yield* TestClock.adjust("1 minute"); + return { confirmed: yield* Fiber.join(fiber), probes: yield* Ref.get(probes) }; + }); + + assert.deepStrictEqual(yield* run(3), { confirmed: true, probes: 3 }); + assert.deepStrictEqual(yield* run(Infinity), { confirmed: false, probes: 4 }); + }), + ); }); diff --git a/apps/server/src/provider/resetCreditCoordinator.ts b/apps/server/src/provider/resetCreditCoordinator.ts index 153728bc8a..c311dad7c5 100644 --- a/apps/server/src/provider/resetCreditCoordinator.ts +++ b/apps/server/src/provider/resetCreditCoordinator.ts @@ -1,11 +1,12 @@ /** Instances sharing a login directory share credits; serialize redemptions on that directory. */ -import type { ProviderConsumeResetCreditOutcome } from "@t3tools/contracts"; +import type { ProviderConsumeResetCreditOutcome, ServerProvider } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import type * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; interface AccountRedemptionState { @@ -70,6 +71,36 @@ export const make = Effect.gen(function* () { return { redeem } satisfies ResetCreditCoordinator["Service"]; }); +type UsageSnapshot = Pick; + +/** + * Re-probe after a redemption; true once a `reset` shows fresh limits. A failed + * usage read republishes the pre-redemption windows, which are known stale after + * a reset, so retry briefly instead of leaving them until the periodic check. + */ +export const refreshAfterRedemption = Effect.fn("resetCreditCoordinator.refreshAfterRedemption")( + function* (input: { + readonly outcome: ProviderConsumeResetCreditOutcome; + readonly getSnapshot: Effect.Effect; + readonly refresh: Effect.Effect; + }) { + const before = (yield* input.getSnapshot).usageLimits?.checkedAt; + const confirmed = ({ usageLimits }: UsageSnapshot) => + input.outcome !== "reset" || + (usageLimits !== undefined && + usageLimits.checkedAt !== before && + usageLimits.unavailable?.reason !== "probeFailed"); + return yield* input.refresh.pipe( + Effect.map(confirmed), + Effect.repeat({ + until: (ok) => ok, + times: 3, + schedule: Schedule.exponential("1 second"), + }), + ); + }, +); + export const layer = Layer.effect(ResetCreditCoordinator, make); export const layerTest = Layer.effect( diff --git a/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs b/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs index 357bdb7fe5..b8cb949a5f 100644 --- a/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs +++ b/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs @@ -5,12 +5,35 @@ const sessionId = "grok-text-session"; let currentModelId = "grok-mock-default"; const models = ["grok-mock-default", "grok-mock-alt"]; const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`); +const permissionRequestId = 9001; +let pendingPromptId; +const completePrompt = (id) => { + write({ + jsonrpc: "2.0", + method: "session/update", + params: { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: process.env.T3_ACP_PROMPT_RESPONSE_TEXT ?? "" }, + }, + }, + }); + write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); +}; for await (const line of NodeReadline.createInterface({ input: process.stdin })) { const request = JSON.parse(line); if (process.env.T3_ACP_REQUEST_LOG_PATH) { NodeFS.appendFileSync(process.env.T3_ACP_REQUEST_LOG_PATH, `${line}\n`); } + if (request.method === undefined) { + if (request.id === permissionRequestId && pendingPromptId !== undefined) { + completePrompt(pendingPromptId); + pendingPromptId = undefined; + } + continue; + } if (request.id === undefined) continue; let result; switch (request.method) { @@ -43,19 +66,25 @@ for await (const line of NodeReadline.createInterface({ input: process.stdin })) result = {}; break; case "session/prompt": - write({ - jsonrpc: "2.0", - method: "session/update", - params: { - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: process.env.T3_ACP_PROMPT_RESPONSE_TEXT ?? "" }, + if (process.env.T3_ACP_REQUEST_PERMISSION) { + pendingPromptId = request.id; + write({ + jsonrpc: "2.0", + id: permissionRequestId, + method: "session/request_permission", + params: { + sessionId, + toolCall: { toolCallId: "tool-1", kind: "execute", title: "Run `git status`" }, + options: [ + { optionId: "allow-once", name: "Yes", kind: "allow_once" }, + { optionId: "reject-once", name: "No", kind: "reject_once" }, + ], }, - }, - }); - result = { stopReason: "end_turn" }; - break; + }); + continue; + } + completePrompt(request.id); + continue; default: write({ jsonrpc: "2.0", diff --git a/apps/server/src/provider/testUtils/providerRegistryMock.ts b/apps/server/src/provider/testUtils/providerRegistryMock.ts index 3ae8079414..ccf4979937 100644 --- a/apps/server/src/provider/testUtils/providerRegistryMock.ts +++ b/apps/server/src/provider/testUtils/providerRegistryMock.ts @@ -12,6 +12,7 @@ const makeProviderRegistryMock = ( refresh: () => Effect.succeed(providers), refreshInstance: () => Effect.succeed(providers), reloadSecretsAndRefresh: () => Effect.succeed(providers), + applySecretAndRefresh: () => Effect.succeed(providers), refreshAfterUpdate: () => Effect.succeed(providers), refreshWorkspaceSnapshot: () => Effect.succeed(providers), invalidateModelCaches: () => Effect.void, diff --git a/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs b/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs index 5c4c84f2aa..b996e420f8 100755 --- a/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs +++ b/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs @@ -68,6 +68,40 @@ lines.on("line", (line) => { ); return; } + if (message.request?.subtype === "get_settings" && process.env.T3_CLAUDE_SETTINGS_UNSUPPORTED) { + process.stdout.write( + JSON.stringify({ + type: "control_response", + response: { + subtype: "error", + request_id: message.request_id, + error: "Unsupported control request subtype: get_settings", + }, + }) + "\n", + ); + return; + } + if (message.request?.subtype === "get_settings") { + const sources = JSON.parse(process.env.T3_CLAUDE_SETTINGS_SOURCES ?? "[]"); + // Like Claude Code, `effective` is the last-writer merge, which hides per-source caps. + const effective = { modelSettings: {} }; + for (const { settings } of sources) { + Object.assign(effective, settings, { + modelSettings: Object.assign(effective.modelSettings, settings.modelSettings), + }); + } + process.stdout.write( + JSON.stringify({ + type: "control_response", + response: { + subtype: "success", + request_id: message.request_id, + response: { effective, sources }, + }, + }) + "\n", + ); + return; + } if (message.request?.subtype !== "initialize") return; process.stdout.write( JSON.stringify({ diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index f9b41babae..4087601b58 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -7,6 +7,7 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as TestClock from "effect/testing/TestClock"; @@ -16,6 +17,7 @@ import * as ServerConfig from "../config.ts"; import * as DocumentText from "./DocumentText.ts"; import { extractDocumentText } from "./documentTextWorker.ts"; import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts"; +import * as DeviceService from "../device/DeviceService.ts"; import * as TerminalManager from "../terminal/Manager.ts"; import * as PreviewManager from "../preview/Manager.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; @@ -87,6 +89,114 @@ describe("question answer paths", () => { }).pipe(Effect.provide(layer)), ); + it.effect.each(["interrupted", "failed"])( + "extracts two documents at once and frees a slot when one is %s", + (outcome) => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const [first, second, third] = ["first", "second", "third"].map((name) => + NodePath.join(config.attachmentsDir, `${name}.rtf`), + ); + NodeFS.writeFileSync(first!, String.raw`{\rtf1 First}`); + NodeFS.writeFileSync(second!, "invalid document"); + NodeFS.writeFileSync(third!, String.raw`{\rtf1 Third}`); + const started = yield* Queue.unbounded(); + const releases = new Map>(); + for (const path of [first!, second!, third!]) + releases.set(path, yield* Deferred.make()); + yield* Effect.gen(function* () { + const documents = yield* DocumentText.DocumentText; + const leaving = yield* documents.ensure(first!).pipe(Effect.forkChild); + const staying = yield* documents.ensure(first!).pipe(Effect.forkChild); + const freed = yield* documents.ensure(second!).pipe(Effect.forkChild); + expect(new Set([yield* Queue.take(started), yield* Queue.take(started)])).toEqual( + new Set([first, second]), + ); + const waiting = yield* documents.ensure(third!).pipe(Effect.forkChild); + yield* Fiber.interrupt(leaving); + if (outcome === "interrupted") yield* Fiber.interrupt(freed); + else { + yield* Deferred.succeed(releases.get(second!)!, undefined); + expect(yield* Fiber.join(freed)).toBeUndefined(); + } + expect(yield* Queue.take(started)).toBe(third); + yield* Deferred.succeed(releases.get(first!)!, undefined); + yield* Deferred.succeed(releases.get(third!)!, undefined); + expect(yield* Fiber.join(staying)).toBe(first + ".txt"); + expect(yield* Fiber.join(waiting)).toBe(third + ".txt"); + expect(yield* Queue.size(started)).toBe(0); + expect(NodeFS.existsSync(second + ".txt")).toBe(false); + expect( + NodeFS.readdirSync(config.attachmentsDir).filter((file) => file.endsWith(".part")), + ).toEqual([]); + }).pipe( + Effect.provide(Layer.fresh(DocumentText.layer)), + Effect.provideService(FileSystem.FileSystem, { + ...fs, + stat: (file) => + Effect.gen(function* () { + yield* Queue.offer(started, file); + yield* Deferred.await(releases.get(file)!); + return yield* fs.stat(file); + }), + }), + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect("retries a document while its cancelled extraction is still publishing", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = NodePath.join(config.attachmentsDir, "retried.rtf"); + NodeFS.writeFileSync(path, String.raw`{\rtf1 Retried}`); + const writing = yield* Deferred.make(); + const writeReleased = yield* Deferred.make(); + const renaming = yield* Deferred.make(); + const renameReleased = yield* Deferred.make(); + let writes = 0; + let renames = 0; + yield* Effect.gen(function* () { + const documents = yield* DocumentText.DocumentText; + const cancelled = yield* documents.ensure(path).pipe(Effect.forkChild); + yield* Deferred.await(writing); + const interrupting = yield* Fiber.interrupt(cancelled).pipe(Effect.forkChild); + const retry = yield* documents.ensure(path).pipe(Effect.forkChild); + yield* Deferred.await(renaming); + yield* Deferred.succeed(writeReleased, undefined); + yield* Fiber.join(interrupting); + yield* Deferred.succeed(renameReleased, undefined); + expect(yield* Fiber.join(retry)).toBe(path + ".txt"); + expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Retried"); + expect( + NodeFS.readdirSync(config.attachmentsDir).filter((file) => file.endsWith(".part")), + ).toEqual([]); + }).pipe( + Effect.provide(Layer.fresh(DocumentText.layer)), + Effect.provideService(FileSystem.FileSystem, { + ...fs, + writeFileString: (file, data) => + Effect.gen(function* () { + if (++writes === 1) { + yield* Deferred.succeed(writing, undefined); + yield* Deferred.await(writeReleased); + } + return yield* fs.writeFileString(file, data); + }), + rename: (from, to) => + Effect.gen(function* () { + if (++renames === 1) { + yield* Deferred.succeed(renaming, undefined); + yield* Deferred.await(renameReleased); + } + return yield* fs.rename(from, to); + }), + }), + ); + }).pipe(Effect.provide(layer)), + ); + it.effect.each(["spawn", "read"])("retries after a transient %s failure expires", (failure) => Effect.acquireUseRelease( Effect.promise(async () => { @@ -175,6 +285,11 @@ describe("question answer paths", () => { String.raw`{\rtf1\ansi A\enspace B\emspace C\qmspace D\~E\_F\-G}`, "A\u2002B\u2003C\u2005D\u00a0E\u2011FG", ], + [ + "joiner and direction marks", + String.raw`{\rtf1\ansi A\zwj B\zwnj C\ltrmark D\rtlmark E}`, + "A\u200dB\u200cC\u200eD\u200fE", + ], [ "text symbol fallback", String.raw`{\rtf1\ansi\uc10\u945\endash\emdash\enspace\emspace\qmspace\lquote\rquote\ldblquote\rdblquote\bullet Z}`, @@ -328,6 +443,7 @@ describe("question answer paths", () => { Layer.mergeAll( Layer.mock(TerminalManager.TerminalManager)({}), Layer.mock(PreviewManager.PreviewManager)({}), + Layer.mock(DeviceService.DeviceService)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -579,28 +695,32 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'Report & totalsNorth1234BeforeInnerAfterNeighbor', + 'Report & totalsNorth1234BeforeInnerAfterNeighbor', }, - expected: ["## Report & totals", "North\t12 34", "Before Inner After\tNeighbor"], + expected: [ + "## Report & totals", + "North\t12 34", + "Before Inner After\tNeighbor\t\u2011\n\u2011", + ], }, { ext: "docx", bounded: true, parts: { "word/document.xml": - 'FirstSecondThird', + 'FirstSecondThirdparty‑End', }, - expected: ["First\nSecond\nThird"], + expected: ["First\nSecond\nThird\u2011party\u2011End"], }, { ext: "docx", bounded: true, parts: { "word/document.xml": - 'Intro PAGEREF _Toc1 \\h 3Fee $500$700Moveddue', + 'Intro PAGEREF _Toc1 \\h 3Fee $500$700Moveddue', }, expected: ["Intro 3\nFee $700\tdue"], - absent: ["PAGEREF", "$500", "Moved"], + absent: ["PAGEREF", "$500", "Moved", "\u2011"], }, { ext: "odt", @@ -637,6 +757,18 @@ describe("question answer paths", () => { ], absent: ["SUM(0,0)", "[Extracted text truncated"], }, + { + ext: "xlsx", + bounded: true, + parts: { + "xl/workbook.xml": '', + "xl/_rels/workbook.xml.rels": + '', + "xl/worksheets/a.xml": + '1012', + }, + expected: ["true\tfalse\t1\t2"], + }, { ext: "xlsx", parts: { @@ -677,6 +809,22 @@ describe("question answer paths", () => { expected: ["## Sheet: Phonetics", "東京\t東京"], absent: ["とうきょう"], }, + { + ext: "xlsx", + bounded: true, + parts: { + "xl/workbook.xml": '', + "xl/_rels/workbook.xml.rels": + '', + "xl/sharedStrings.xml": + "first_x000D_\nsecond_x005F_x0041__x005F_x005F_x0041_Bold_x000D__x005F_x000D_&_xnothex_ cap_X0041_ _x000d_ tail", + "xl/worksheets/a.xml": + '01234_x005F_x005F_first_x000D_secondA1Total_x000D_due', + }, + expected: [ + "## Sheet: Escapes\nfirst second\t_x0041_\t_x005F_x0041_\tBold _x000D_\t&_xnothex_ cap_X0041_ tail\n_x005F_\tfirst second\tTotal due", + ], + }, { ext: "xlsx", bounded: true, @@ -780,9 +928,11 @@ describe("question answer paths", () => { ext: "odt", parts: { "content.xml": - 'Orchard19violetcrates', + '\n Orchard\n19violetcrates \n\t shipped todayDockGate\u00a0B SecondAconsole.log(1);\n B', }, - expected: ["## Orchard", "19 violet crates"], + expected: [ + "## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B", + ], }, { ext: "ods", @@ -829,9 +979,9 @@ describe("question answer paths", () => { ext: "odp", parts: { "content.xml": - "FirstSecond", + "\n First\n\t slide Second", }, - expected: ["## Slide 1", "First", "## Slide 2", "Second"], + expected: ["## Slide 1\nFirst slide\n\n## Slide 2\nSecond"], }, { ext: "ods", @@ -926,13 +1076,13 @@ describe("question answer paths", () => { "OEBPS/book.opf": '', "OEBPS/a.xhtml": - '

Last chapter

Price 10 8

', + '

Last chapter

Price 10 8 old

', "OEBPS/b.xhtml": - "

First chapter

Larkspur

Direct div
Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    ", + 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    ', }, expected: [ "## Chapter 1", - "# First chapter", + "\n# First chapter", "Larkspur", "Direct div", "Direct section", @@ -943,8 +1093,9 @@ describe("question answer paths", () => { "Before Inner After\tNeighbor", "## Chapter 2", "Last chapter", - "Price 10 8", + "Price 10 8 old", ], + absent: ["My Novel", "Hidden Author"], }, ]; for (const [caseIndex, item] of cases.entries()) { diff --git a/apps/server/src/pullRequest/PullRequestReadCache.test.ts b/apps/server/src/pullRequest/PullRequestReadCache.test.ts index 071f1d4978..99b3cdba22 100644 --- a/apps/server/src/pullRequest/PullRequestReadCache.test.ts +++ b/apps/server/src/pullRequest/PullRequestReadCache.test.ts @@ -1,5 +1,4 @@ import * as NodeV8 from "node:v8"; -import * as NodeVM from "node:vm"; import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -16,9 +15,6 @@ import * as KeyValueStore from "effect/persistence/KeyValueStore"; import * as TestClock from "effect/testing/TestClock"; import * as PullRequestReadCache from "./PullRequestReadCache.ts"; -NodeV8.setFlagsFromString("--expose-gc"); -const collectGarbage = NodeVM.runInNewContext("gc") as () => void; - const cacheLayer = (directory: string) => PullRequestReadCache.make.pipe(Effect.provide(KeyValueStore.layerFileSystem(directory))); @@ -203,13 +199,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PR filesystem ca it.effect("does not keep a caller's data alive after its reads and invalidations", () => Effect.gen(function* () { const cache = yield* PullRequestReadCache.make; - const sweeps: Array> = []; + class SweepData extends Map {} // Like a sync sweep: an Effect.fn made per run that closes over that run's data. const sweep = Effect.fn("sweep")(function* (index: number) { - const groups = new Map( - Array.from({ length: 1_000 }, (_, id) => [`group-${id}`, id]), - ); - sweeps.push(new WeakRef(groups)); + const groups = new SweepData(Array.from({ length: 1_000 }, (_, id) => [`group-${id}`, id])); const read = Effect.fn("read")(function* (pr: string) { const size = groups.size; yield* cache.invalidate(pr); @@ -219,10 +212,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PR filesystem ca yield* Effect.forEach(["pr-1", "pr-2"], read, { discard: true }); }); for (let index = 0; index < 5; index++) yield* sweep(index); - // WeakRef targets stay alive until the current job ends, so yield before collecting. - yield* Effect.yieldNow; - collectGarbage(); - assert.strictEqual(sweeps.filter((sweepData) => sweepData.deref() !== undefined).length, 0); + // Counts after a full GC. A WeakRef would keep its target alive until the job ends. + assert.strictEqual(NodeV8.queryObjects(SweepData, { format: "count" }), 0); }).pipe(Effect.provide(KeyValueStore.layerMemory)), ); diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts index 3ee929f923..200ea36b7d 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts @@ -390,208 +390,198 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"], }, ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) => - Effect.scoped( - Effect.gen(function* () { - const run = yield* startSingleBranchRun({ - repositoryName: "refused-head", - reportedHead, - refuseCommitFetch: false, - prepare: (repositories, workspace) => - git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe( - Effect.andThen( - shadow === "none" - ? Effect.void - : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]), - ), - Effect.asVoid, + Effect.gen(function* () { + const run = yield* startSingleBranchRun({ + repositoryName: "refused-head", + reportedHead, + refuseCommitFetch: false, + prepare: (repositories, workspace) => + git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe( + Effect.andThen( + shadow === "none" + ? Effect.void + : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]), ), - }); - const result = yield* run.settled; - assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written"); - assert.strictEqual(result.run?._tag, "Failed"); - const detail = result.run?._tag === "Failed" ? result.run.detail : ""; - for (const part of expected) assert.include(detail, part); - // Only the host's own head ref is tried. - assert.notInclude(detail, "refs/merge-requests/"); - assert.deepStrictEqual(run.observed, []); - assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-"))); - const fs = yield* FileSystem.FileSystem; - assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`)); - }), - ), + Effect.asVoid, + ), + }); + const result = yield* run.settled; + assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written"); + assert.strictEqual(result.run?._tag, "Failed"); + const detail = result.run?._tag === "Failed" ? result.run.detail : ""; + for (const part of expected) assert.include(detail, part); + // Only the host's own head ref is tried. + assert.notInclude(detail, "refs/merge-requests/"); + assert.deepStrictEqual(run.observed, []); + assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-"))); + const fs = yield* FileSystem.FileSystem; + assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`)); + }), ); it.effect("measures only the PR change using the renamed verified remote's fetch URL", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fork = `${repositories.root}/fork`; - yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); - yield* git(fork, ["branch", "stack-base", "main~1"]); - // The cached identity still names origin, which now belongs to the stale fork. - yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); - yield* git(repositories.workspace, ["remote", "add", "origin", fork]); - yield* git(repositories.workspace, [ - "config", - `url.${repositories.remote}.insteadOf`, - "review-upstream:", - ]); - yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); - const changed = yield* Deferred.make(); - const driver = yield* GitVcsDriver.GitVcsDriver; - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: (input) => - git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( - Effect.provideService(GitVcsDriver.GitVcsDriver, driver), - Effect.orDie, - Effect.flatMap((names) => Deferred.succeed(changed, names)), - Effect.as({ stops: [] }), - ), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - yield* service.generate(reference); - assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); - yield* Deferred.await(stored); - const result = yield* service.get(reference); - assert.strictEqual(result.guide?.headSha, repositories.headSha); - assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fork = `${repositories.root}/fork`; + yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); + yield* git(fork, ["branch", "stack-base", "main~1"]); + // The cached identity still names origin, which now belongs to the stale fork. + yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); + yield* git(repositories.workspace, ["remote", "add", "origin", fork]); + yield* git(repositories.workspace, [ + "config", + `url.${repositories.remote}.insteadOf`, + "review-upstream:", + ]); + yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); + const changed = yield* Deferred.make(); + const driver = yield* GitVcsDriver.GitVcsDriver; + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + generate: (input) => + git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + Effect.orDie, + Effect.flatMap((names) => Deferred.succeed(changed, names)), + Effect.as({ stops: [] }), + ), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + yield* service.generate(reference); + assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); + yield* Deferred.await(stored); + const result = yield* service.get(reference); + assert.strictEqual(result.guide?.headSha, repositories.headSha); + assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); + }), ); it.effect("keeps excerpts despite the checkout's diff driver and a failing hook", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fs = yield* FileSystem.FileSystem; - yield* fs.writeFileString( - `${repositories.workspace}/.git/info/attributes`, - "feature.txt diff=blank\n", - ); - yield* git(repositories.workspace, ["config", "diff.blank.textconv", "true"]); - const hook = `${repositories.workspace}/.git/hooks/post-checkout`; - yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n"); - yield* fs.chmod(hook, 0o755); - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: () => - Effect.succeed({ - stops: [ - { - title: "The feature", - summary: "The change.", - attention: null, - excerpts: [{ path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }], - files: [], - notes: [], - questions: [], - }, - ], - }), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - const runs = yield* watchRuns; - yield* runs.generate(service, reference); - const result = yield* runs.settled(service, reference); - assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run)); - assert.deepStrictEqual(result.guide?.stops[0]?.excerpts, [ - { path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }, - ]); - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString( + `${repositories.workspace}/.git/info/attributes`, + "feature.txt diff=blank\n", + ); + yield* git(repositories.workspace, ["config", "diff.blank.textconv", "true"]); + const hook = `${repositories.workspace}/.git/hooks/post-checkout`; + yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n"); + yield* fs.chmod(hook, 0o755); + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + generate: () => + Effect.succeed({ + stops: [ + { + title: "The feature", + summary: "The change.", + attention: null, + excerpts: [{ path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }], + files: [], + notes: [], + questions: [], + }, + ], + }), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + const runs = yield* watchRuns; + yield* runs.generate(service, reference); + const result = yield* runs.settled(service, reference); + assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run)); + assert.deepStrictEqual(result.guide?.stops[0]?.excerpts, [ + { path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }, + ]); + }), ); it.effect("refuses generation when the verified remote disappeared despite a usable origin", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fork = `${repositories.root}/fork`; - yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); - yield* git(fork, ["branch", "stack-base", repositories.lowerSha]); - yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]); - const started = yield* Deferred.make>(); - const stored = yield* Deferred.make(); - const generated = yield* Ref.make(false); - const driver = yield* GitVcsDriver.GitVcsDriver; - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })), - }).pipe( - Layer.provide( - Layer.succeed(GitVcsDriver.GitVcsDriver, { - ...driver, - execute: (call) => - Effect.withFiber((fiber) => - Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))), - ), - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fork = `${repositories.root}/fork`; + yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); + yield* git(fork, ["branch", "stack-base", repositories.lowerSha]); + yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]); + const started = yield* Deferred.make>(); + const stored = yield* Deferred.make(); + const generated = yield* Ref.make(false); + const driver = yield* GitVcsDriver.GitVcsDriver; + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })), + }).pipe( + Layer.provide( + Layer.succeed(GitVcsDriver.GitVcsDriver, { + ...driver, + execute: (call) => + Effect.withFiber((fiber) => + Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))), + ), + }), ), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - const before = yield* service.get(reference); - yield* service.generate(reference); - // Join the background run so its failure is visible without polling service state. - yield* Fiber.await(yield* Deferred.await(started)); - const result = yield* service.get(reference); - assert.strictEqual(result.run?._tag, "Failed"); - assert.include( - result.run?._tag === "Failed" ? result.run.detail : "", - "no longer has a remote for the pull request's repository", - ); - assert.deepStrictEqual(result.guide, before.guide); - assert.isFalse(yield* Deferred.isDone(stored)); - assert.isFalse(yield* Ref.get(generated)); - }), - ), + ), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + const before = yield* service.get(reference); + yield* service.generate(reference); + // Join the background run so its failure is visible without polling service state. + yield* Fiber.await(yield* Deferred.await(started)); + const result = yield* service.get(reference); + assert.strictEqual(result.run?._tag, "Failed"); + assert.include( + result.run?._tag === "Failed" ? result.run.detail : "", + "no longer has a remote for the pull request's repository", + ); + assert.deepStrictEqual(result.guide, before.guide); + assert.isFalse(yield* Deferred.isDone(stored)); + assert.isFalse(yield* Ref.get(generated)); + }), ); it.effect("refuses a pull request from a repository the project is not a checkout of", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - identity: { - ...ACME_APP, - canonicalKey: "github.com/acme/other", - displayName: "acme/other", - name: "other", - }, - generate: () => - Effect.die("a guide must not be written from another repository's checkout"), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - const result = yield* Effect.flip(service.generate(reference)); - assert.include(result.message, "in another repository"); - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + identity: { + ...ACME_APP, + canonicalKey: "github.com/acme/other", + displayName: "acme/other", + name: "other", + }, + generate: () => + Effect.die("a guide must not be written from another repository's checkout"), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + const result = yield* Effect.flip(service.generate(reference)); + assert.include(result.message, "in another repository"); + }), ); }); diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index e559bc84dd..63bd1c88a7 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -905,6 +905,173 @@ it.effect("tells two hosts of one kind apart in the switcher and the filter", () }), ); +it.effect("retains an unavailable host's summary when it is the only queried host", () => + Effect.gen(function* () { + for (const reason of ["missing-tool", "unauthenticated"] as const) { + const service = yield* makeService({ + projects: [ + project({ + id: "p1", + title: "t3code", + workspaceRoot: "/a", + repository: "pingdotgg/t3code", + }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getViewer: () => + Effect.fail(unusable(SourceControlProviderKind.make("github"), reason)), + }), + ], + }); + + for (const filter of [{}, { host: "github.com" }]) { + const error = yield* service.list({ state: "open", ...filter }).pipe(Effect.flip); + assert.strictEqual(error._tag, "PullRequestUnavailableError"); + assert.strictEqual( + error._tag === "PullRequestUnavailableError" ? error.reason : null, + reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated", + ); + assert.isDefined(error.listResult); + const result = error.listResult!; + assert.deepStrictEqual(result.entries, []); + assert.deepStrictEqual(result.viewers, {}); + assert.deepStrictEqual( + result.providers.map(({ host, configured, projectIds }) => ({ + host, + configured, + projectIds: projectIds?.map(String), + })), + [{ host: "github.com", configured: false, projectIds: undefined }], + ); + assert.strictEqual(result.providers[0]?.detail?.includes("github"), true); + assert.deepStrictEqual( + result.errors.map(({ projectId }) => projectId), + ["p1"], + ); + } + } + }), +); + +it.effect("retains a Bitbucket host summary when the provider rejects saved credentials", () => + Effect.gen(function* () { + const provider = fakePullRequestProvider(SourceControlProviderKind.make("bitbucket"), { + getViewer: () => + Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("bitbucket"), + operation: "getViewer", + reason: "failed", + detail: "HTTP 403", + }), + ), + }); + const service = yield* makeService({ + projects: [ + project({ + id: "bitbucket", + title: "Widget", + workspaceRoot: "/widget", + repository: "acme/widget", + provider: "bitbucket", + host: "bitbucket.org", + }), + ], + providers: [provider], + }); + for (const filter of [{}, { host: "bitbucket.org" }]) { + const error = yield* service.list({ state: "open", ...filter }).pipe(Effect.flip); + assert.strictEqual(error._tag, "PullRequestOperationError"); + assert.isDefined(error.listResult); + const result = error.listResult!; + assert.deepStrictEqual( + result.providers.map(({ host, configured, projectIds }) => ({ + host, + configured, + projectIds: projectIds?.map(String), + })), + [{ host: "bitbucket.org", configured: false, projectIds: undefined }], + ); + assert.deepStrictEqual(result.entries, []); + assert.deepStrictEqual( + result.errors.map(({ projectId }) => projectId), + ["bitbucket"], + ); + } + }), +); + +it.effect.each([ + { + provider: "forgejo", + host: "ssh.forge.example", + remoteUrl: "ssh://git@ssh.forge.example:2222/team/repo.git", + }, + { + provider: "unknown", + host: "forge.example", + remoteUrl: "http://forge.example:3000/team/repo.git", + }, +])( + "identifies every worktree behind an unavailable refined Forgejo authority", + ({ provider, host, remoteUrl }) => + Effect.gen(function* () { + const service = yield* makeService({ + projects: ["ssh", "ssh-worktree"].map((id) => + project({ + id, + title: id, + workspaceRoot: `/${id}`, + repository: "team/repo", + provider, + host, + remoteUrl, + }), + ), + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("forgejo"), { + getViewer: ({ host }) => { + assert.strictEqual(host, "forge.example:3000"); + return Effect.fail( + unusable(SourceControlProviderKind.make("forgejo"), "unauthenticated"), + ); + }, + listChangeRequests: () => Effect.die("An unauthenticated host must not be queried"), + }), + ], + resolveHandle: ({ context }) => + Effect.succeed({ + context: { + ...context!, + provider: { + kind: SourceControlProviderKind.make("forgejo"), + name: "Forgejo", + baseUrl: "http://forge.example:3000", + }, + }, + provider: undefined as never, + }), + }); + const error = yield* service.list({ state: "open" }).pipe(Effect.flip); + assert.isDefined(error.listResult); + const result = error.listResult!; + assert.deepStrictEqual( + result.providers.map(({ host, configured, projectIds }) => ({ + host, + configured, + projectIds: projectIds?.map(String), + })), + [{ host: "forge.example:3000", configured: false, projectIds: ["ssh", "ssh-worktree"] }], + ); + assert.deepStrictEqual(result.entries, []); + assert.deepStrictEqual( + result.errors.map(({ projectId }) => projectId), + ["ssh"], + ); + }), +); + it.effect("reads a repository once when several worktrees share it", () => Effect.gen(function* () { let calls = 0; @@ -936,6 +1103,7 @@ it.effect("reads a repository once when several worktrees share it", () => assert.strictEqual(calls, 1); assert.strictEqual(result.entries.length, 1); + assert.isUndefined(result.providers[0]?.projectIds); }), ); @@ -1261,174 +1429,160 @@ it.effect( ); it.effect("publishes a merge for immediate settlement only after host confirmation", () => - Effect.scoped( - Effect.gen(function* () { - const mergedAt = "2026-09-03T02:00:00.000Z"; - let state: "open" | "merged" = "open"; - let confirmationFails = false; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - confirmationFails - ? Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getChangeRequestSummary", - reason: "failed", - detail: "HTTP 504", - }), - ) - : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }), - }), - ], - }); - const merges = yield* service.subscribeMerges; - const observedMerge = yield* Stream.runHead(merges).pipe( - Effect.forkChild({ startImmediately: true }), - ); + Effect.gen(function* () { + const mergedAt = "2026-09-03T02:00:00.000Z"; + let state: "open" | "merged" = "open"; + let confirmationFails = false; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + confirmationFails + ? Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "getChangeRequestSummary", + reason: "failed", + detail: "HTTP 504", + }), + ) + : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }), + }), + ], + }); + const merges = yield* service.subscribeMerges; + const observedMerge = yield* Stream.runHead(merges).pipe( + Effect.forkChild({ startImmediately: true }), + ); - assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); - const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)); - confirmationFails = true; - yield* service.runAction({ ...reference, action: "merge" }); - assert.isAbove( - Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)), - queuedRefresh, - ); - confirmationFails = false; - state = "merged"; - // The event carries the host's merge time, not the moment the confirmation ran. - yield* TestClock.setTime(Date.parse(mergedAt) + 60_000); - yield* service.runAction({ - ...reference, - repository: " ACME/WEB ", - action: "merge", - mergeMethod: "merge", - }); + assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); + const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)); + confirmationFails = true; + yield* service.runAction({ ...reference, action: "merge" }); + assert.isAbove( + Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)), + queuedRefresh, + ); + confirmationFails = false; + state = "merged"; + // The event carries the host's merge time, not the moment the confirmation ran. + yield* TestClock.setTime(Date.parse(mergedAt) + 60_000); + yield* service.runAction({ + ...reference, + repository: " ACME/WEB ", + action: "merge", + mergeMethod: "merge", + }); - assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { - ...reference, - mergedAt, - }); - }), - ), + assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { + ...reference, + mergedAt, + }); + }), ); it.effect("returns the host's merged reply as a summary and trusts it without another read", () => - Effect.scoped( - Effect.gen(function* () { - const mergedAt = "2026-09-03T02:00:00.000Z"; - const merged = { - number: 1, - title: "Change request 1", - url: "https://host/pull/1", - headBranch: "feat/1", - baseBranch: "main", - state: "merged" as const, - isDraft: false, - updatedAt: mergedAt, - mergedAt, - headSha: "abc123", - autoMergeEnabled: false, - }; - let summaryReads = 0; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - runAction: () => Effect.succeed(merged), - getChangeRequestSummary: () => - Effect.sync(() => { - summaryReads++; - return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt }; - }), - }), - ], - }); - const merges = yield* service.subscribeMerges; - const observedMerge = yield* Stream.runHead(merges).pipe( - Effect.forkChild({ startImmediately: true }), - ); - const observedAt = Date.parse("2026-09-03T02:00:01.000Z"); - yield* TestClock.setTime(observedAt); - - // Clients that did not ask decode the success as void, so they must get nothing back. - assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); - const result = yield* service.runAction({ - ...reference, - action: "merge", - replyWithSummary: true, - }); + Effect.gen(function* () { + const mergedAt = "2026-09-03T02:00:00.000Z"; + const merged = { + number: 1, + title: "Change request 1", + url: "https://host/pull/1", + headBranch: "feat/1", + baseBranch: "main", + state: "merged" as const, + isDraft: false, + updatedAt: mergedAt, + mergedAt, + headSha: "abc123", + autoMergeEnabled: false, + }; + let summaryReads = 0; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + runAction: () => Effect.succeed(merged), + getChangeRequestSummary: () => + Effect.sync(() => { + summaryReads++; + return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt }; + }), + }), + ], + }); + const merges = yield* service.subscribeMerges; + const observedMerge = yield* Stream.runHead(merges).pipe( + Effect.forkChild({ startImmediately: true }), + ); + const observedAt = Date.parse("2026-09-03T02:00:01.000Z"); + yield* TestClock.setTime(observedAt); - assert.deepStrictEqual(result, { - ...merged, - provider: SourceControlProviderKind.make("github"), - projectId: reference.projectId, - repository: reference.repository, - observedAt, - }); - assert.strictEqual(summaryReads, 0); - assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { - ...reference, - mergedAt, - }); - }), - ), + // Clients that did not ask decode the success as void, so they must get nothing back. + assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); + const result = yield* service.runAction({ + ...reference, + action: "merge", + replyWithSummary: true, + }); + + assert.deepStrictEqual(result, { + ...merged, + provider: SourceControlProviderKind.make("github"), + projectId: reference.projectId, + repository: reference.repository, + observedAt, + }); + assert.strictEqual(summaryReads, 0); + assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { + ...reference, + mergedAt, + }); + }), ); it.effect("refreshes every reader before a queued merge confirmation finishes", () => - Effect.scoped( - Effect.gen(function* () { - const confirmationStarted = yield* Deferred.make(); - const confirm = yield* Deferred.make(); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - Effect.gen(function* () { - yield* Deferred.succeed(confirmationStarted, undefined); - yield* Deferred.await(confirm); - return changeRequest(1, "2026-09-16T00:00:00.000Z"); - }), - }), - ], - }); - const merges = yield* service.subscribeMerges; - const observedMerge = yield* Stream.runHead(merges).pipe( - Effect.forkChild({ startImmediately: true }), - ); - const readers = yield* Effect.forEach([0, 1], () => - Stream.runHead(service.subscribeRefreshes).pipe( - Effect.forkChild({ startImmediately: true }), - ), - ); - const action = yield* service - .runAction({ ...reference, action: "merge" }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(confirmationStarted); - const revisions = yield* Effect.forEach(readers, (reader) => - Fiber.join(reader).pipe(Effect.map(Option.getOrThrow)), - ); - assert.isAbove(revisions[0]!, 0); - assert.strictEqual(revisions[0], revisions[1]); - assert.isUndefined(action.pollUnsafe()); - yield* Deferred.succeed(confirm, undefined); - yield* Fiber.join(action); - assert.isUndefined(observedMerge.pollUnsafe()); - }), - ), + Effect.gen(function* () { + const confirmationStarted = yield* Deferred.make(); + const confirm = yield* Deferred.make(); + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.gen(function* () { + yield* Deferred.succeed(confirmationStarted, undefined); + yield* Deferred.await(confirm); + return changeRequest(1, "2026-09-16T00:00:00.000Z"); + }), + }), + ], + }); + const merges = yield* service.subscribeMerges; + const observedMerge = yield* Stream.runHead(merges).pipe( + Effect.forkChild({ startImmediately: true }), + ); + const readers = yield* Effect.forEach([0, 1], () => + Stream.runHead(service.subscribeRefreshes).pipe(Effect.forkChild({ startImmediately: true })), + ); + const action = yield* service + .runAction({ ...reference, action: "merge" }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(confirmationStarted); + const revisions = yield* Effect.forEach(readers, (reader) => + Fiber.join(reader).pipe(Effect.map(Option.getOrThrow)), + ); + assert.isAbove(revisions[0]!, 0); + assert.strictEqual(revisions[0], revisions[1]); + assert.isUndefined(action.pollUnsafe()); + yield* Deferred.succeed(confirm, undefined); + yield* Fiber.join(action); + assert.isUndefined(observedMerge.pollUnsafe()); + }), ); it.effect("runs branch deletion only when the host and viewer support it, never for a stack", () => @@ -1723,6 +1877,71 @@ it.effect("stops new reads after a rate limit while leaving manual actions avail }), ); +it.effect( + "opening a pull request during a rate-limit pause still reads its detail and activity", + () => + Effect.gen(function* () { + let detailReads = 0; + let activityReads = 0; + const service = yield* makeService({ + projects: [ + project({ id: "p1", title: "cloud", workspaceRoot: "/cloud", repository: "acme/web" }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequest: ({ number }) => + Effect.suspend(() => { + detailReads += 1; + return number === 1 + ? Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "getChangeRequest", + reason: "rate-limited", + detail: "GitHub API rate limit exceeded.", + }), + ) + : Effect.succeed({ ...hostedChangeRequest("Body"), number }); + }), + getChangeRequestActivity: () => + Effect.sync(() => { + activityReads += 1; + return { + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }; + }), + }), + ], + }); + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 2 }; + + yield* Effect.result(service.detail({ ...reference, number: 1 })); + const background = yield* Effect.result(service.detail(reference)); + const opened = yield* Effect.result( + service + .detail(reference) + .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true)), + ); + const timeline = yield* Effect.result( + service + .activity(reference) + .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true)), + ); + + expect(background).toMatchObject({ _tag: "Failure" }); + expect({ opened, timeline }).toMatchObject({ + opened: { _tag: "Success", success: { number: 2 } }, + timeline: { _tag: "Success", success: { commentCount: 0 } }, + }); + assert.strictEqual(detailReads, 2); + assert.strictEqual(activityReads, 1); + }), +); + it.effect("refuses a repository that does not belong to the requested project", () => Effect.gen(function* () { const service = yield* makeService({ @@ -1982,6 +2201,72 @@ it.effect("routes a hosted reference to another repository through a project on }), ); +it.effect("an uncached summary reaches the host despite a cached read in another project", () => + Effect.gen(function* () { + const caller = project({ + id: "caller", + title: "caller", + workspaceRoot: "/caller", + repository: "acme/other", + }); + const target = project({ + id: "gitlab", + title: "gitlab", + workspaceRoot: "/gitlab", + repository: "team/project", + provider: "gitlab", + }); + let missing = false; + let reads = 0; + const service = yield* makeService({ + projects: [caller, target], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github")), + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + getChangeRequestSummary: (input) => + Effect.suspend(() => { + reads++; + assert.strictEqual(input.cwd, target.workspaceRoot); + assert.strictEqual(input.repository, "team/project"); + assert.strictEqual(input.host, "gitlab.com"); + return missing + ? Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("gitlab"), + operation: "summary", + reason: "missing-tool", + detail: "The hosting CLI is unavailable.", + }), + ) + : Effect.succeed(changeRequest(42, "2026-07-02T00:00:00Z")); + }), + }), + ], + }); + const reference = { + projectId: caller.id, + host: "gitlab.com", + repository: "team/project", + number: 42, + allowStale: false, + }; + yield* service.summary(reference, { recoverTransientFailure: false }); + missing = true; + yield* service.summary(reference, { recoverTransientFailure: false }); + assert.strictEqual(reads, 1); + + const error = yield* service + .summary(reference, { recoverTransientFailure: false, bypassCache: true }) + .pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "PullRequestUnavailableError", + reason: "cli-missing", + provider: "gitlab", + }); + assert.strictEqual(reads, 2); + }), +); + it.effect("routes Azure reads and writes through the requested organization's checkout", () => Effect.gen(function* () { const seen: string[] = []; @@ -2090,7 +2375,10 @@ it.effect.each([ }), ); -it.effect("refuses Azure cross-organization reads and writes without its checkout", () => +it.effect.each([ + { case: "another organization", repository: "org-b/project/_git/web" }, + { case: "a sibling repository", repository: "org-a/project/_git/web-e2e" }, +])("refuses Azure reads and writes in $case without its checkout", ({ repository }) => Effect.gen(function* () { const service = yield* makeService({ projects: [ @@ -2114,15 +2402,48 @@ it.effect("refuses Azure cross-organization reads and writes without its checkou const reference = { projectId: "org-a" as ProjectId, host: "dev.azure.com", - repository: "org-b/project/_git/web", + repository, number: 7, }; const readError = yield* Effect.flip( service.summary(reference, { recoverTransientFailure: false }), ); const writeError = yield* Effect.flip(service.runAction({ ...reference, action: "close" })); - assert.strictEqual(readError._tag, "PullRequestUnavailableError"); - assert.strictEqual(writeError._tag, "PullRequestUnavailableError"); + for (const error of [readError, writeError]) { + expect(error).toMatchObject({ + _tag: "PullRequestUnavailableError", + reason: "repository-without-project", + message: `${repository} is not a project in 456code. Add it as a project to read its change requests.`, + }); + } + }), +); + +// regression: #37633 any checkout on the host routes the read, so name the host, not the repository +it.effect("names the host when no project has a checkout on it for a host-routed read", () => + Effect.gen(function* () { + const service = yield* makeService({ + projects: [project({ id: "wrapper", title: "Wrapper", workspaceRoot: "/work" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + getChangeRequestSummary: () => Effect.die("no checkout to read through"), + }), + ], + }); + const error = yield* Effect.flip( + service.summary( + { + projectId: "wrapper" as ProjectId, + host: "gitlab.com", + repository: "acme/web", + number: 7, + }, + { recoverTransientFailure: false }, + ), + ); + assert.strictEqual(error._tag, "PullRequestUnavailableError"); + expect(error.message).not.toContain("acme/web is not a project"); + expect(error.message).toContain("gitlab.com"); }), ); @@ -2438,6 +2759,40 @@ it.effect("does not revive old summaries when project epochs are evicted", () => }), ); +it.effect("a finished turn leaves another project's cached listing in place", () => + Effect.gen(function* () { + const reads: string[] = []; + const service = yield* makeService({ + projects: [ + project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), + project({ id: "p2", title: "api", workspaceRoot: "/b", repository: "acme/api" }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + listChangeRequests: ({ repository }) => { + reads.push(repository); + return Effect.succeed({ items: [], truncated: false, continues: false }); + }, + }), + ], + }); + const webListing = { state: "open" as const, projectId: "p1" as ProjectId }; + const everyListing = { state: "open" as const }; + + yield* service.list(webListing); + yield* service.list(everyListing); + reads.length = 0; + yield* service.refreshAfterTurn("p2" as ProjectId); + yield* service.list(webListing); + yield* service.list(everyListing); + assert.deepStrictEqual(reads, []); + + yield* service.refreshAfterTurn("p2" as ProjectId, { pushed: true }); + yield* service.list(everyListing); + assert.deepStrictEqual(reads.toSorted(), ["acme/api", "acme/web"]); + }), +); + it.effect("a refresh or a finished turn drops the provider's own change request reads", () => Effect.gen(function* () { const forgotten: Array<{ readonly repository: string; readonly number?: number } | undefined> = @@ -2531,56 +2886,52 @@ it.effect("a read during a refresh cannot keep the provider's old change request ); it.effect("close and reopen notify subscribed readers after invalidating their cached state", () => - Effect.scoped( - Effect.gen(function* () { - let hostCalls = 0; - let state: "open" | "closed" = "open"; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }), - runAction: (input) => - Effect.sync(() => { - state = input.action === "close" ? "closed" : "open"; - }), - listChangeRequests: () => { - hostCalls += 1; - return Effect.succeed({ items: [], truncated: false, continues: false }); - }, - }), - ], - }); - - yield* service.refreshAfterTurn(reference.projectId); - yield* service.list({ state: "open" }); - assert.strictEqual((yield* service.summary(reference)).state, "open"); - for (const action of ["close", "reopen"] as const) { - const refreshed = yield* service.subscribeRefreshes.pipe( - Stream.drop(1), - Stream.take(1), - Stream.mapEffect(() => - Effect.gen(function* () { - yield* service.list({ state: "open" }); - return yield* service.summary(reference); + Effect.gen(function* () { + let hostCalls = 0; + let state: "open" | "closed" = "open"; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }), + runAction: (input) => + Effect.sync(() => { + state = input.action === "close" ? "closed" : "open"; }), - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - yield* service.runAction({ ...reference, action }); - assert.strictEqual( - Option.getOrThrow(yield* Fiber.join(refreshed)).state, - action === "close" ? "closed" : "open", - ); - } - assert.strictEqual(hostCalls, 3); - }), - ), + listChangeRequests: () => { + hostCalls += 1; + return Effect.succeed({ items: [], truncated: false, continues: false }); + }, + }), + ], + }); + + yield* service.refreshAfterTurn(reference.projectId); + yield* service.list({ state: "open" }); + assert.strictEqual((yield* service.summary(reference)).state, "open"); + for (const action of ["close", "reopen"] as const) { + const refreshed = yield* service.subscribeRefreshes.pipe( + Stream.drop(1), + Stream.take(1), + Stream.mapEffect(() => + Effect.gen(function* () { + yield* service.list({ state: "open" }); + return yield* service.summary(reference); + }), + ), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* service.runAction({ ...reference, action }); + assert.strictEqual( + Option.getOrThrow(yield* Fiber.join(refreshed)).state, + action === "close" ? "closed" : "open", + ); + } + assert.strictEqual(hostCalls, 3); + }), ); it.effect("reads a host's repositories in one search, and files the rows back under each", () => @@ -2702,7 +3053,13 @@ it.effect("carries a slice on without sending the rows it already sent", () => cursors: { "github.com acme/web": "2026-07-02T00:00:00Z|1|3" }, }); - assert.deepStrictEqual(cursors, [{ updatedBefore: "2026-07-02T00:00:00Z", delivered: 1 }]); + assert.deepStrictEqual(cursors, [ + { + updatedBefore: "2026-07-02T00:00:00Z", + delivered: 1, + seenAt: [{ repository: "acme/web", number: 3 }], + }, + ]); assert.deepStrictEqual( result.entries.map((entry) => entry.number), [4], @@ -2928,6 +3285,40 @@ it.effect("reads the fresh diff when detail or summary discovers a changed revis }), ); +it.effect("keeps a withheld file's read out of the page's cached diff", () => + Effect.gen(function* () { + const provider = fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getDiff: (input) => + Effect.succeed({ + patch: input.path === undefined ? "page" : `file ${input.path}`, + truncated: input.path === undefined, + nextCursor: null, + }), + }); + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [provider], + }); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 10 }; + assert.strictEqual((yield* service.diff(ref)).patch, "page"); + assert.strictEqual( + (yield* service.diff({ ...ref, path: "sdk.patch" })).patch, + "file sdk.patch", + ); + assert.strictEqual((yield* service.diff(ref)).patch, "page"); + + // A host that would answer with its whole diff must not be cached as one file's. + const wholeDiffOnly = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + { ...provider, capabilities: { ...provider.capabilities, withheldFileDiff: false } }, + ], + }); + const error = yield* Effect.flip(wholeDiffOnly.diff({ ...ref, path: "sdk.patch" })); + assert.strictEqual(error._tag, "PullRequestOperationError"); + }), +); + it.effect("keeps routed reads separate when the GitHub account changes", () => Effect.gen(function* () { for (const operation of ["summary", "detail", "checks", "diff", "filesViewed"] as const) { @@ -3137,6 +3528,7 @@ it.effect( Effect.succeed({ ...changeRequest(1, "2026-07-02T00:00:00Z"), isDraft: true, + rebaseRequired: false, reviewDecision: "approved", checksState: "passing", }), @@ -3146,6 +3538,7 @@ it.effect( deletions: 3, changedFiles: 5, mergeability: "conflicting", + rebaseRequired: true, }), }), ], @@ -3153,6 +3546,8 @@ it.effect( yield* service.summary(reference); const detail = yield* service.detail(reference); const summary = yield* service.summary(reference); + assert.strictEqual(detail.rebaseRequired, true); + assert.strictEqual(summary.rebaseRequired, true); assert.strictEqual(summary.isDraft, false); assert.deepStrictEqual(summary.author, detail.author); assert.strictEqual(summary.additions, 14); @@ -3164,6 +3559,27 @@ it.effect( }), ); +it.effect("preserves merge queue removal details from the provider", () => + Effect.gen(function* () { + const removal = { id: "RMQE_1", removedAt: "2026-07-02T00:00:00Z", reason: "CI failed" }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequest: () => + Effect.succeed({ ...hostedChangeRequest("body"), mergeQueueRemoval: removal }), + }), + ], + }); + const detail = yield* service.detail({ + projectId: "p1" as ProjectId, + repository: "acme/web", + number: 1, + }); + assert.deepStrictEqual(detail.mergeQueueRemoval, removal); + }), +); + it.effect("notifies linked threads when detail changes draft status in either direction", () => Effect.gen(function* () { let isDraft = true; @@ -3232,19 +3648,31 @@ it.effect("deduplicates routed PR reports without dropping draft changes", () => }), ); -it.effect( - "reuses fresh detail checks without extending their refresh interval on detail cache hits", - () => +it.effect.each(["github", "azure-devops"])( + "reuses fresh %s detail checks without extending their refresh interval on detail cache hits", + (provider) => Effect.gen(function* () { let reads = 0; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const repository = provider === "azure-devops" ? "web" : "acme/web"; + const reference = { projectId: "p1" as ProjectId, repository, number: 1 }; const service = yield* makeService({ projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), + project({ + id: "p1", + title: "web", + workspaceRoot: "/a", + repository, + provider, + ...(provider === "azure-devops" ? { host: "dev.azure.com" } : {}), + }), ], providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => Effect.succeed(hostedChangeRequest("Description")), + fakePullRequestProvider(SourceControlProviderKind.make(provider), { + getChangeRequest: () => + Effect.succeed({ + ...hostedChangeRequest("Description"), + checks: [{ name: "build", status: "success", description: null, url: null }], + }), getChangeRequestChecks: () => Effect.sync(() => { reads += 1; @@ -3274,6 +3702,37 @@ it.effect( }), ); +it.effect("asks Azure for checks when its detail came back with none", () => + Effect.gen(function* () { + let reads = 0; + const reference = { projectId: "p1" as ProjectId, repository: "web", number: 1 }; + const service = yield* makeService({ + projects: [ + project({ + id: "p1", + title: "web", + workspaceRoot: "/a", + repository: "web", + provider: "azure-devops", + }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), { + getChangeRequest: () => Effect.succeed(hostedChangeRequest("Description")), + getChangeRequestChecks: () => + Effect.sync(() => { + reads += 1; + return { state: "open" as const, checks: [] }; + }), + }), + ], + }); + yield* service.detail(reference); + yield* service.checks(reference); + expect(reads).toBe(1); + }), +); + it.effect("preserves check observation time on cache hits and advances it on refresh", () => Effect.gen(function* () { let reads = 0; @@ -4040,32 +4499,40 @@ it.effect("keeps viewed files itself for a host that keeps none of its own", () }), ); -it.effect("reports a file pushed to since it was cleared as changed", () => +it.effect("records shown revisions until the reader ticks the pushed version", () => Effect.gen(function* () { + const asked: Array> = []; const revisions = new Map([ - ["src/a.ts", "blob-a"], - ["src/b.ts", "blob-b"], + ["src/a.ts", "pushed-a"], + ["src/b.ts", "current-b"], ]); - const service = yield* environmentViewedService(revisions, []); + const service = yield* environmentViewedService(revisions, asked); yield* service.setFilesViewed({ ...GITLAB_REFERENCE, files: [ - { path: "src/a.ts", viewed: true }, + { path: "src/a.ts", viewed: true, revision: "shown-a" }, { path: "src/b.ts", viewed: true }, ], }); - revisions.set("src/a.ts", "blob-a-again"); + assert.deepStrictEqual(asked, [["src/b.ts"]]); yield* service.invalidate({ reference: GITLAB_REFERENCE }); - const marked = yield* service.filesViewed(GITLAB_REFERENCE); + assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ + { path: "src/a.ts", state: "dismissed" }, + { path: "src/b.ts", state: "viewed" }, + ]); - assert.deepStrictEqual( - [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)), - [ - { path: "src/a.ts", state: "dismissed" }, - { path: "src/b.ts", state: "viewed" }, - ], - ); + const reads = asked.length; + revisions.set("src/a.ts", "pushed-a-again"); + yield* service.setFilesViewed({ + ...GITLAB_REFERENCE, + files: [{ path: "src/a.ts", viewed: true, revision: "pushed-a-again" }], + }); + assert.strictEqual(asked.length, reads); + assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ + { path: "src/a.ts", state: "viewed" }, + { path: "src/b.ts", state: "viewed" }, + ]); }), ); @@ -4117,6 +4584,26 @@ it.effect("leaves a mark alone when the host could not say what the head has of }), ); +it.effect("reports a file pushed to after the diff the reader ticked was drawn as changed", () => + Effect.gen(function* () { + const revisions = new Map([["src/a.ts", "shown-a"]]); + const service = yield* environmentViewedService(revisions, []); + + yield* service.filesViewed(GITLAB_REFERENCE); + yield* TestClock.adjust("61 seconds"); + revisions.set("src/a.ts", "pushed-a"); + yield* service.setFilesViewed({ + ...GITLAB_REFERENCE, + files: [{ path: "src/a.ts", viewed: true, revision: "shown-a" }], + }); + yield* service.invalidate({ reference: GITLAB_REFERENCE }); + + assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ + { path: "src/a.ts", state: "dismissed" }, + ]); + }), +); + it.effect("forgets what the head had of a marked file once a mutation moves the head", () => Effect.gen(function* () { const revisions = new Map([["src/a.ts", "blob-a"]]); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 8200b774ad..08204c8ba2 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -198,8 +198,14 @@ export class PullRequestService extends Context.Service< ) => Effect.Effect; readonly summary: ( input: PullRequestRef, - options?: { readonly recoverTransientFailure?: boolean }, + options?: { + readonly recoverTransientFailure?: boolean; + /** Registration preflights must reach the provider despite a successful cached read. */ + readonly bypassCache?: boolean; + }, ) => Effect.Effect; + /** Whether the reference's host batches summary reads; false when it cannot be resolved. */ + readonly batchesReads: (input: PullRequestRef) => Effect.Effect; readonly stack: ( input: PullRequestRef, options?: { readonly includeDetails?: boolean }, @@ -218,7 +224,13 @@ export class PullRequestService extends Context.Service< input: PullRequestReportStateInput, ) => Effect.Effect; readonly subscribeRefreshes: Stream.Stream; - readonly refreshAfterTurn: (projectId: ProjectId) => Effect.Effect; + readonly subscribeLinkedThreadRefreshes: Stream.Stream; + /** Wakes linked-thread readers only; other pull request reads don't depend on thread links. */ + readonly notifyLinkedThreadsChanged: Effect.Effect; + readonly refreshAfterTurn: ( + projectId: ProjectId, + options?: { readonly pushed?: boolean }, + ) => Effect.Effect; /** Project and remote lookups inside `effect` read once per filter, e.g. across one sync sweep. */ readonly withSharedProjectReads: ( effect: Effect.Effect, @@ -344,6 +356,7 @@ interface WorkspaceProjects { { readonly kind: SourceControlProviderKind; readonly projectCount: number } >; readonly viewerRoots: ReadonlyMap>; + readonly refinedProjectIdsByHost: ReadonlyMap>; } // Inherited by fibers forked inside the scope, so it is closed, not just dropped, when the scope ends. @@ -470,32 +483,37 @@ function withRateLimitBackoff( const protect =
    ( operation: string, effect: Effect.Effect, - allowPaused: boolean, + alwaysInteractive: boolean, ) => - limits.check(key, allowPaused ? { allowPaused: true } : undefined).pipe( - Effect.mapError( - (error) => - new PullRequestProviderError({ - provider: api.kind, - operation, - reason: "rate-limited", - detail: error.detail, - retryAt: error.retryAt, - cause: error, - }), - ), - Effect.flatMap((lease) => - effect.pipe( - Effect.provideService(SourceControlRateLimit.Interactive, allowPaused), - Effect.tap(() => limits.recordSuccess({ ...key, lease })), - Effect.tapError((error) => - error.reason === "rate-limited" - ? limits.recordRateLimit({ - ...key, - lease, - ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }), - }) - : Effect.void, + SourceControlRateLimit.Interactive.pipe( + Effect.map((callerInteractive) => alwaysInteractive || callerInteractive), + Effect.flatMap((allowPaused) => + limits.check(key, allowPaused ? { allowPaused: true } : undefined).pipe( + Effect.mapError( + (error) => + new PullRequestProviderError({ + provider: api.kind, + operation, + reason: "rate-limited", + detail: error.detail, + retryAt: error.retryAt, + cause: error, + }), + ), + Effect.flatMap((lease) => + effect.pipe( + Effect.provideService(SourceControlRateLimit.Interactive, allowPaused), + Effect.tap(() => limits.recordSuccess({ ...key, lease })), + Effect.tapError((error) => + error.reason === "rate-limited" + ? limits.recordRateLimit({ + ...key, + lease, + ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }), + }) + : Effect.void, + ), + ), ), ), ), @@ -504,10 +522,10 @@ function withRateLimitBackoff( , A>( operation: string, call: (...args: Args) => Effect.Effect, - allowPaused = false, + alwaysInteractive = false, ) => (...args: Args) => - protect(operation, call(...args), allowPaused); + protect(operation, call(...args), alwaysInteractive); const interactive = , A>( operation: string, call: (...args: Args) => Effect.Effect, @@ -527,6 +545,7 @@ function withRateLimitBackoff( ...(api.readsPublicHostWithoutCheckout === undefined ? {} : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }), + ...(api.batchesReads === undefined ? {} : { batchesReads: api.batchesReads }), getViewer: options?.viewerAllowsPause === true ? interactive("getViewer", api.getViewer) @@ -722,6 +741,7 @@ export const make = Effect.gen(function* () { const mergedPullRequests = yield* PubSub.sliding(64); const stateChanges = yield* PubSub.sliding(64); const pullRequestRefreshes = yield* SubscriptionRef.make(0); + const linkedThreadRefreshes = yield* SubscriptionRef.make(0); const registry = yield* PullRequestProviderRegistry.PullRequestProviderRegistry; const requirementOf: UnavailableRequirementOf = (kind) => registry.get(kind)?.unavailableRequirement; @@ -930,6 +950,7 @@ export const make = Effect.gen(function* () { { kind: SourceControlProviderKind; projectCount: number } >(); const viewerRoots = new Map(); + const refinedProjectIdsByHost = new Map(); const seen = new Set(); for (const project of projects) { if (filter.projectId !== undefined && project.id !== filter.projectId) continue; @@ -950,6 +971,11 @@ export const make = Effect.gen(function* () { if (filter.host !== undefined && host !== filter.host.toLowerCase()) { continue; } + if (host !== sourceControlDefinitions.changeRequestHost(identity, identity.provider)) { + const projectIds = refinedProjectIdsByHost.get(host); + if (projectIds === undefined) refinedProjectIdsByHost.set(host, [project.id]); + else projectIds.push(project.id); + } const registered = registry.get(kind); const api = registered?.servesHost?.(host) === false ? null : registered; if (api !== null) { @@ -983,7 +1009,7 @@ export const make = Effect.gen(function* () { : sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()), }); } - return { supported, unimplemented, viewerRoots }; + return { supported, unimplemented, viewerRoots, refinedProjectIdsByHost }; }), ); @@ -1058,6 +1084,21 @@ export const make = Effect.gen(function* () { }; } } + const owner = + publicHost ?? sourceControlDefinitions.findByRepositoryKey(referenceKey); + const readable = owner === undefined ? null : registry.get(owner.kind); + if ( + readable !== null && + !readable.readsPublicHostWithoutCheckout && + readable.servesHost?.(host) !== false + ) { + // Without repository keys, any checkout on the host routes the read. + return yield* new PullRequestUnavailableError( + readable.repositoryKey === undefined + ? { reason: "repository-without-project", host } + : { reason: "repository-without-project", repository }, + ); + } return yield* new PullRequestUnavailableError({ reason: "provider-unsupported" }); }); } @@ -1283,6 +1324,9 @@ export const make = Effect.gen(function* () { state: input.item.state, isDraft: input.item.isDraft, mergeability: input.item.mergeability, + ...(input.item.rebaseRequired === undefined + ? {} + : { rebaseRequired: input.item.rebaseRequired }), additions: input.item.additions, deletions: input.item.deletions, createdAt: input.item.createdAt, @@ -1307,7 +1351,12 @@ export const make = Effect.gen(function* () { const involvement = input.involvement ?? "all"; const epochAtStart = epochCounter; const continuation = yield* decodeCursors(input.cursors); - const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input); + const { + supported: projects, + unimplemented, + viewerRoots, + refinedProjectIdsByHost, + } = yield* listWorkspaceProjects(input); const projectCounts = new Map(); for (const { host } of projects) { projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1); @@ -1329,6 +1378,7 @@ export const make = Effect.gen(function* () { searchesOnHost: capabilities?.search ?? false, actions: capabilities?.actions ?? [], projectCount: projectCounts.get(result.host) ?? 1, + projectIds: refinedProjectIdsByHost.get(result.host), configured: result.viewer !== null, detail: result.error === null ? null : providerDetail(requirementOf, result.error), }; @@ -1339,6 +1389,7 @@ export const make = Effect.gen(function* () { searchesOnHost: false, actions: [], projectCount, + projectIds: refinedProjectIdsByHost.get(host), configured: false, detail: "This host cannot be browsed here yet.", })), @@ -1357,6 +1408,14 @@ export const make = Effect.gen(function* () { message: `${repository} could not be read.`, })); if (readable.length === 0) { + const listResult: PullRequestListResult = { + viewers: viewers as PullRequestListResult["viewers"], + providers, + entries: [], + errors: unreadable, + truncated: false, + nextCursors: {}, + }; const errors = viewerResults.flatMap((result) => result.error === null || !selected.some(({ host }) => host === result.host) ? [] @@ -1364,17 +1423,13 @@ export const make = Effect.gen(function* () { ); const blocking = errors.find(isProviderUnusable) ?? errors[0]; if (blocking) { - return yield* toPullRequestError("list")(blocking); + // Preserve failure/retry semantics while letting clients try another server for these hosts. + const error = toPullRequestError("list")(blocking); + return yield* error._tag === "PullRequestUnavailableError" + ? new PullRequestUnavailableError({ ...error, listResult }) + : new PullRequestOperationError({ ...error, listResult }); } - - return { - viewers: viewers as PullRequestListResult["viewers"], - providers, - entries: [], - errors: [], - truncated: false, - nextCursors: {}, - }; + return listResult; } const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT; @@ -1513,7 +1568,18 @@ export const make = Effect.gen(function* () { filters: input.filters, ...(cursor === undefined ? {} - : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }), + : { + cursor: { + updatedBefore: cursor.updatedBefore, + delivered: cursor.delivered, + seenAt: chunk.flatMap((project) => + (cursorOf(project)?.seenAt ?? []).map((number) => ({ + repository: project.repository, + number, + })), + ), + }, + }), }).pipe( observeRead, Effect.flatMap(({ value: page, observedAt }) => { @@ -1744,6 +1810,9 @@ export const make = Effect.gen(function* () { ...(changeRequest.mergeability === undefined ? {} : { mergeability: changeRequest.mergeability }), + ...(changeRequest.rebaseRequired === undefined + ? {} + : { rebaseRequired: changeRequest.rebaseRequired }), ...(changeRequest.stack === undefined ? {} : { stack: changeRequest.stack }), ...(changeRequest.headSha?.trim() ? { headSha: changeRequest.headSha.trim() } : {}), ...(changeRequest.autoMergeEnabled === undefined @@ -1843,6 +1912,9 @@ export const make = Effect.gen(function* () { state: changeRequest.state, isDraft: changeRequest.isDraft, mergeability: changeRequest.mergeability, + ...(changeRequest.rebaseRequired === undefined + ? {} + : { rebaseRequired: changeRequest.rebaseRequired }), additions: changeRequest.additions, deletions: changeRequest.deletions, changedFiles: changeRequest.changedFiles, @@ -1879,6 +1951,9 @@ export const make = Effect.gen(function* () { ...(changeRequest.workflowApprovalsRequired === undefined ? {} : { workflowApprovalsRequired: changeRequest.workflowApprovalsRequired }), + ...(changeRequest.mergeQueueRemoval === undefined + ? {} + : { mergeQueueRemoval: changeRequest.mergeQueueRemoval }), })), ), ), @@ -1938,6 +2013,9 @@ export const make = Effect.gen(function* () { ? {} : { reviewThreadsTruncated: activity.reviewThreadsTruncated }), reviewThreads: activity.reviewThreads, + ...(activity.overviewThreads === undefined + ? {} + : { overviewThreads: activity.overviewThreads }), commits: activity.commits, ...(activity.reactions === undefined ? {} : { reactions: activity.reactions }), })), @@ -1973,23 +2051,31 @@ export const make = Effect.gen(function* () { const diffUncached: PullRequestService["Service"]["diff"] = (input) => requireProject(input).pipe( Effect.flatMap((project) => - project.api.capabilities.diff - ? project.api - .getDiff({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - ...(input.cursor === undefined ? {} : { cursor: input.cursor }), - ...(input.commit === undefined ? {} : { commit: input.commit }), - }) - .pipe(Effect.mapError(toPullRequestError("diff"))) - : Effect.fail( + input.path !== undefined && project.api.capabilities.withheldFileDiff !== true + ? Effect.fail( new PullRequestOperationError({ operation: "diff", - detail: "This host cannot provide a diff for a change request.", + detail: "This host cannot read one file of a change request's diff.", }), - ), + ) + : project.api.capabilities.diff + ? project.api + .getDiff({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + ...(input.path === undefined ? {} : { path: input.path }), + ...(input.cursor === undefined ? {} : { cursor: input.cursor }), + ...(input.commit === undefined ? {} : { commit: input.commit }), + }) + .pipe(Effect.mapError(toPullRequestError("diff"))) + : Effect.fail( + new PullRequestOperationError({ + operation: "diff", + detail: "This host cannot provide a diff for a change request.", + }), + ), ), ); @@ -2042,7 +2128,14 @@ export const make = Effect.gen(function* () { // Deliberately not `invalidatedByMutation`: ticking a file off says nothing about the // change request, and dropping a 300-file diff on every checkbox is the whole cost of // the feature. - Effect.ensuring(Effect.sync(() => bumpFilesViewedEpoch(ref))), + Effect.ensuring( + Effect.sync(() => { + bumpFilesViewedEpoch(ref); + if (input.files.some((file) => file.viewed && file.revision !== undefined)) { + bumpEpoch(fileRevisionEpochs, ref); + } + }), + ), ), ), ); @@ -2954,6 +3047,7 @@ export const make = Effect.gen(function* () { const filesViewedEpoch = (ref: PullRequestRef) => filesViewedEpochs.get(refScope(ref)) ?? 0; const bumpFilesViewedEpoch = (ref: PullRequestRef) => bumpEpoch(filesViewedEpochs, ref); + const fileRevisionEpochs = new Map(); let everyFileRevisionEpoch = 0; const viewedFiles = ViewedFiles.make({ filesViewedStore, @@ -2962,7 +3056,8 @@ export const make = Effect.gen(function* () { toPullRequestError, runFork, refEpoch, - fileRevisionsEpoch: () => everyFileRevisionEpoch, + fileRevisionsEpoch: (ref) => + `${everyFileRevisionEpoch}:${fileRevisionEpochs.get(refScope(ref)) ?? 0}`, }); const filtersOfKey = ( @@ -3028,19 +3123,33 @@ export const make = Effect.gen(function* () { const summary: PullRequestService["Service"]["summary"] = (input, options) => { const key = refCacheKey(input); - const cached = persistedRead(input, "summary", summaryCodec, summaryUncached(input)); + const read = + options?.bypassCache === true + ? summaryUncached(input) + : persistedRead(input, "summary", summaryCodec, summaryUncached(input)); const held = lastGoodSummary.peek(key); - return held !== undefined && + return options?.bypassCache !== true && + held !== undefined && input.allowStale !== false && (options?.recoverTransientFailure !== false || held.state === "merged") ? Effect.succeed(held) - : cached.pipe( + : read.pipe( Effect.tap((value) => shouldReplaceHeldSummary(key, value) ? lastGoodSummary.record(key, value) : Effect.void, ), ); }; + const batchesReads: PullRequestService["Service"]["batchesReads"] = Effect.fn( + "PullRequestService.batchesReads", + )( + function* (input) { + const project = yield* requireProject(input); + return project.api.batchesReads === true; + }, + Effect.orElseSucceed(() => false), + ); + const stack: PullRequestService["Service"]["stack"] = (input, options) => persistedRead( input, @@ -3195,9 +3304,11 @@ export const make = Effect.gen(function* () { return detailUncached(refOfCacheKey(key)).pipe( Effect.tap( Effect.fn("PullRequestService.recordDetailStats")(function* (value: PullRequestDetail) { - // GitHub detail includes the same checks; the checks TTL counts from their observation. + // GitHub and Azure detail include the same checks; the checks TTL counts from their observation. + // Azure detail answers a failed policy read with no checks, which must not be cached. if ( - value.provider === "github" && + (value.provider === "github" || + (value.provider === "azure-devops" && value.checks.length > 0)) && value.observedAt !== undefined && !(yield* Cache.has(checksCache, key)) ) { @@ -3247,6 +3358,7 @@ export const make = Effect.gen(function* () { deletions: detail.deletions, changedFiles: detail.changedFiles, mergeability: detail.mergeability, + ...(detail.rebaseRequired === undefined ? {} : { rebaseRequired: detail.rebaseRequired }), headBranch: detail.headBranch, baseBranch: detail.baseBranch, closedAt: detail.closedAt, @@ -3410,16 +3522,26 @@ export const make = Effect.gen(function* () { const diffCache = yield* Cache.makeWith( (key: string) => { - const [reference, cursor, commit] = JSON.parse(key) as [string, string | null, string | null]; + const [reference, cursor, commit, , path] = JSON.parse(key) as [ + string, + string | null, + string | null, + string | null, + string | null, + ]; return diffUncached({ ...refOfCacheKey(reference), + ...(path === null ? {} : { path }), ...(cursor === null ? {} : { cursor }), ...(commit === null ? {} : { commit }), } as PullRequestDiffInput).pipe( observeRead, Effect.tap(({ value, observedAt }) => { // Keep the loader's epoch and read time if a refresh occurs during the provider read. - diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt); + // One withheld file is not the page's file list. + if (path === null) { + diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt); + } return Effect.void; }), ); @@ -3466,6 +3588,7 @@ export const make = Effect.gen(function* () { input.commit === undefined ? (lastGoodSummary.peek(refCacheKey(input))?.updatedAt ?? null) : null, + input.path ?? null, ]); const evictDiffs = Cache.entries(diffCache).pipe( Effect.flatMap((entries) => @@ -3609,12 +3732,14 @@ export const make = Effect.gen(function* () { const refreshAfterTurn: PullRequestService["Service"]["refreshAfterTurn"] = Effect.fn( "PullRequestService.refreshAfterTurn", - )(function* (projectId) { + )(function* (projectId, options) { // Everything the provider holds, not just the project's repository: a turn can touch a // change request reached through another repository, and no epoch may move until those // reads are gone, or a reader in between keeps the old one under the new epoch. yield* forgetProviderReads(); - listingsEpoch = ++epochCounter; + const epoch = ++epochCounter; + // A push can open or move a PR; a plain turn waits for the listing TTL to spare the API quota. + if (options?.pushed === true) listingsEpoch = epoch; projectEpochs.delete(projectId); if (projectEpochs.size >= REF_EPOCH_CAPACITY) { const oldest = projectEpochs.keys().next().value; @@ -3623,12 +3748,16 @@ export const make = Effect.gen(function* () { projectEpochs.delete(oldest); } } - projectEpochs.set(projectId, listingsEpoch); - const epoch = listingsEpoch; + projectEpochs.set(projectId, epoch); yield* readCache.invalidate(`project:${projectId}`); yield* SubscriptionRef.set(pullRequestRefreshes, epoch); }); + const notifyLinkedThreadsChanged = SubscriptionRef.update( + linkedThreadRefreshes, + (revision) => revision + 1, + ); + const invalidatedByMutation = ( method: (input: I) => Effect.Effect, @@ -3816,6 +3945,7 @@ export const make = Effect.gen(function* () { return yield* listStats({ ...input, refs: refs.flatMap(Option.toArray) }); }), summary: credentialCached(summary), + batchesReads, stack: credentialCached(stack), subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe( Effect.map((subscription) => Stream.fromSubscription(subscription)), @@ -3827,6 +3957,10 @@ export const make = Effect.gen(function* () { subscribeRefreshes: SubscriptionRef.changes(pullRequestRefreshes).pipe( Stream.filter((revision) => revision > 0), ), + subscribeLinkedThreadRefreshes: SubscriptionRef.changes(linkedThreadRefreshes).pipe( + Stream.filter((revision) => revision > 0), + ), + notifyLinkedThreadsChanged, refreshAfterTurn, detail: credentialCached(detail), checks: credentialCached((input) => Cache.get(checksCache, refCacheKey(input))), diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts new file mode 100644 index 0000000000..2c4f4d92e4 --- /dev/null +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -0,0 +1,294 @@ +import { + ProjectId, + ProviderInstanceId, + ThreadId, + PullRequestOperationError, + PullRequestUnavailableError, + type PullRequestSummary, + type OrchestrationV2ServerCommand as OrchestrationCommand, + type OrchestrationProjectShell, + type ThreadPullRequestLink, + SourceControlProviderKind, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { + type PullRequestTestThread, + v2PullRequestThread, +} from "../orchestration-v2/testkit/pullRequestFixtures.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "./PullRequestService.ts"; +import * as PullRequestWatchService from "./PullRequestWatchService.ts"; +import type { PullRequestTarget } from "./pullRequestTarget.ts"; + +const PROJECT_ID = ProjectId.make("project-1"); +const THREAD_ID = ThreadId.make("thread-1"); +const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(7)); + +function makeProject( + repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = { + canonicalKey: "github.com/t3tools/t3code", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "git@github.com:T3Tools/T3Code.git", + }, + provider: SourceControlProviderKind.make("github"), + displayName: "T3Tools/T3Code", + owner: "T3Tools", + name: "T3Code", + }, +): OrchestrationProjectShell { + return { + id: PROJECT_ID, + title: "Project", + workspaceRoot: "/workspace/project", + defaultModelSelection: null, + scripts: [], + repositoryIdentity, + createdAt: "2026-08-01T00:00:00.000Z", + updatedAt: "2026-08-01T00:00:00.000Z", + }; +} + +function makeThread(pullRequests: ReadonlyArray): PullRequestTestThread { + return { + id: THREAD_ID, + projectId: PROJECT_ID, + title: "Thread", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + pullRequests, + createdAt: "2026-08-01T00:00:00.000Z", + updatedAt: "2026-08-20T00:00:00.000Z", + archivedAt: null, + settledOverride: null, + settledAt: null, + latestUserMessageAt: "2026-08-20T00:00:00.000Z", + }; +} + +function makeLink( + number: number, + overrides: Partial & { + readonly headBranch?: string; + readonly baseBranch?: string; + } = {}, +): ThreadPullRequestLink { + const { headBranch, baseBranch, ...rest } = overrides; + return { + host: "github.com", + repository: "t3tools/t3code", + number, + url: `https://github.com/t3tools/t3code/pull/${number}`, + source: "manual", + linkedAt: "2026-08-10T00:00:00.000Z", + snapshot: + headBranch === undefined + ? null + : { + state: "open", + title: `PR ${number}`, + headBranch, + baseBranch: baseBranch ?? "main", + isDraft: false, + updatedAt: null, + syncedAt: "2026-08-27T00:00:00.000Z", + }, + stack: null, + ...rest, + }; +} + +interface HarnessOptions { + readonly thread?: PullRequestTestThread | null; + readonly project?: OrchestrationProjectShell | null; + readonly readFailure?: PullRequestService.PullRequestError; + readonly readState?: PullRequestSummary["state"]; +} + +const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* ( + options: HarnessOptions = {}, +) { + const commands = yield* Ref.make>([]); + const thread = options.thread === undefined ? makeThread([]) : options.thread; + const project = options.project === undefined ? makeProject() : options.project; + const dependencies = Layer.mergeAll( + Layer.mock(ProjectService.ProjectService)({ + getShell: () => Effect.succeed(Option.fromNullishOr(project)), + }), + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadShell: (id) => + Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null), + dispatch: (command) => + Ref.update(commands, (recorded) => [...recorded, command]).pipe( + Effect.as({ sequence: 1, storedEvents: [] }), + ), + }), + Layer.mock(PullRequestService.PullRequestService)({ + summary: (input) => + options.readFailure !== undefined + ? Effect.fail(options.readFailure) + : Effect.succeed({ + ...input, + provider: SourceControlProviderKind.make("github"), + title: "Pull request", + url: `https://github.com/${input.repository}/pull/${input.number}`, + state: options.readState ?? "open", + headBranch: "feature", + baseBranch: "main", + updatedAt: "2026-08-20T00:00:00.000Z", + }), + }), + Layer.succeed(SecureRandom.SecureRandom, testCrypto), + ); + const service = yield* PullRequestWatchService.PullRequestWatchService.pipe( + Effect.provide(PullRequestWatchService.layer.pipe(Layer.provide(dependencies))), + ); + return { + commands, + setWatching: (watching: boolean, target: PullRequestTarget) => + service.setWatching({ threadId: THREAD_ID, target, watching }), + }; +}); + +describe("PullRequestWatchService", () => { + it.effect("links an unlinked watch even while the host has a transient read failure", () => + Effect.gen(function* () { + for (const options of [ + {}, + { + readFailure: new PullRequestOperationError({ + operation: "summary", + detail: "The host is temporarily unavailable.", + }), + }, + ]) { + const harness = yield* makeHarness(options); + const result = yield* harness.setWatching(true, { + url: "https://github.com/t3tools/t3code/pull/9", + }); + expect(result).toMatchObject({ number: 9, wasWatching: false }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { + type: "thread.pull-request.watch", + number: 9, + watching: true, + link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" }, + }, + ]); + } + }), + ); + + it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () => + Effect.gen(function* () { + const missing = new PullRequestUnavailableError({ + reason: "cli-missing", + provider: SourceControlProviderKind.make("gitlab"), + requirement: "Install glab on the T3 server's PATH.", + }); + const harness = yield* makeHarness({ readFailure: missing }); + const target = { url: "https://gitlab.example.com/team/project/-/merge_requests/42" }; + const error = yield* harness.setWatching(true, target).pipe(Effect.flip); + expect(error).toEqual(missing); + expect(yield* Ref.get(harness.commands)).toEqual([]); + + yield* harness.setWatching(false, target); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.watch", watching: false }, + ]); + }), + ); + + it.effect("rejects merged PRs and keeps an active watch usable without hosting access", () => + Effect.gen(function* () { + const freshMerged = yield* makeHarness({ readState: "merged" }); + const freshError = yield* freshMerged + .setWatching(true, { repository: "t3tools/t3code", number: 1 }) + .pipe(Effect.flip); + expect(freshError).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" }); + expect(yield* Ref.get(freshMerged.commands)).toEqual([]); + + const watch = { + startedAt: "2026-08-20T00:00:00.000Z", + headSha: null, + failedChecks: [], + passed: false, + passedChecks: [], + remarksThrough: "2026-08-20T00:00:00.000Z", + remarkIds: [], + conflicting: false, + wakes: 0, + }; + const merged = makeLink(1, { headBranch: "done" }); + const harness = yield* makeHarness({ + readFailure: new PullRequestUnavailableError({ reason: "cli-missing" }), + thread: makeThread([ + { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } }, + makeLink(2, { headBranch: "idle" }), + makeLink(3, { headBranch: "watched", watch }), + ]), + }); + const error = yield* harness + .setWatching(true, { repository: "t3tools/t3code", number: 1 }) + .pipe(Effect.flip); + expect(error).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" }); + expect( + yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 3 }), + ).toMatchObject({ watching: true, wasWatching: true }); + expect( + yield* harness.setWatching(false, { repository: "t3tools/t3code", number: 3 }), + ).toMatchObject({ wasWatching: true }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.watch", number: 3, watching: true }, + { type: "thread.pull-request.watch", number: 3, watching: false }, + ]); + }), + ); + + it.effect("watches a pull request saved as closed, since it may have reopened", () => + Effect.gen(function* () { + const closed = makeLink(1, { headBranch: "closed" }); + const harness = yield* makeHarness({ + readState: "closed", + thread: makeThread([ + { ...closed, snapshot: closed.snapshot && { ...closed.snapshot, state: "closed" } }, + ]), + }); + yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 1 }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.watch", number: 1, watching: true }, + ]); + }), + ); + + it.effect("refuses a watch from a subagent thread, whose parent owns the pull request", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + thread: { + ...makeThread([makeLink(1, { headBranch: "feature" })]), + lineage: { + rootThreadId: ThreadId.make("parent"), + parentThreadId: ThreadId.make("parent"), + relationshipToParent: "subagent", + }, + }, + }); + const error = yield* harness + .setWatching(true, { repository: "t3tools/t3code", number: 1 }) + .pipe(Effect.flip); + expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" }); + expect(yield* Ref.get(harness.commands)).toEqual([]); + }), + ); +}); diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts new file mode 100644 index 0000000000..6ed736075c --- /dev/null +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -0,0 +1,180 @@ +import { + CommandId, + ThreadId, + type OrchestrationV2ThreadShell, + type PullRequestUnavailableError, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "./PullRequestService.ts"; +import { + resolveTarget, + type PullRequestTarget, + type PullRequestTargetError, + type ResolvedTarget, +} from "./pullRequestTarget.ts"; +import { + threadPullRequestKeysEqual, + threadPullRequestsOf, +} from "../sourceControl/threadPullRequests.ts"; + +export class PullRequestWatchFailedError extends Schema.TaggedError()( + "PullRequestWatchFailedError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not change whether the pull request is watched."; + } +} + +export class PullRequestNotOpenError extends Schema.TaggedError()( + "PullRequestNotOpenError", + { state: Schema.String }, +) { + override get message(): string { + return `The pull request is ${this.state}, so there is nothing to watch.`; + } +} + +export class PullRequestWatchFromSubagentError extends Schema.TaggedError()( + "PullRequestWatchFromSubagentError", + {}, +) { + override get message(): string { + return "This thread is a subagent, so it cannot watch pull requests. Its parent thread owns the pull request: finish your task and report back instead."; + } +} + +export class PullRequestWatchThreadNotFoundError extends Schema.TaggedError()( + "PullRequestWatchThreadNotFoundError", + { threadId: ThreadId }, +) { + override get message(): string { + return `Thread ${this.threadId} was not found.`; + } +} + +export class PullRequestWatchService extends Context.Service< + PullRequestWatchService, + { + readonly setWatching: (input: { + readonly threadId: ThreadId; + readonly target: PullRequestTarget; + readonly watching: boolean; + }) => Effect.Effect< + ResolvedTarget & { readonly watching: boolean; readonly wasWatching: boolean }, + | PullRequestWatchFailedError + | PullRequestNotOpenError + | PullRequestWatchFromSubagentError + | PullRequestWatchThreadNotFoundError + | PullRequestTargetError + | PullRequestUnavailableError + >; + } +>()("t3/pullRequest/PullRequestWatchService") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projects = yield* ProjectService.ProjectService; + const pullRequests = yield* PullRequestService.PullRequestService; + const random = yield* SecureRandom.SecureRandom; + + const requireThread = Effect.fn("PullRequestWatchService.requireThread")(function* ( + threadId: ThreadId, + ) { + const thread = yield* engine + .getThreadShell(threadId) + .pipe(Effect.mapError((cause) => new PullRequestWatchFailedError({ cause }))); + if (thread === null || thread.deletedAt !== null) { + return yield* new PullRequestWatchThreadNotFoundError({ threadId }); + } + return thread; + }); + + // Keep the registration span stable across the service extraction. + const setWatching = Effect.fn("PullRequestsToolkit.setWatching")(function* (input: { + readonly threadId: ThreadId; + readonly target: PullRequestTarget; + readonly watching: boolean; + }) { + const { watching } = input; + const thread = yield* requireThread(input.threadId); + const project = yield* projects.getShell(thread.projectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })), + ); + const target = yield* resolveTarget(input.target, project); + const watchedLink = (shell: OrchestrationV2ThreadShell) => + threadPullRequestsOf(shell).find( + (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target), + ); + if (watching && thread.lineage.relationshipToParent === "subagent") { + return yield* new PullRequestWatchFromSubagentError(); + } + const before = watchedLink(thread); + if (watching && before?.snapshot?.state === "merged") { + return yield* new PullRequestNotOpenError({ state: "merged" }); + } + if (watching && before?.watch === undefined) { + yield* pullRequests + .summary( + { + projectId: thread.projectId, + host: target.host, + repository: target.repository, + number: target.number, + allowStale: false, + }, + { recoverTransientFailure: false, bypassCache: true }, + ) + .pipe( + Effect.flatMap((summary) => + summary.state === "merged" + ? Effect.fail(new PullRequestNotOpenError({ state: "merged" })) + : Effect.void, + ), + Effect.catchTags({ + // Host and transport errors can recover while the watch is active. + PullRequestOperationError: () => Effect.void, + }), + ); + } + const uuid = yield* random.uuidV4().pipe(Effect.orDie); + yield* engine + .dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`server:mcp-pr-watch:${thread.id}:${uuid}`), + threadId: thread.id, + host: target.host, + repository: target.repository, + number: target.number, + watching, + ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}), + }) + .pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.fail(new PullRequestWatchFailedError({ cause })), + ), + ); + const after = yield* requireThread(thread.id); + return { + ...target, + watching: watchedLink(after)?.watch !== undefined, + wasWatching: before?.watch !== undefined, + }; + }); + + return PullRequestWatchService.of({ setWatching }); +}); + +export const layer = Layer.effect(PullRequestWatchService, make); diff --git a/apps/server/src/pullRequest/linkedThreads.test.ts b/apps/server/src/pullRequest/linkedThreads.test.ts index 8992a32ea1..2dac788641 100644 --- a/apps/server/src/pullRequest/linkedThreads.test.ts +++ b/apps/server/src/pullRequest/linkedThreads.test.ts @@ -1,10 +1,18 @@ +import { + ProjectId, + ThreadId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type ThreadPullRequestLink, +} from "@t3tools/contracts"; import { assert, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; -import { listLinkedPullRequestThreads } from "./linkedThreads.ts"; +import { listLinkedPullRequestThreads, makeLinkedThreadsChangeDetector } from "./linkedThreads.ts"; const encodePayload = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); @@ -209,3 +217,132 @@ it.effect( ); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it("signals linked-thread changes only when a linked answer could change", () => { + const now = DateTime.makeUnsafe("2026-11-12T00:00:00.000Z"); + const threadId = ThreadId.make("thread-a"); + const link: ThreadPullRequestLink = { + host: "github.com", + repository: "acme/web", + number: 7, + url: "https://github.com/acme/web/pull/7", + source: "agent", + linkedAt: "2026-11-12T00:00:00.000Z", + snapshot: null, + stack: null, + }; + const base = { + id: threadId, + projectId: ProjectId.make("project-a"), + title: "Thread A", + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + updatedAt: now, + } as unknown as OrchestrationV2AppThread; + const event = ( + type: OrchestrationV2DomainEvent["type"], + payload: Partial, + ) => ({ type, threadId, payload: { ...base, ...payload } }) as OrchestrationV2DomainEvent; + const changed = makeLinkedThreadsChangeDetector(); + + expect( + [ + event("thread.metadata-updated", { title: "Unlinked rename" }), + event("thread.pull-request-synced", { pullRequests: [link] }), + event("thread.pull-request-synced", { + pullRequests: [{ ...link, watch: { since: "2026-11-12T00:00:00.000Z" } as never }], + }), + event("thread.visited", { pullRequests: [link] }), + event("thread.pinned", { pullRequests: [link], settledAt: now }), + { type: "thread.pull-request-link-updated", threadId, payload: link } as never, + event("thread.metadata-updated", { pullRequests: [link], title: "Renamed" }), + event("thread.archived", { pullRequests: [link], title: "Renamed", archivedAt: now }), + event("thread.pull-request-synced", { + pullRequests: [{ ...link, source: "stack-dismissed" }], + title: "Renamed", + archivedAt: now, + }), + event("thread.deleted", { pullRequests: [], deletedAt: now }), + ].map(changed), + ).toEqual([ + "changed", + "changed", + null, + null, + "changed", + null, + "changed", + "changed", + "changed", + null, + ]); + + const afterRestart = makeLinkedThreadsChangeDetector(); + expect(afterRestart(event("thread.created", { title: "New" }))).toBe(null); + expect( + makeLinkedThreadsChangeDetector()( + event("thread.deleted", { pullRequests: [], deletedAt: now }), + ), + ).toBe("changed"); +}); + +it("signals when activity reorders the threads linked to a pull request", () => { + const at = (second: number) => DateTime.makeUnsafe(`2026-11-12T00:00:0${second}.000Z`); + const link = { + host: "github.com", + repository: "acme/web", + number: 7, + url: "https://github.com/acme/web/pull/7", + source: "agent", + }; + const thread = (id: string, second: number, pullRequests: ReadonlyArray = [link]) => + ({ + type: "thread.pull-request-synced", + threadId: ThreadId.make(id), + payload: { + id: ThreadId.make(id), + projectId: ProjectId.make("project-a"), + title: id, + lineage: { rootThreadId: ThreadId.make(id) }, + pullRequests, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + updatedAt: at(second), + }, + }) as unknown as OrchestrationV2DomainEvent; + const activity = (id: string, second: number) => + ({ + type: "message.updated", + threadId: ThreadId.make(id), + occurredAt: at(second), + }) as unknown as OrchestrationV2DomainEvent; + const changed = makeLinkedThreadsChangeDetector(); + changed(thread("a", 1)); + changed(thread("b", 2)); + + expect( + [ + { ...thread("a", 3), type: "thread.pinned" } as OrchestrationV2DomainEvent, + activity("a", 4), + activity("b", 5), + activity("b", 5), + // Seen since startup without links, so its activity can't reorder an answer. + thread("unlinked", 5, []), + activity("unlinked", 6), + // Not seen since startup, so it may be linked from before the restart. + activity("persisted", 6), + ].map(changed), + ).toEqual(["reordered", "reordered", "reordered", null, "changed", null, "reordered"]); + + // Other threads linked to the pull request may have had no event since the restart. + const afterRestart = makeLinkedThreadsChangeDetector(); + afterRestart(thread("a", 2)); + expect( + afterRestart({ ...thread("a", 6), type: "thread.pinned" } as OrchestrationV2DomainEvent), + ).toBe("reordered"); +}); diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.ts index 87ffae525e..1fb6b5f5df 100644 --- a/apps/server/src/pullRequest/linkedThreads.ts +++ b/apps/server/src/pullRequest/linkedThreads.ts @@ -1,12 +1,18 @@ import { normalizeThreadPullRequestKey, + threadPullRequestKeyOf, threadPullRequestKeysEqual, + visibleThreadPullRequests, } from "../sourceControl/threadPullRequests.ts"; import { PullRequestLinkedThreadsResult, PullRequestOperationError, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type ThreadId, type ThreadPullRequestKey, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Schema from "effect/Schema"; @@ -66,3 +72,67 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre }), ), ); + +// Mirrors the rows and filters of `listLinkedPullRequestThreads`. +function linkedKeys(thread: OrchestrationV2AppThread): ReadonlyArray { + if (thread.deletedAt !== null || thread.lineage.sideChat === true) return []; + return visibleThreadPullRequests(thread.pullRequests ?? []) + .map(threadPullRequestKeyOf) + .toSorted(); +} + +function linkedThreadsView( + thread: OrchestrationV2AppThread, + keys: ReadonlyArray, +): string | null { + if (keys.length === 0) return null; + const settled = thread.settledAt !== null || thread.settledOverride === "settled"; + return JSON.stringify([ + keys, + thread.title, + thread.projectId, + thread.archivedAt !== null, + settled, + ]); +} + +/** + * Tells how a domain event changed `pullRequests.linkedThreads` answers, so readers can refresh on + * change instead of polling. `reordered` means activity on a linked thread, or on one whose links + * are unknown since a restart, which can reorder answers. A thread's first full event after a + * restart counts as a change, since its earlier links are unknown. + */ +export function makeLinkedThreadsChangeDetector() { + const views = new Map(); + // Last activity of each thread with visible links. + const activeAt = new Map(); + const active = (threadId: ThreadId, at: DateTime.Utc): boolean => { + const previous = activeAt.get(threadId); + if (previous === undefined) return false; + const millis = DateTime.toEpochMillis(at); + if (millis <= previous) return false; + activeAt.set(threadId, millis); + return true; + }; + return (event: OrchestrationV2DomainEvent): "changed" | "reordered" | null => { + // The projection stamps every non-thread event as the thread's activity. A thread not seen + // since startup may be linked already, since history is not replayed. + if (!event.type.startsWith("thread.")) { + if (!views.has(event.threadId)) return "reordered"; + return active(event.threadId, event.occurredAt) ? "reordered" : null; + } + if (!("lineage" in event.payload)) return null; + const thread = event.payload; + const view = linkedThreadsView(thread, linkedKeys(thread)); + const known = views.has(event.threadId) || event.type === "thread.created"; + const previous = views.get(event.threadId) ?? null; + if (event.type === "thread.deleted") views.delete(event.threadId); + else views.set(event.threadId, view); + if (view === null) activeAt.delete(event.threadId); + if (!known || view !== previous) { + if (view !== null) activeAt.set(event.threadId, DateTime.toEpochMillis(thread.updatedAt)); + return "changed"; + } + return active(event.threadId, thread.updatedAt) ? "reordered" : null; + }; +} diff --git a/apps/server/src/pullRequest/pullRequestTarget.ts b/apps/server/src/pullRequest/pullRequestTarget.ts new file mode 100644 index 0000000000..4520b0523a --- /dev/null +++ b/apps/server/src/pullRequest/pullRequestTarget.ts @@ -0,0 +1,123 @@ +import type { OrchestrationProjectShell, SourceControlProviderKind } from "@t3tools/contracts"; +import { canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-definitions/registry"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts"; + +export interface PullRequestTarget { + readonly url?: string | undefined; + readonly repository?: string | undefined; + readonly number?: number | undefined; + readonly host?: string | undefined; +} + +export class PullRequestUrlInvalidError extends Schema.TaggedError()( + "PullRequestUrlInvalidError", + {}, +) { + override get message(): string { + return "This is not a recognised pull request URL. Pass repository and number instead."; + } +} + +export class PullRequestTargetIncompleteError extends Schema.TaggedError()( + "PullRequestTargetIncompleteError", + {}, +) { + override get message(): string { + return "Pass either url, or both repository and number."; + } +} + +export class PullRequestHostRequiredError extends Schema.TaggedError()( + "PullRequestHostRequiredError", + {}, +) { + override get message(): string { + return "This thread's project has no recognised remote. Pass host or url."; + } +} + +export class PullRequestUrlUnavailableError extends Schema.TaggedError()( + "PullRequestUrlUnavailableError", + {}, +) { + override get message(): string { + return "This thread's project is on a host with no known pull request URL shape. Pass url."; + } +} + +export type PullRequestTargetError = + | PullRequestUrlInvalidError + | PullRequestTargetIncompleteError + | PullRequestHostRequiredError + | PullRequestUrlUnavailableError; + +export interface ResolvedTarget { + readonly host: string; + readonly repository: string; + readonly number: number; + readonly url: string; +} + +function projectHostAndProvider(project: OrchestrationProjectShell | undefined): { + readonly host: string | null; + readonly kind: SourceControlProviderKind | null; +} { + const identity = project?.repositoryIdentity; + const kind = identity?.provider ?? null; + if (!identity || kind === null) return { host: null, kind: null }; + return { + host: sourceControlDefinitions.changeRequestHost(identity, kind), + kind, + }; +} + +export const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* ( + input: PullRequestTarget, + project: OrchestrationProjectShell | undefined, +) { + if (input.url !== undefined) { + const parsed = sourceControlDefinitions.parseChangeRequestUrl(input.url)?.link; + if (parsed === undefined) { + return yield* new PullRequestUrlInvalidError({}); + } + return { + ...normalizeThreadPullRequestKey(parsed), + url: canonicalizeGitCafePullRequestUrl(input.url), + } satisfies ResolvedTarget; + } + if (input.repository === undefined || input.number === undefined) { + return yield* new PullRequestTargetIncompleteError({}); + } + const projectHost = projectHostAndProvider(project); + const host = (input.host ?? projectHost.host)?.toLowerCase(); + if (host === undefined) { + return yield* new PullRequestHostRequiredError({}); + } + const repository = input.repository.toLowerCase(); + // Without a URL, a public forge host says what shape its change request URLs take; + // any other host is taken to run the project's own forge. + const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind; + const kind = + sourceControlDefinitions.findByPublicHost(host)?.kind ?? + (recognizedKind === "gitcafe" ? recognizedKind : projectHost.kind); + const url = + kind === null + ? null + : sourceControlDefinitions.get(kind).changeRequestUrl({ + host, + repository, + number: input.number, + remoteUrl: project?.repositoryIdentity?.locator.remoteUrl, + }); + if (url === null) { + return yield* new PullRequestUrlUnavailableError({}); + } + return { + ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }), + url: canonicalizeGitCafePullRequestUrl(url), + } satisfies ResolvedTarget; +}); diff --git a/apps/server/src/pullRequest/pullRequestViewedFiles.ts b/apps/server/src/pullRequest/pullRequestViewedFiles.ts index 596808eb46..7558e8b6a1 100644 --- a/apps/server/src/pullRequest/pullRequestViewedFiles.ts +++ b/apps/server/src/pullRequest/pullRequestViewedFiles.ts @@ -30,7 +30,7 @@ const MAX_FILE_REVISION_PATHS = 1_000; interface FileRevisionsDependencies { readonly runFork: (effect: Effect.Effect) => unknown; readonly refEpoch: (ref: PullRequestRef) => number; - readonly fileRevisionsEpoch: () => number; + readonly fileRevisionsEpoch: (ref: PullRequestRef) => string; readonly toPullRequestError: ( operation: string, ) => (error: PullRequestProviderError) => PullRequestError; @@ -50,7 +50,7 @@ const makeFileRevisions = (dependencies: FileRevisionsDependencies) => { const fileRevisionsKey = (project: SupportedProject, ref: PullRequestRef) => [ refEpoch({ ...ref, host: project.host, repository: project.repository }), - fileRevisionsEpoch(), + fileRevisionsEpoch({ ...ref, host: project.host, repository: project.repository }), ref.projectId, project.repository.trim().toLowerCase(), ref.number, @@ -260,7 +260,9 @@ export const make = (dependencies: Dependencies) => { input: PullRequestSetFilesViewedInput, ): Effect.fn.Return { const viewer = yield* requiredViewerOf(project, "setFilesViewed"); - const cleared = input.files.filter((file) => file.viewed).map((file) => file.path); + const cleared = input.files + .filter((file) => file.viewed && file.revision === undefined) + .map((file) => file.path); const revisions = cleared.length === 0 ? null @@ -276,10 +278,10 @@ export const make = (dependencies: Dependencies) => { yield* filesViewedStore .set({ ...filesViewedScope(project, input.number, viewer), - // Missing paths have null baselines; empty revision means confirmed deletion. + // Shown revisions win over the head; missing paths have null baselines; empty means deleted. files: input.files.map((file) => ({ path: file.path, - revision: revisions?.get(file.path) ?? null, + revision: file.revision ?? revisions?.get(file.path) ?? null, viewed: file.viewed, })), viewedAt, diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts index 7d9de87ecf..ca77c9e262 100644 --- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts +++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts @@ -187,6 +187,8 @@ export class DesktopTelemetryReceiver extends Context.Service< readonly setDiagnosticsDemand: ( enabled: boolean, ) => Effect.Effect; + /** Tells the desktop parent that the server accepts requests, so it can skip readiness polling. */ + readonly announceServerReady: Effect.Effect; readonly requestDesktopUpdate: ( requestId: string, trackSwitch?: DesktopTrackSwitch, @@ -717,6 +719,9 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make") health: Ref.get(health), subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)), setDiagnosticsDemand, + announceServerReady: sendControlMessage({ version: 1, type: "serverReady" }).pipe( + Effect.withSpan("DesktopTelemetryReceiver.announceServerReady"), + ), requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")( function (requestId, trackSwitch) { return sendControlMessage({ @@ -787,6 +792,7 @@ export const layerTest = ( setDiagnosticsDemand: Effect.fn("DesktopTelemetryReceiver.setDiagnosticsDemand")(function () { return Effect.void; }), + announceServerReady: Effect.void, requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(function () { return Effect.void; }), diff --git a/apps/server/src/resourceTelemetry/HostResources.test.ts b/apps/server/src/resourceTelemetry/HostResources.test.ts new file mode 100644 index 0000000000..3e5c636c5d --- /dev/null +++ b/apps/server/src/resourceTelemetry/HostResources.test.ts @@ -0,0 +1,227 @@ +import { assert, describe, it } from "@effect/vitest"; +import type * as NodeOS from "node:os"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as PlatformError from "effect/PlatformError"; +import { ChildProcessSpawner } from "effect/process"; +import * as TestClock from "effect/testing/TestClock"; +import { vi } from "vite-plus/test"; + +import * as HostResources from "./HostResources.ts"; + +// An 8-CPU host; every cpus() call advances each CPU by 100 ms at `host.busy` utilization. +const host = vi.hoisted(() => ({ busy: 0, reads: 0 })); +vi.mock("node:os", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + totalmem: () => 4 * 1024 ** 3, + cpus: () => { + const elapsed = 100 * host.reads++; + const times = { + user: elapsed * host.busy, + nice: 0, + sys: 0, + idle: elapsed * (1 - host.busy), + irq: 0, + }; + return Array.from({ length: 8 }, () => ({ model: "test", speed: 1, times })); + }, + }; +}); +const setup = (busy = 0) => { + host.busy = busy; + host.reads = 0; +}; + +const GiB = 1024 ** 3; +const MiB = 1024 ** 2; +const cgroup = "/sys/fs/cgroup/t3.slice/server.scope"; +const unlimitedCgroup = { + "/proc/self/cgroup": ["0::/t3.slice/server.scope\n"], + "/proc/meminfo": [`MemTotal: ${4 * 1024 * 1024} kB\nMemAvailable: ${2 * 1024 * 1024} kB\n`], + [`${cgroup}/cpu.max`]: ["max 100000\n"], + [`${cgroup}/cpu.stat`]: ["usage_usec 5000000\n"], + [`${cgroup}/memory.max`]: ["max\n"], + [`${cgroup}/memory.current`]: [`${600 * MiB}\n`], + [`${cgroup}/memory.stat`]: [`anon ${450 * MiB}\ninactive_file ${100 * MiB}\n`], +}; + +// Each path serves its values in order and repeats the last one. +const linuxHost = (files: Record>) => { + const reads = new Map(); + return HostResources.layer.pipe( + Layer.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + readFileString: (path) => { + const values = files[path]; + if (!values) { + return Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: path, + }), + ); + } + const index = reads.get(path) ?? 0; + reads.set(path, index + 1); + return Effect.succeed(values[Math.min(index, values.length - 1)]!); + }, + }), + Layer.succeed(HostProcess.Platform, "linux"), + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.die("HostResources spawned on linux")), + ), + ), + ), + ); +}; + +const read = Effect.gen(function* () { + const host = yield* HostResources.HostResources; + const fiber = yield* Effect.forkChild(host.read); + yield* TestClock.adjust("200 millis"); + return yield* Fiber.join(fiber); +}); + +describe("HostResources.layer", () => { + it.effect("reports the CPU quota and usage of the server's cgroup", () => + Effect.gen(function* () { + setup(); + const snapshot = yield* read; + + // One CPU of quota, 150 ms of it used during the 200 ms sample. + assert.strictEqual(snapshot.cpuCount, 1); + assert.strictEqual(snapshot.cpuUtilization, 0.75); + }).pipe( + Effect.provide( + linuxHost({ + ...unlimitedCgroup, + [`${cgroup}/cpu.max`]: ["100000 100000\n"], + [`${cgroup}/cpu.stat`]: [ + "usage_usec 5000000\nuser_usec 4000000\nsystem_usec 1000000\n", + "usage_usec 5150000\nuser_usec 4100000\nsystem_usec 1050000\n", + ], + }), + ), + ), + ); + + it.effect("reports memory against the server cgroup's memory.max", () => + Effect.gen(function* () { + setup(); + const snapshot = yield* read; + + assert.strictEqual(snapshot.totalMemoryBytes, GiB); + // 600 MiB charged, of which 100 MiB is reclaimable page cache. + assert.strictEqual(snapshot.availableMemoryBytes, GiB - 500 * MiB); + }).pipe( + Effect.provide( + linuxHost({ + ...unlimitedCgroup, + [`${cgroup}/memory.max`]: [`${GiB}\n`], + }), + ), + ), + ); + + it.effect("counts a busy host against an idle, quota-limited server cgroup", () => + Effect.gen(function* () { + // Agents in sibling cgroups keep the host 90% busy; the server's own cgroup is idle. + setup(0.9); + const snapshot = yield* read; + + assert.strictEqual(snapshot.cpuCount, 2); + // Only 0.8 of 8 host CPUs are free, which is 60% of the 2-CPU quota in use. + assert.closeTo(snapshot.cpuUtilization ?? Number.NaN, 0.6, 1e-9); + }).pipe( + Effect.provide( + linuxHost({ + ...unlimitedCgroup, + [`${cgroup}/cpu.max`]: ["200000 100000\n"], + }), + ), + ), + ); + + it.effect("samples the CPUs the server is pinned to by id, not by os.cpus() index", () => + Effect.gen(function* () { + setup(); + const snapshot = yield* read; + + assert.strictEqual(snapshot.cpuCount, 1); + assert.strictEqual(snapshot.cpuUtilization, 1); + }).pipe( + Effect.provide( + linuxHost({ + ...unlimitedCgroup, + "/proc/self/status": ["Name:\tnode\nCpus_allowed_list:\t4\n"], + // CPU 1 is offline; the server's CPU 4 is saturated, everything else is idle. + "/proc/stat": [0, 100].map((elapsed) => + [0, 2, 3, 4, 5, 6, 7] + .map((id) => + id === 4 + ? `cpu${id} ${elapsed} 0 0 0 0 0 0 0` + : `cpu${id} 0 0 0 ${elapsed} 0 0 0 0`, + ) + .join("\n"), + ), + }), + ), + ), + ); + + it.effect("keeps host memory when the cgroup's memory.current is unreadable", () => + Effect.gen(function* () { + setup(); + const snapshot = yield* read; + + assert.strictEqual(snapshot.totalMemoryBytes, 4 * GiB); + assert.strictEqual(snapshot.availableMemoryBytes, 2 * GiB); + }).pipe( + Effect.provide( + linuxHost({ + ...unlimitedCgroup, + [`${cgroup}/memory.max`]: [`${GiB}\n`], + [`${cgroup}/memory.current`]: [""], + }), + ), + ), + ); + + it.effect("keeps host values when the cgroup has no limits", () => + Effect.gen(function* () { + setup(0.25); + const snapshot = yield* read; + + assert.strictEqual(snapshot.cpuCount, 8); + assert.closeTo(snapshot.cpuUtilization ?? Number.NaN, 0.25, 1e-9); + assert.strictEqual(snapshot.availableMemoryBytes, 2 * GiB); + }).pipe(Effect.provide(linuxHost(unlimitedCgroup))), + ); + + it.effect("falls back to host load when the cgroup's cpu.stat is unreadable", () => + Effect.gen(function* () { + setup(0.9); + const snapshot = yield* read; + + assert.strictEqual(snapshot.cpuCount, 2); + assert.closeTo(snapshot.cpuUtilization ?? Number.NaN, 0.6, 1e-9); + }).pipe( + Effect.provide( + linuxHost({ + ...unlimitedCgroup, + [`${cgroup}/cpu.max`]: ["200000 100000\n"], + [`${cgroup}/cpu.stat`]: [""], + }), + ), + ), + ); +}); diff --git a/apps/server/src/resourceTelemetry/HostResources.ts b/apps/server/src/resourceTelemetry/HostResources.ts index 4788689046..85c985f5a3 100644 --- a/apps/server/src/resourceTelemetry/HostResources.ts +++ b/apps/server/src/resourceTelemetry/HostResources.ts @@ -2,6 +2,7 @@ import * as NodeOS from "node:os"; import type { HostResourcesSnapshot } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cache from "effect/Cache"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -14,6 +15,33 @@ export class HostResources extends Context.Service< { readonly read: Effect.Effect } >()("t3/resourceTelemetry/HostResources") {} +// Linux CPU list syntax, as in Cpus_allowed_list: "0-3,8,10-11". +function parseCpuList(list: string): ReadonlySet | null { + const cpus = new Set(); + for (const range of list.split(",")) { + const match = /^(\d+)(?:-(\d+))?$/.exec(range.trim()); + if (!match) return null; + for (let cpu = Number(match[1]); cpu <= Number(match[2] ?? match[1]); cpu++) cpus.add(cpu); + } + return cpus; +} + +// os.cpus() compacts online CPUs, so its indices are not CPU ids; /proc/stat lines are keyed. +function pinnedCpu(stat: string, allowed: ReadonlySet) { + const cpu = { idle: 0, total: 0, count: 0 }; + for (const [, id, fields] of stat.matchAll(/^cpu(\d+) (.+)$/gm)) { + if (!allowed.has(Number(id))) continue; + const counters = (fields ?? "").trim().split(/\s+/).map(Number); + const at = (index: number) => counters[index] ?? 0; + // user nice system idle iowait irq softirq steal + const idle = at(3) + at(4); + cpu.idle += idle; + cpu.total += idle + at(0) + at(1) + at(2) + at(5) + at(6) + at(7); + cpu.count++; + } + return cpu.count > 0 ? cpu : null; +} + function readCpu() { const cpus = NodeOS.cpus(); const cpu = cpus.reduce( @@ -37,28 +65,84 @@ function darwinAvailableMemory(output: string): number | null { return Number.isSafeInteger(available) && Number(pageSize) > 0 ? available : null; } +function cgroupNumber(text: string, pattern: RegExp): number | null { + const value = pattern.exec(text)?.[1]; + return value === undefined ? null : Number(value); +} + const make = Effect.fn("makeHostResources")(function* () { const fs = yield* FileSystem.FileSystem; const platform = yield* HostProcess.Platform; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const readFile = (path: string) => fs.readFileString(path).pipe(Effect.orElseSucceed(() => "")); + const sample = Effect.fn("HostResources.sample")(function* () { - const previousCpu = readCpu(); + // cgroup v2 only; limits of the server's own cgroup, which is `/` inside a container. + const cgroupPath = + platform === "linux" + ? /^0::(\/.*)$/m.exec(yield* readFile("/proc/self/cgroup"))?.[1] + : undefined; + const cgroup = + cgroupPath === undefined ? null : `/sys/fs/cgroup${cgroupPath.replace(/\/$/, "")}`; + const cpuMax = cgroup + ? /^(\d+) (\d+)$/.exec((yield* readFile(`${cgroup}/cpu.max`)).trim()) + : null; + const readCpuUsage = () => + cpuMax + ? Effect.map(readFile(`${cgroup}/cpu.stat`), (stat) => + cgroupNumber(stat, /^usage_usec (\d+)$/m), + ) + : Effect.succeed(null); + // Affinity (cpuset) pins the server to some CPUs; idle CPUs outside it are of no use. + const allowedCpus = + platform === "linux" + ? parseCpuList( + /^Cpus_allowed_list:\s*(\S+)$/m.exec(yield* readFile("/proc/self/status"))?.[1] ?? "", + ) + : null; + + const sampleCpu = () => + allowedCpus + ? Effect.map(readFile("/proc/stat"), (stat) => pinnedCpu(stat, allowedCpus) ?? readCpu()) + : Effect.sync(readCpu); + + const previousCpu = yield* sampleCpu(); + const previousUsage = yield* readCpuUsage(); + const startedAt = yield* Clock.currentTimeMillis; yield* Effect.sleep("200 millis"); - const cpu = readCpu(); + const cpu = yield* sampleCpu(); + const usage = yield* readCpuUsage(); + const elapsedMicros = ((yield* Clock.currentTimeMillis) - startedAt) * 1000; const totalDelta = cpu.total - previousCpu.total; const idleDelta = cpu.idle - previousCpu.idle; - const cpuUtilization = + let cpuCount = cpu.count; + const hostUtilization = previousCpu.count === cpu.count && totalDelta > 0 && idleDelta >= 0 ? Math.min(1, Math.max(0, 1 - idleDelta / totalDelta)) : null; - const totalMemoryBytes = NodeOS.totalmem(); + let cpuUtilization = hostUtilization; + if (cpuMax) { + const capacity = Math.min(Number(cpuMax[1]) / Number(cpuMax[2]), cpu.count); + cpuCount = Math.max(1, Math.floor(capacity)); + const cgroupIdle = + previousUsage !== null && usage !== null && elapsedMicros > 0 + ? capacity - (usage - previousUsage) / elapsedMicros + : null; + // Agents can run in sibling cgroups (agentScope.ts), so a busy host still counts. + const hostIdle = hostUtilization === null ? null : cpu.count * (1 - hostUtilization); + const idle = + cgroupIdle === null || hostIdle === null + ? (cgroupIdle ?? hostIdle) + : Math.min(cgroupIdle, hostIdle); + cpuUtilization = idle === null ? null : Math.min(1, Math.max(0, 1 - idle / capacity)); + } + + let totalMemoryBytes = NodeOS.totalmem(); // On Windows libuv returns GlobalMemoryStatusEx.ullAvailPhys, including standby memory. let availableMemoryBytes = NodeOS.freemem(); if (platform === "linux") { - const meminfo = yield* fs - .readFileString("/proc/meminfo") - .pipe(Effect.orElseSucceed(() => "")); + const meminfo = yield* readFile("/proc/meminfo"); const available = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(meminfo)?.[1]; if (available) availableMemoryBytes = Number(available) * 1024; } else if (platform === "darwin") { @@ -70,10 +154,28 @@ const make = Effect.fn("makeHostResources")(function* () { ); availableMemoryBytes = darwinAvailableMemory(output) ?? availableMemoryBytes; } + const memoryMax = cgroup + ? cgroupNumber(yield* readFile(`${cgroup}/memory.max`), /^(\d+)$/m) + : null; + const memoryCurrent = + memoryMax === null + ? null + : cgroupNumber(yield* readFile(`${cgroup}/memory.current`), /^(\d+)$/m); + // Without usage, a capped total would read as a near-empty cgroup; keep host values instead. + if (memoryMax !== null && memoryCurrent !== null) { + totalMemoryBytes = Math.min(totalMemoryBytes, memoryMax); + // inactive_file is page cache the kernel reclaims before hitting memory.max. + const stat = yield* readFile(`${cgroup}/memory.stat`); + const reclaimable = cgroupNumber(stat, /^inactive_file (\d+)$/m) ?? 0; + availableMemoryBytes = Math.min( + availableMemoryBytes, + memoryMax - (memoryCurrent - reclaimable), + ); + } return { sampledAt: DateTime.toEpochMillis(yield* DateTime.now), cpuUtilization, - cpuCount: cpu.count, + cpuCount, availableMemoryBytes: Math.min(totalMemoryBytes, Math.max(0, availableMemoryBytes)), totalMemoryBytes, }; diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts index c12e2e44ed..8a3640977d 100644 --- a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts +++ b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts @@ -272,131 +272,127 @@ describe("ResourceTelemetry", () => { ); it.effect("rejects buffered snapshots from an earlier sidecar generation", () => - Effect.scoped( - Effect.gen(function* () { - const startedAt = DateTime.toEpochMillis(yield* DateTime.now); - const stale = nativeSnapshot({ - sequence: 100, - sampledAtUnixMs: startedAt + 1_000, - childCpuTimeMs: 100, - childWriteBytes: 1_000, - }); - const current = nativeSnapshot({ - sequence: 1, - sampledAtUnixMs: startedAt + 2_000, - childCpuTimeMs: 200, - childWriteBytes: 2_000, - }); - const nativeSnapshots = - yield* PubSub.unbounded(); - const layerNative = NativeTelemetryClient.layerTest({ - snapshots: Stream.fromPubSub(nativeSnapshots), - sampleNow: Effect.never, - health: Effect.succeed({ - status: "healthy", - hello: Option.none(), - lastSampleAt: Option.none(), - lastError: Option.none(), - restartCount: 1, - sampleIntervalMs: 1_000, - }), - }); - const layerTelemetry = ResourceTelemetry.layer.pipe( - Layer.provide( - Layer.mergeAll( - layerNative, - DesktopTelemetryReceiver.layerTest(), - ResourceAttribution.layer, - ), + Effect.gen(function* () { + const startedAt = DateTime.toEpochMillis(yield* DateTime.now); + const stale = nativeSnapshot({ + sequence: 100, + sampledAtUnixMs: startedAt + 1_000, + childCpuTimeMs: 100, + childWriteBytes: 1_000, + }); + const current = nativeSnapshot({ + sequence: 1, + sampledAtUnixMs: startedAt + 2_000, + childCpuTimeMs: 200, + childWriteBytes: 2_000, + }); + const nativeSnapshots = + yield* PubSub.unbounded(); + const layerNative = NativeTelemetryClient.layerTest({ + snapshots: Stream.fromPubSub(nativeSnapshots), + sampleNow: Effect.never, + health: Effect.succeed({ + status: "healthy", + hello: Option.none(), + lastSampleAt: Option.none(), + lastError: Option.none(), + restartCount: 1, + sampleIntervalMs: 1_000, + }), + }); + const layerTelemetry = ResourceTelemetry.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerNative, + DesktopTelemetryReceiver.layerTest(), + ResourceAttribution.layer, ), - ); + ), + ); - yield* Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - const subscription = yield* telemetry.subscribe; - const nextSnapshot = yield* Stream.runHead(subscription.changes).pipe(Effect.forkChild); + yield* Effect.gen(function* () { + const telemetry = yield* ResourceTelemetry.ResourceTelemetry; + const subscription = yield* telemetry.subscribe; + const nextSnapshot = yield* Stream.runHead(subscription.changes).pipe(Effect.forkChild); - yield* PubSub.publish(nativeSnapshots, nativeGeneration(stale, 0)); - yield* Effect.yieldNow; - expect((yield* telemetry.latest).health.scannedProcessCount).toBe(0); + yield* PubSub.publish(nativeSnapshots, nativeGeneration(stale, 0)); + yield* Effect.yieldNow; + expect((yield* telemetry.latest).health.scannedProcessCount).toBe(0); - yield* PubSub.publish(nativeSnapshots, nativeGeneration(current, 1)); - const received = yield* Fiber.join(nextSnapshot); + yield* PubSub.publish(nativeSnapshots, nativeGeneration(current, 1)); + const received = yield* Fiber.join(nextSnapshot); - expect(Option.isSome(received)).toBe(true); - expect(DateTime.toEpochMillis(Option.getOrThrow(received).readAt)).toBe( - current.sampledAtUnixMs, - ); - }).pipe(Effect.provide(layerTelemetry)); - }), - ), + expect(Option.isSome(received)).toBe(true); + expect(DateTime.toEpochMillis(Option.getOrThrow(received).readAt)).toBe( + current.sampledAtUnixMs, + ); + }).pipe(Effect.provide(layerTelemetry)); + }), ); it.effect("atomically subscribes while a desktop update is being rebuilt", () => - Effect.scoped( - Effect.gen(function* () { - const startedAt = DateTime.toEpochMillis(yield* DateTime.now); - const nextDesktopSnapshot = desktopSnapshot(startedAt + 1_000); - const desktopChanges = yield* PubSub.unbounded(); - const rebuildStarted = yield* Deferred.make(); - const finishRebuild = yield* Deferred.make(); - const attributionReads = yield* Ref.make(0); - const layerAttribution = Layer.succeed( - ResourceAttribution.ResourceAttribution, - ResourceAttribution.ResourceAttribution.of({ - record: () => Effect.void, - snapshot: Ref.updateAndGet(attributionReads, (count) => count + 1).pipe( - Effect.flatMap((count) => - count === 1 - ? Effect.void - : Deferred.succeed(rebuildStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishRebuild)), - ), - ), - Effect.andThen( - Effect.succeed({ - readAt: DateTime.makeUnsafe(startedAt), - entries: [], - }), - ), + Effect.gen(function* () { + const startedAt = DateTime.toEpochMillis(yield* DateTime.now); + const nextDesktopSnapshot = desktopSnapshot(startedAt + 1_000); + const desktopChanges = yield* PubSub.unbounded(); + const rebuildStarted = yield* Deferred.make(); + const finishRebuild = yield* Deferred.make(); + const attributionReads = yield* Ref.make(0); + const layerAttribution = Layer.succeed( + ResourceAttribution.ResourceAttribution, + ResourceAttribution.ResourceAttribution.of({ + record: () => Effect.void, + snapshot: Ref.updateAndGet(attributionReads, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 1 + ? Effect.void + : Deferred.succeed(rebuildStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishRebuild)), + ), ), - }), - ); - const layerNative = NativeTelemetryClient.layerTest({ - sampleNow: Effect.never, - health: Effect.succeed({ - status: "healthy", - hello: Option.none(), - lastSampleAt: Option.none(), - lastError: Option.none(), - restartCount: 0, - sampleIntervalMs: 1_000, - }), - }); - const layerDesktop = DesktopTelemetryReceiver.layerTest({ - changes: Stream.fromPubSub(desktopChanges), - }); - const layerTelemetry = ResourceTelemetry.layer.pipe( - Layer.provide(Layer.mergeAll(layerNative, layerDesktop, layerAttribution)), - ); + Effect.andThen( + Effect.succeed({ + readAt: DateTime.makeUnsafe(startedAt), + entries: [], + }), + ), + ), + }), + ); + const layerNative = NativeTelemetryClient.layerTest({ + sampleNow: Effect.never, + health: Effect.succeed({ + status: "healthy", + hello: Option.none(), + lastSampleAt: Option.none(), + lastError: Option.none(), + restartCount: 0, + sampleIntervalMs: 1_000, + }), + }); + const layerDesktop = DesktopTelemetryReceiver.layerTest({ + changes: Stream.fromPubSub(desktopChanges), + }); + const layerTelemetry = ResourceTelemetry.layer.pipe( + Layer.provide(Layer.mergeAll(layerNative, layerDesktop, layerAttribution)), + ); - yield* Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - yield* Effect.yieldNow; - yield* PubSub.publish(desktopChanges, nextDesktopSnapshot); - yield* Deferred.await(rebuildStarted); + yield* Effect.gen(function* () { + const telemetry = yield* ResourceTelemetry.ResourceTelemetry; + yield* Effect.yieldNow; + yield* PubSub.publish(desktopChanges, nextDesktopSnapshot); + yield* Deferred.await(rebuildStarted); - const subscriptionFiber = yield* telemetry.subscribe.pipe(Effect.forkChild); - yield* Effect.yieldNow; - yield* Deferred.succeed(finishRebuild, undefined); - const subscription = yield* Fiber.join(subscriptionFiber); + const subscriptionFiber = yield* telemetry.subscribe.pipe(Effect.forkChild); + yield* Effect.yieldNow; + yield* Deferred.succeed(finishRebuild, undefined); + const subscription = yield* Fiber.join(subscriptionFiber); - expect(DateTime.toEpochMillis(subscription.latest.readAt)).toBe( - nextDesktopSnapshot.sampledAtUnixMs, - ); - expect(subscription.latest.power).toEqual(nextDesktopSnapshot.power); - }).pipe(Effect.provide(layerTelemetry)); - }), - ), + expect(DateTime.toEpochMillis(subscription.latest.readAt)).toBe( + nextDesktopSnapshot.sampledAtUnixMs, + ); + expect(subscription.latest.power).toEqual(nextDesktopSnapshot.power); + }).pipe(Effect.provide(layerTelemetry)); + }), ); }); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts index ecc761d1d0..86d6f26e06 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts @@ -26,6 +26,7 @@ const dependencies = Layer.mergeAll( ManagedPolicy.layerTest(), Layer.mock(ThreadLaunchService.ThreadLaunchService)({ launch: () => Effect.die("synthetic dispatch failure"), + isNonGitProject: () => Effect.succeed(false), }), Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects", diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts index a6adcdaba9..92167ef83c 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts @@ -1,11 +1,18 @@ import * as Scheduler from "../scheduling/Scheduler.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { expect, it } from "@effect/vitest"; -import { ScheduledTaskUpsertInput } from "@t3tools/contracts"; +import { + type OrchestrationV2ConversationMessage, + type OrchestrationV2Run, + MessageId, + RunId, + ScheduledTaskUpsertInput, +} from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; @@ -173,6 +180,157 @@ it.effect("keeps the task list order when a toggle or edit rewrites updated_at", }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); +it.effect("keeps one queued occurrence of a recurring task while its bound thread is busy", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-07-01T09:00:00.000Z")); + // The bound thread's own run never finishes, so every scheduled send lands + // in its queue and stays there. + const activeRun = { + id: RunId.make("run:busy"), + status: "running", + userMessageId: MessageId.make("message:busy"), + } as OrchestrationV2Run; + const thread = yield* Ref.make<{ + readonly runs: ReadonlyArray; + readonly messages: ReadonlyArray; + }>({ runs: [activeRun], messages: [] }); + const runDueWork = yield* Ref.make>(Effect.void); + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + ManagedPolicy.layerTest(), + // Capture the poll pass so the test drives each due interval directly. + Layer.mock(Scheduler.Scheduler)({ + register: (name, work) => + name !== "scheduled-tasks" + ? Effect.void + : Effect.context>().pipe( + Effect.flatMap((context) => + Ref.set(runDueWork, work.pipe(Effect.provideContext(context), Effect.ignore)), + ), + ), + }), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + sendToThread: (input) => + Ref.modify(thread, (current) => { + const run = { + id: RunId.make(`run:${input.messageId}`), + status: "queued", + userMessageId: input.messageId, + } as OrchestrationV2Run; + const message = { + id: input.messageId, + threadId: input.threadId, + runId: run.id, + role: "user", + text: input.text, + ...(input.scheduledTaskId === undefined + ? {} + : { scheduledTaskId: input.scheduledTaskId }), + } as OrchestrationV2ConversationMessage; + return [ + { + delivery: "queued", + run, + message, + } as ThreadManagementService.ThreadManagementSendResult, + { runs: [...current.runs, run], messages: [...current.messages, message] }, + ]; + }), + getThreadRecords: () => Ref.get(thread).pipe(Effect.map((records) => records as never)), + getThreadShell: () => + Effect.succeed({ + projectId: "project-busy-thread", + deletedAt: null, + archivedAt: null, + } as never), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert( + yield* decodeUpsertInput({ + id: "scheduled-task:busy-thread", + title: "Check progress", + prompt: "Check progress", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: "project-busy-thread", + threadId: "thread:busy", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + + for (let interval = 0; interval < 3; interval++) { + yield* TestClock.adjust("61 seconds"); + yield* Effect.flatten(Ref.get(runDueWork)); + } + + const queuedOccurrencesOf = (taskId: typeof task.id) => + Ref.get(thread).pipe( + Effect.map( + ({ runs, messages }) => + runs + .filter((run) => run.status === "queued") + .map((run) => messages.find((message) => message.id === run.userMessageId)) + .filter((message) => message?.scheduledTaskId === taskId).length, + ), + ); + const queuedOccurrences = queuedOccurrencesOf(task.id); + expect(yield* queuedOccurrences).toBe(1); + // Skipped intervals still move the schedule forward. + const [listed] = (yield* service.list()).tasks; + expect(Date.parse(listed?.nextRunAt ?? "")).toBeGreaterThan( + Date.parse("2026-07-01T09:03:03.000Z"), + ); + + // Run now is an explicit request, so it still queues behind the held one. + yield* service.runNow({ id: task.id }); + expect(yield* queuedOccurrences).toBe(2); + + // Once the queued copies start, the next interval sends again. + yield* Ref.update(thread, (current) => ({ + ...current, + runs: current.runs.map((run) => + run.status === "queued" ? ({ ...run, status: "running" } as OrchestrationV2Run) : run, + ), + })); + yield* TestClock.adjust("61 seconds"); + yield* Effect.flatten(Ref.get(runDueWork)); + expect(yield* queuedOccurrences).toBe(1); + + // A one-time task's only scheduled occurrence still sends behind a queued Run now. + const { task: once } = yield* service.upsert( + yield* decodeUpsertInput({ + id: "scheduled-task:busy-thread-once", + title: "Check once", + prompt: "Check once", + enabled: true, + schedule: { type: "once", runAt: "2026-07-01T09:05:00.000Z" }, + projectId: "project-busy-thread", + threadId: "thread:busy", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + yield* service.runNow({ id: once.id }); + yield* TestClock.adjust("61 seconds"); + yield* Effect.flatten(Ref.get(runDueWork)); + expect(yield* queuedOccurrencesOf(once.id)).toBe(2); + }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + it.effect( "idle polls still wake for tasks saved later, recorded due times, and beside far-future tasks", () => @@ -234,3 +392,167 @@ it.effect( }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it.effect("a fixed-time slot missed while the server was off shows on the task", () => + Effect.gen(function* () { + const at = (hour: number, minute = 0, day = 1) => + DateTime.makeZonedUnsafe( + { year: 2026, month: 7, day, hour, minute, second: 0, millisecond: 0 }, + { timeZone: DateTime.zoneMakeLocal(), adjustForTimeZone: true }, + ); + yield* TestClock.setTime(DateTime.toEpochMillis(at(8))); + const launches = yield* Ref.make(0); + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + Scheduler.layer, + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: () => + Ref.update(launches, (count) => count + 1).pipe( + Effect.as({ threadId: "thread-missed-slot", resumed: false } as never), + ), + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + ); + const withServer = (effect: Effect.Effect) => + effect.pipe( + Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies))), + ); + + const taskId = yield* withServer( + Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert( + yield* decodeUpsertInput({ + title: "Morning bookkeeping", + prompt: "Update yesterday's notes.", + enabled: true, + schedule: { type: "fixed_time", timeOfDay: "09:00" }, + projectId: "project-missed-slot", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + yield* service.runNow({ id: task.id }); + return task.id; + }), + ); + + // The server is off across the 09:00 slot and comes back at 09:30. + yield* TestClock.setTime(DateTime.toEpochMillis(at(9, 30))); + const [listed] = yield* withServer( + Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + yield* TestClock.adjust("6 seconds"); + return (yield* service.list()).tasks; + }), + ); + + expect(listed?.id).toBe(taskId); + expect(yield* Ref.get(launches)).toBe(1); + expect(listed?.nextRunAt).toBe(DateTime.formatIso(DateTime.toUtc(at(9, 0, 2)))); + // The skipped slot must not read as the earlier manual run's clean success. + expect({ status: listed?.lastRunStatus, error: listed?.lastRunError }).not.toEqual({ + status: "succeeded", + error: null, + }); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + +it.effect( + "a run made while the scheduler was busy is not overwritten by its stale missed slot", + () => + Effect.gen(function* () { + const at = (hour: number, minute = 0, day = 1) => + DateTime.makeZonedUnsafe( + { year: 2026, month: 7, day, hour, minute, second: 0, millisecond: 0 }, + { timeZone: DateTime.zoneMakeLocal(), adjustForTimeZone: true }, + ); + yield* TestClock.setTime(DateTime.toEpochMillis(at(6))); + const slowStarted = yield* Deferred.make(); + const releaseSlow = yield* Deferred.make(); + const lastProcessed = yield* Deferred.make(); + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + Scheduler.layer, + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: (input) => + (input.title === "Slow" + ? Deferred.succeed(slowStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseSlow)), + ) + : input.title === "Last" + ? Deferred.succeed(lastProcessed, undefined) + : Effect.void + ).pipe(Effect.as({ threadId: `thread-${input.title}`, resumed: false } as never)), + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + ); + const withServer = (effect: Effect.Effect) => + effect.pipe( + Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies))), + ); + const upsert = ( + title: string, + schedule: { type: "interval"; everyMs: number } | { type: "fixed_time"; timeOfDay: string }, + ) => + Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert( + yield* decodeUpsertInput({ + title, + prompt: "Update the notes.", + enabled: true, + schedule, + projectId: "project-stale-slot", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + return task.id; + }); + + // Due at 07:00, 08:00 and 08:30; the server is off until 09:30. + const morningId = yield* withServer( + Effect.gen(function* () { + yield* upsert("Slow", { type: "interval", everyMs: 60 * 60 * 1000 }); + const id = yield* upsert("Morning", { type: "fixed_time", timeOfDay: "08:00" }); + yield* upsert("Last", { type: "interval", everyMs: 150 * 60 * 1000 }); + return id; + }), + ); + yield* TestClock.setTime(DateTime.toEpochMillis(at(9, 30))); + const morning = yield* withServer( + Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + yield* TestClock.adjust("6 seconds"); + yield* Deferred.await(slowStarted); + yield* service.runNow({ id: morningId }); + yield* Deferred.succeed(releaseSlow, undefined); + yield* Deferred.await(lastProcessed); + return (yield* service.list()).tasks.find((task) => task.id === morningId); + }), + ); + + expect({ status: morning?.lastRunStatus, error: morning?.lastRunError }).toEqual({ + status: "succeeded", + error: null, + }); + expect(morning?.nextRunAt).toBe(DateTime.formatIso(DateTime.toUtc(at(8, 0, 2)))); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index cbfea6b4e3..1335e36948 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -4,6 +4,7 @@ import * as NodeUtil from "node:util"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, it, vi } from "@effect/vitest"; import { + CommandId, ProjectId, ProviderInstanceId, ScheduledTaskError, @@ -17,6 +18,7 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; +import * as Option from "effect/Option"; import * as SqlClient from "effect/sql/SqlClient"; import * as Fiber from "effect/Fiber"; @@ -28,6 +30,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { OrchestratorDispatchError } from "../orchestration-v2/Orchestrator.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; @@ -418,6 +421,94 @@ it.effect("thread cleanup notifies subscribers and a finishing run cannot recrea }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); +it.effect.each([ + { status: "failed", error: "Weekly usage limit reached" }, + { status: "interrupted", error: "The run was stopped." }, + { status: "cancelled", error: "The run was cancelled." }, +] as const)("a run that ends $status after its message was accepted records it", (outcome) => + Effect.gen(function* () { + const projectId = ProjectId.make("project:test"); + const ended = yield* Deferred.make(); + const sent = yield* Ref.make(""); + const run = { id: "run:2", status: outcome.status, rootNodeId: "node:root" }; + const layer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.mergeAll( + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + sendToThread: (input) => Ref.set(sent, input.messageId).pipe(Effect.as({} as never)), + getThreadShell: () => Effect.succeed(threadShell(projectId)), + getProjectThreadRecords: () => + Effect.map( + Ref.get(sent), + (userMessageId) => + ({ + runs: [ + { id: "run:1", status: "completed", userMessageId: "message:earlier" }, + { ...run, userMessageId }, + ], + messages: [{ id: userMessageId, runId: "run:2" }], + turnItems: [ + { + type: "error", + status: "failed", + runId: "run:2", + nodeId: "node:root", + failure: { message: "Weekly usage limit reached" }, + }, + ], + }) as never, + ), + waitForThread: (input) => + Deferred.await(ended).pipe( + Effect.as({ + threadId: input.threadId, + run: { ...run, id: input.runId, userMessageId: "" }, + timedOut: false, + } as never), + ), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + NodeCrypto.layer, + Scheduler.layer, + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert({ + id: ScheduledTaskId.make("task:quota"), + title: "Quota bookkeeping", + prompt: "Update the notes", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId, + threadId: ThreadId.make("thread:quota"), + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + yield* service.runNow({ id: task.id }); + const failed = yield* service.subscribeList().pipe( + Stream.map(({ tasks }) => tasks.find((candidate) => candidate.id === task.id)), + Stream.filter((current) => current?.lastRunStatus === "failed"), + Stream.runHead, + Effect.forkChild, + ); + yield* Deferred.succeed(ended, undefined); + const recorded = Option.getOrUndefined(yield* Fiber.join(failed)); + assert.equal(recorded?.lastRunError, outcome.error); + assert.equal(recorded?.runCount, 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + it.effect("a bound run follows its thread when promotion moves it mid-send", () => Effect.gen(function* () { const scratch = ProjectId.make("project:scratch"); @@ -574,6 +665,67 @@ it.effect("a fresh-session task launches one thread, then starts each later run }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); +it.effect("a refused dispatch records its refusal, and opaque causes stay generic", () => + Effect.gen(function* () { + const refusal = "Thread thread:refused was stopped."; + const refused = (cause: unknown) => + new OrchestratorDispatchError({ + commandId: CommandId.make("command:refused"), + commandType: "message.dispatch", + cause, + }); + const generic = refused(undefined).message; + const cases = [ + [refusal, refusal], + [" ", generic], + [new Error("private-nested-secret"), generic], + ] as const; + const failure = yield* Ref.make(undefined); + const layer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.mergeAll( + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadShell: () => Effect.succeed(threadShell(ProjectId.make("project:test"))), + sendToThread: () => + Ref.get(failure).pipe(Effect.flatMap((cause) => Effect.fail(refused(cause)))), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + NodeCrypto.layer, + Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }), + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert({ + id: ScheduledTaskId.make("task:refused"), + title: "Refused dispatch", + prompt: "Check progress", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: ProjectId.make("project:test"), + threadId: ThreadId.make("thread:refused"), + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + for (const [cause, expected] of cases) { + yield* Ref.set(failure, cause); + const result = yield* service.runNow({ id: task.id }); + assert.equal(result.task.lastRunStatus, "failed"); + assert.equal(result.task.lastRunError, expected); + } + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + it.effect("a first run whose thread was deleted before it bound removes the task", () => Effect.gen(function* () { const layer = ScheduledTaskService.layer.pipe( diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 6458efc46e..222744d16a 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -51,10 +51,13 @@ import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as Metrics from "../observability/Metrics.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { OrchestratorDispatchError } from "../orchestration-v2/Orchestrator.ts"; +import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as DueHint from "../scheduling/DueHint.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; +import { latestRootProviderFailure } from "@t3tools/shared/orchestrationV2ThreadError"; import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts"; import { redactHeaders, @@ -76,6 +79,7 @@ import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerificatio export const WEBHOOK_ROUTE_PREFIX = "/api/hooks"; const isScheduledTaskError = Schema.is(ScheduledTaskError); +const isOrchestratorDispatchError = Schema.is(OrchestratorDispatchError); const PROMPT_TOO_LONG = "The filled-in prompt is too long."; const WEBHOOK_DELIVERY_RETENTION = 50; const WEBHOOK_DEDUPE_DELIVERY_RETENTION = 20; @@ -275,6 +279,13 @@ function iso(value: DateTime.DateTime): string { return DateTime.formatIso(DateTime.toUtc(value)); } +const RUN_OUTCOME_WAIT_MS = 24 * 60 * 60 * 1_000; +const UNSUCCESSFUL_RUN_ERRORS = { + failed: "The run failed.", + interrupted: "The run was stopped.", + cancelled: "The run was cancelled.", + rolled_back: "The run was rolled back.", +} as const; const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone); function nextRunAt( @@ -325,6 +336,14 @@ function errorMessage(error: unknown): string { return failure instanceof Error ? failure.message : String(failure); } +function dispatchErrorMessage(cause: Cause.Cause): string { + const failure = Cause.squash(cause); + // Direct orchestration refusals are user-facing; nested defects can contain private data. + return isOrchestratorDispatchError(failure) && typeof failure.cause === "string" + ? (userFacingDispatchErrorMessage(failure.cause) ?? errorMessage(failure)) + : errorMessage(failure); +} + function webhookPath(taskId: string, token: string): string { return `${WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(taskId)}/${token}`; } @@ -425,6 +444,7 @@ export const layer = Layer.effect( const mac = yield* Mac.Mac; const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const serviceScope = yield* Effect.scope; const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; const secretRequests = yield* SecretRequests.SecretRequests; const scheduler = yield* Scheduler.Scheduler; @@ -788,6 +808,24 @@ export const layer = Layer.effect( ), ); + // Reads every run row but only the queued runs' messages, so the cost per + // due interval tracks the thread's run count, not its transcript. + const hasQueuedOccurrence = Effect.fn("ScheduledTaskService.hasQueuedOccurrence")(function* ( + taskId: ScheduledTaskId, + threadId: ThreadId, + ) { + const { runs } = yield* threadManagement.getThreadRecords(threadId, ["runs"]); + const queued = runs.filter((run) => run.status === "queued"); + if (queued.length === 0) return false; + const queuedMessageIds = new Set(queued.map((run) => run.userMessageId)); + const { messages } = yield* threadManagement.getThreadRecords(threadId, ["messages"], { + messageIds: [...queuedMessageIds], + }); + return messages.some( + (message) => queuedMessageIds.has(message.id) && message.scheduledTaskId === taskId, + ); + }); + // The run already started the thread, so a failed write only costs the binding. // A thread deleted before the binding landed already ran its task cleanup, so apply that // cleanup here; a later deletion finds the binding. An unconfirmed lookup keeps the binding. @@ -807,6 +845,52 @@ export const layer = Layer.effect( ), ); + // A dispatch is recorded once the message is accepted; the provider can still + // reject the turn after that, so follow the run and record its failure. + const recordRunFailure = Effect.fn("ScheduledTaskService.recordRunFailure")(function* ( + taskId: ScheduledTaskId, + startedAtIso: string, + threadId: ThreadId, + messageId: MessageId, + ) { + const shell = yield* threadManagement.getThreadShell(threadId); + if (shell === null) return; + const thread = { projectId: shell.projectId, threadId }; + const { runs } = yield* threadManagement.getProjectThreadRecords(thread, ["runs"]); + const dispatched = runs.find((run) => run.userMessageId === messageId); + if (dispatched === undefined) return; + const { run } = yield* threadManagement.waitForThread({ + ...thread, + runId: dispatched.id, + timeoutMs: RUN_OUTCOME_WAIT_MS, + }); + if ( + run === null || + run.status === "completed" || + !ThreadManagementService.isTerminalRunStatus(run.status) + ) + return; + const { turnItems, messages } = yield* threadManagement.getProjectThreadRecords(thread, [ + "turnItems", + "messages", + ]); + // A queued message promoted to a steer cancels its run and joins the active one. + if ( + run.status === "cancelled" && + messages.find((message) => message.id === messageId)?.runId !== run.id + ) + return; + const error = + latestRootProviderFailure(run, turnItems)?.message ?? UNSUCCESSFUL_RUN_ERRORS[run.status]; + const updated = yield* sql` + UPDATE scheduled_tasks + SET last_run_status = 'failed', last_run_error = ${error} + WHERE task_id = ${taskId} AND last_run_at = ${startedAtIso} AND last_run_status = 'succeeded' + RETURNING task_id + `; + if (updated.length > 0) yield* notifyChanged; + }); + const runTask = Effect.fn("ScheduledTaskService.runTask")(function* ( task: ScheduledTask, trigger: "scheduled" | "manual" | "webhook", @@ -854,6 +938,19 @@ export const layer = Layer.effect( ) { return { task: active, threadId: null, dispatchFailed: false }; } + // A thread that stays busy would otherwise collect one copy of the + // prompt per interval. A failed read falls through to the normal send. + if ( + trigger === "scheduled" && + active.schedule.type !== "once" && + active.threadId !== null && + (yield* hasQueuedOccurrence(active.id, ThreadId.make(active.threadId)).pipe( + Effect.orElseSucceed(() => false), + )) + ) { + yield* rescheduleMissedRun(active, startedAt, "previous occurrence still queued"); + return { task: active, threadId: null, dispatchFailed: false }; + } // Reject queued deliveries after pause, same-id recreation or trigger changes. if (webhook !== undefined) { const reason = @@ -974,7 +1071,7 @@ export const layer = Layer.effect( if (webhook !== undefined && runSucceeded) yield* Ref.set(webhook.dispatched, true); const completedAt = yield* localNow; const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const); - const lastRunError = runSucceeded ? null : errorMessage(result.cause); + const lastRunError = runSucceeded ? null : dispatchErrorMessage(result.cause); const threadId = runSucceeded ? result.value : null; // One transaction, so an edit cannot land between reading the schedule and // writing the next run computed from it. The origin is read first: it reads @@ -1039,6 +1136,17 @@ export const layer = Layer.effect( ), ); if (written) yield* notifyChanged; + if (written && threadId !== null) { + yield* recordRunFailure(active.id, startedAtIso, threadId, messageId).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not record scheduled run outcome", { + taskId: active.id, + cause, + }), + ), + Effect.forkIn(serviceScope), + ); + } // The stored row can belong to a replacement, so report this dispatch separately. return { task: recorded, threadId, dispatchFailed: !runSucceeded }; }).pipe( @@ -1075,24 +1183,32 @@ export const layer = Layer.effect( const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* ( task: ScheduledTask, now: DateTime.DateTime, + reason = "missed", + runError?: string, ) { const next = nextRunAt(task, now); - yield* Effect.logInfo("Skipping missed schedule task run", { + yield* Effect.logInfo("Skipping schedule task run", { taskId: task.id, + reason, missedRunAt: task.nextRunAt, rescheduledTo: next, }); - yield* sql` + // `task` can be a stale batch snapshot; a run or edit since then already moved the row on. + const updated = yield* sql` UPDATE scheduled_tasks SET next_run_at = ${next}, updated_at = ${iso(now)} + ${runError === undefined ? sql`` : sql`, last_run_status = 'failed', last_run_error = ${runError}`} WHERE task_id = ${task.id} + AND next_run_at IS ${task.nextRunAt} + AND last_run_at IS ${task.lastRunAt} + RETURNING task_id `.pipe( Effect.mapError((cause) => taskError("Could not reschedule missed schedule task run.", { taskId: task.id, cause }), ), ); - yield* notifyChanged; + if (updated.length > 0) yield* notifyChanged; }); const runDueTasks = Effect.fn("ScheduledTaskService.runDueTasks")(function* () { @@ -1130,7 +1246,12 @@ export const layer = Layer.effect( ({ task, dueAt }) => Effect.suspend(() => isMissedFixedTimeRun(task.schedule, dueAt, now) - ? rescheduleMissedRun(task, now) + ? rescheduleMissedRun( + task, + now, + "missed", + "Missed a scheduled run because the server was not running at that time.", + ) : runTask(task, "scheduled"), ).pipe( Effect.catch((cause) => @@ -1198,7 +1319,10 @@ export const layer = Layer.effect( const list: ScheduledTaskService["Service"]["list"] = () => listRows().pipe( - Effect.map((tasks) => ({ tasks })), + Effect.map((tasks) => ({ + tasks, + timeZone: DateTime.zoneToString(DateTime.zoneMakeLocal()), + })), Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })), ); @@ -1358,9 +1482,11 @@ export const layer = Layer.effect( return { token, secret, secretChanged }; }) : { token: null, secret: null, secretChanged: true }; + // A folder that is not a Git repository, Scratch included, cannot hold a worktree. const workspaceStrategy: ScheduledTask["workspaceStrategy"] = input.workspaceStrategy.type === "worktree" && - (yield* managedFolders.isScratchProject(input.projectId)) + ((yield* managedFolders.isScratchProject(input.projectId)) || + (yield* threadLaunch.isNonGitProject(input.projectId))) ? { type: "root" } : input.workspaceStrategy; const scheduleUnchanged = @@ -1837,8 +1963,6 @@ export const layer = Layer.effect( }); }); - const serviceScope = yield* Effect.scope; - const releaseFailedDelivery = Effect.fn("ScheduledTaskService.releaseFailedDelivery")( function* (deliveryId: string) { yield* releaseReplay(deliveryId); diff --git a/apps/server/src/secrets/SecretCheck.test.ts b/apps/server/src/secrets/SecretCheck.test.ts new file mode 100644 index 0000000000..473cab1dfc --- /dev/null +++ b/apps/server/src/secrets/SecretCheck.test.ts @@ -0,0 +1,363 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + ProviderDriverKind, + ProviderInstanceId, + SecretProviderId, + SecretProviderKind, + type SecretReference, + SettingsSecretValue, + type ServerProvider, +} from "@t3tools/contracts"; +import type { AnyProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver"; +import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import { defineSecretProviderDriver } from "@t3tools/secret-provider-core/server/driver"; +import { defineSecretProvider } from "@t3tools/secret-provider-core/shared/definition"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import { HttpClient, HttpClientResponse } from "effect/http"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import * as ServerConfig from "../config.ts"; +import * as ModelManifest from "../provider/ModelManifest.ts"; +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import * as ProviderInstanceRegistryMutator from "../provider/ProviderInstanceRegistryMutator.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as SecretCheck from "./SecretCheck.ts"; + +const FAKE_KIND = SecretProviderKind.make("fake"); +const secretProvider = SecretProviderId.make("personal"); +const wanted: SecretReference = { provider: secretProvider, reference: "fake://wanted" }; +const other: SecretReference = { provider: secretProvider, reference: "fake://other" }; +const locked: SecretReference = { provider: secretProvider, reference: "fake://locked" }; +const driverKind = ProviderDriverKind.make("fake-provider"); +const dependent = ProviderInstanceId.make("dependent"); +const unrelated = ProviderInstanceId.make("unrelated"); + +const providerSnapshot = (instanceId: ProviderInstanceId): ServerProvider => ({ + instanceId, + driver: driverKind, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-10-03T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], +}); + +/** + * A server whose `dependent` instance reads `dependentReads` and `unrelated` reads `other`, all + * through the real resolver, instance registry and provider registry. `vault` answers each read of + * a reference with the next queued value, repeating the last one, after `beforeRead`. + */ +const setup = Effect.fn("SecretCheckTest.setup")(function* ( + vault: Map>, + dependentReads: ReadonlyArray = [wanted], + options: { + readonly dependentConfig?: unknown; + readonly beforeRead?: (reference: string) => Effect.Effect; + } = {}, +) { + const reads: Array = []; + const created: Array<{ instanceId: ProviderInstanceId; secrets: ReadonlyArray }> = []; + const createdConfigs: Array = []; + const refreshed: Array = []; + + const secretDriver = defineSecretProviderDriver({ + kind: FAKE_KIND, + definition: defineSecretProvider({ + kind: FAKE_KIND, + label: "Fake", + configSchema: Schema.Struct({}), + isReference: (value) => value.startsWith("fake://"), + referencePlaceholder: "fake://item", + invalidReferenceMessage: "Use fake://item.", + }), + read: (_config, references) => + Effect.forEach(references, (reference) => + (options.beforeRead?.(reference) ?? Effect.void).pipe( + Effect.andThen( + Effect.sync(() => { + reads.push(reference); + const answers = vault.get(reference) ?? []; + return answers.length > 1 ? answers.shift() : answers[0]; + }), + ), + ), + ), + }); + + const driver: AnyProviderDriver = { + driverKind, + metadata: { displayName: "Fake" }, + configSchema: Schema.Struct({ + keys: Schema.Record(Schema.String, SettingsSecretValue).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), + }), + defaultConfig: () => ({}), + create: (input) => + Effect.sync(() => { + created.push({ + instanceId: input.instanceId, + secrets: input.environment.map((variable) => variable.value), + }); + createdConfigs.push(input.config); + const snapshot = providerSnapshot(input.instanceId); + return { + instanceId: input.instanceId, + driverKind, + continuationIdentity: { driverKind, continuationKey: `fake:${input.instanceId}` }, + displayName: undefined, + enabled: input.enabled, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driverKind, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(snapshot), + refresh: Effect.sync(() => { + refreshed.push(input.instanceId); + return snapshot; + }), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + }), + }; + const instanceConfig = (secrets: ReadonlyArray, config: unknown = {}) => ({ + driver: driverKind, + config, + environment: secrets.map((secret, index) => ({ + name: `API_KEY_${index}`, + value: secret, + sensitive: true, + })), + }); + + const resolverContext = yield* Layer.build( + SecretResolver.layer({ + drivers: [secretDriver], + secretProviders: Effect.succeed({ + [secretProvider]: { kind: FAKE_KIND, label: "Personal", config: {} }, + }), + }), + ); + const { registry, mutator } = yield* ProviderInstanceRegistry.makeProviderInstanceRegistry({ + drivers: [driver], + configMap: { + [dependent]: instanceConfig(dependentReads, options.dependentConfig), + [unrelated]: instanceConfig([other]), + }, + }).pipe(Effect.provide(resolverContext)); + // Secrets are read after startup, so wait for the change that applies them. + const changes = yield* registry.subscribeChanges; + yield* PubSub.take(changes); + + const services = yield* Layer.build( + SecretCheck.layer.pipe( + Layer.provideMerge(ProviderRegistry.layer), + Layer.provide( + Layer.mergeAll( + Layer.succeedContext(resolverContext), + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, registry), + Layer.succeed(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, mutator), + ), + ), + ), + ); + const secretCheck = yield* SecretCheck.SecretCheck.pipe(Effect.provide(services)); + const resolver = yield* SecretResolver.SecretResolver.pipe(Effect.provide(resolverContext)); + return { secretCheck, registry, mutator, resolver, reads, created, createdConfigs, refreshed }; +}); + +const layerTest = Layer.mergeAll( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-check-" }), + ModelManifest.layerTest, + ProviderLatestVersions.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))), + ), + ), +).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); + +it.layer(layerTest)("SecretCheck", (it) => { + it.effect( + "a readable secret rebuilds and refreshes only the instances that read it, from that one read", + () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, [undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault); + assert.deepStrictEqual( + (yield* server.registry.listUnavailable).map((entry) => entry.instanceId), + [dependent], + ); + const createdBefore = server.created.length; + const readsBefore = server.reads.length; + + // Unlocked for the check's own read only: any second read would fail again. + vault.set(wanted.reference, ["wanted-key", undefined]); + const result = yield* server.secretCheck.check(wanted); + + assert.deepStrictEqual(result, { _tag: "Resolved" }); + assert.notInclude(JSON.stringify(result), "wanted-key"); + assert.deepStrictEqual(server.reads.slice(readsBefore), [wanted.reference]); + assert.deepStrictEqual(server.created.slice(createdBefore), [ + { instanceId: dependent, secrets: ["wanted-key"] }, + ]); + assert.deepStrictEqual(server.refreshed, [dependent]); + assert.deepStrictEqual(yield* server.registry.listUnavailable, []); + }), + ); + + it.effect("an unreadable secret fails naming its provider and leaves instances alone", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, [undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault); + const createdBefore = server.created.length; + + const result = yield* server.secretCheck.check(wanted); + + assert.strictEqual(result._tag, "Failed"); + if (result._tag === "Failed") assert.include(result.detail, "Personal"); + assert.deepStrictEqual(server.created.slice(createdBefore), []); + assert.deepStrictEqual(server.refreshed, []); + assert.deepStrictEqual( + (yield* server.registry.listUnavailable).map((entry) => entry.instanceId), + [dependent], + ); + }), + ); + + it.effect("a failed check keeps the value the server already holds", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, ["wanted-key"]], + [locked.reference, ["locked-key", undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault, [wanted, locked]); + const readsBefore = server.reads.length; + + assert.strictEqual((yield* server.secretCheck.check(locked))._tag, "Failed"); + + assert.deepStrictEqual(yield* server.resolver.read([locked]), ["locked-key"]); + assert.deepStrictEqual(server.reads.slice(readsBefore), [locked.reference]); + }), + ); + + it.effect("a check applies to an instance whose other secret failed a later refresh", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, ["wanted-old"]], + [locked.reference, ["locked-key", undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault, [wanted, locked]); + // A Settings refresh while the vault is locked keeps the live instance and caches the failure. + yield* server.mutator.reloadSecrets(dependent); + vault.set(wanted.reference, ["wanted-new"]); + + assert.deepStrictEqual(yield* server.secretCheck.check(wanted), { _tag: "Resolved" }); + + assert.deepStrictEqual(server.created.at(-1), { + instanceId: dependent, + secrets: ["wanted-new", "locked-key"], + }); + assert.deepStrictEqual(yield* server.registry.listUnavailable, []); + }), + ); + + it.effect("a check applies the value it read when a refresh re-reads that secret first", () => + Effect.forEach( + // A live instance holding the old value, and one parked on a locked vault. + ["wanted-old", undefined], + (initial) => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, [initial]], + [other.reference, ["other-key"]], + ]); + const readStarted = yield* Deferred.make(); + const release = yield* Deferred.make(); + let gate: Effect.Effect = Effect.void; + const server = yield* setup(vault, [wanted], { + beforeRead: () => { + const current = gate; + gate = Effect.void; + return current; + }, + }); + // The check reads the rotated value; the refresh's read after it finds the vault locked. + vault.set(wanted.reference, ["wanted-new", undefined]); + gate = Deferred.succeed(readStarted, undefined).pipe( + Effect.andThen(Deferred.await(release)), + ); + + const check = yield* server.secretCheck + .check(wanted) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(readStarted); + // The refresh takes the registry lock, then waits on the resolver for the check's read. + const refresh = yield* server.mutator + .reloadSecrets(dependent) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(release, undefined); + + assert.deepStrictEqual(yield* Fiber.join(check), { _tag: "Resolved" }); + yield* Fiber.join(refresh); + assert.deepStrictEqual(server.created.at(-1), { + instanceId: dependent, + secrets: ["wanted-new"], + }); + assert.deepStrictEqual(yield* server.registry.listUnavailable, []); + }).pipe(Effect.scoped), + { discard: true }, + ), + ); + + it.effect("a check replaces only its own key of a record-valued config secret", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, ["wanted-old"]], + [locked.reference, ["locked-key"]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault, [], { + dependentConfig: { keys: { a: wanted, b: locked } }, + }); + vault.set(wanted.reference, ["wanted-new"]); + + assert.deepStrictEqual(yield* server.secretCheck.check(wanted), { _tag: "Resolved" }); + + assert.deepStrictEqual(server.created.at(-1), { instanceId: dependent, secrets: [] }); + assert.deepStrictEqual(server.createdConfigs.at(-1), { + keys: { a: "wanted-new", b: "locked-key" }, + }); + }), + ); +}); diff --git a/apps/server/src/secrets/SecretCheck.ts b/apps/server/src/secrets/SecretCheck.ts new file mode 100644 index 0000000000..f2a6241eeb --- /dev/null +++ b/apps/server/src/secrets/SecretCheck.ts @@ -0,0 +1,39 @@ +import type { SecretReference, SecretSourceCheckResult } from "@t3tools/contracts"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; + +export class SecretCheck extends Context.Service< + SecretCheck, + { + /** + * Reads one secret fresh for the Settings "check" button and never returns the value. A + * readable secret also rebuilds the provider instances that read it, from that same read. + */ + readonly check: (reference: SecretReference) => Effect.Effect; + } +>()("t3/secrets/SecretCheck") {} + +const make = Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; + + const check = Effect.fn("SecretCheck.check")(function* (reference: SecretReference) { + const [value] = yield* resolver.read([reference], { fresh: true }); + if (value === undefined || value.trim() === "") { + return { + _tag: "Failed", + detail: `Could not read this secret from "${yield* resolver.label(reference.provider)}". Check the provider's settings and that its store is unlocked.`, + } as const; + } + yield* providerRegistry.applySecretAndRefresh(reference, value); + return { _tag: "Resolved" } as const; + }); + + return SecretCheck.of({ check }); +}); + +export const layer = Layer.effect(SecretCheck, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 008759263c..01ade2b327 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -25,17 +25,21 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; +import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; +import * as KeepAwake from "./background/KeepAwake.ts"; import * as ServerConfig from "./config.ts"; import { withUntracedRequests } from "./http.ts"; import * as ServerHttp from "./http.ts"; import { guardHttpResponseWriteErrors, + keepIdleConnections, rejectRequestsUntilServing, } from "./httpResponseErrorGuard.ts"; import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; +import * as SpawnWorker from "./process/SpawnWorker.ts"; import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts"; import * as PullRequestHttp from "./pullRequest/http.ts"; import * as SpeechModelStore from "./speech/SpeechModelStore.ts"; @@ -66,6 +70,7 @@ import * as CheckpointStore from "./checkpointing/CheckpointStore.ts"; import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts"; import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST } from "./sourceControl/sourceControlDefinitions.ts"; import * as TextGeneration from "./textGeneration/TextGeneration.ts"; +import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as SecretResolver from "./secrets/SecretResolver.ts"; import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts"; import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverrideSweep.ts"; @@ -101,6 +106,7 @@ import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts"; import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts"; import * as ProviderInstallation from "./provider/providerInstallation.ts"; import * as CodexInstallation from "./provider/CodexInstallation.ts"; +import * as ProviderInstallationGate from "./provider/ProviderInstallationGate.ts"; import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts"; import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegistry.ts"; import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; @@ -114,6 +120,7 @@ import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts"; import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; +import * as VcsAutomaticFetchInterval from "./vcs/VcsAutomaticFetchInterval.ts"; import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts"; import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts"; import * as VcsProcess from "./vcs/VcsProcess.ts"; @@ -180,6 +187,7 @@ import * as NetService from "@t3tools/shared/Net"; import { disableTailscaleServe, ensureTailscaleServe, + readTailscaleServeRootHolder, readTailscaleServeRoutesTo, readTailscaleStatus, } from "@t3tools/tailscale"; @@ -274,6 +282,9 @@ const layerResourceDiagnostics = Layer.mergeAll( ProcessGroupMetrics.layer.pipe(Layer.provide(layerResourceTelemetry)), ); +// NodeServices and NodeHttpServer each output Node's own spawner, so each is followed by this one. +const layerSpawner = SpawnWorker.layerServer.pipe(Layer.provide(NodeServices.layer)); + const layerHttpServer = Layer.unwrap( Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -289,7 +300,7 @@ const layerHttpServer = Layer.unwrap( return NodeHttpServer.layer( () => { const server = rejectRequestsUntilServing( - guardHttpResponseWriteErrors(NodeHttp.createServer()), + keepIdleConnections(guardHttpResponseWriteErrors(NodeHttp.createServer())), ); if (config.privateNetworkOnly) { server.on("connection", (socket) => { @@ -310,12 +321,17 @@ const layerHttpServer = Layer.unwrap( // `threshold` when context takeover is disabled). websocket: { perMessageDeflate: true }, }, - ); + ).pipe(Layer.merge(layerSpawner)); }), -).pipe(Layer.provide(ManagedPolicy.layer)); +).pipe( + Layer.provide(ManagedPolicy.layer), + // NodeHttpServer.layer also outputs NodeServices, whose spawner would shadow the wrapped one. + (layer) => NonBlockingSpawner.layer.pipe(Layer.provideMerge(layer)), +); const layerPlatformServices = DocumentText.layer.pipe( - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + Layer.provideMerge(NonBlockingSpawner.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner)), ); const layerPersistence = Layer.empty.pipe(Layer.provideMerge(SqlitePersistence.layerConfig)); @@ -408,7 +424,6 @@ const layerVcs = Layer.empty.pipe( Layer.provideMerge( VcsStatusBroadcaster.layer.pipe( Layer.provide(layerGitWorkflow), - Layer.provide(VcsStatusBroadcaster.layerAutomaticFetchInterval), // The orchestration runtime also consumes the broadcaster (run // finalization), so the policy cannot read the store from the runtime's // output. @@ -421,9 +436,14 @@ const layerVcs = Layer.empty.pipe( const layerCheckpointStore = CheckpointStore.layer.pipe(Layer.provide(layerVcsDriverRegistry)); -const layerPortScanner = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer)); +const layerPortScanner = PortScanner.layer.pipe( + Layer.provide(ProcessRunner.layer), + Layer.provide(layerBackground), +); -const layerTerminal = TerminalManager.layer.pipe( +const layerTerminal = TerminalManager.layer( + ProviderInstanceRegistryHydration.deriveProviderInstanceConfigMap, +).pipe( Layer.provide(layerPtyAdapter), Layer.provide(layerPortScanner), Layer.provide(layerNativeTelemetry), @@ -468,6 +488,7 @@ const layerAuth = EnvironmentAuth.layer.pipe( ); const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( + Layer.provide(UsageLimitSources.layerResetFallback), Layer.provide(layerCheckpointStore), Layer.provide(layerGitWorkflow), Layer.provide( @@ -551,6 +572,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provide(layerServerRestart), ), layerThreadPullRequestWorker, + KeepAwake.layer, Layer.effectDiscard( Effect.gen(function* () { const service = yield* PullRequestSyncReactor.PullRequestSyncReactor; @@ -587,7 +609,10 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge(layerOrchestrationApplication), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)), + Layer.provideMerge(SecretCheck.layer), Layer.provideMerge(SecretResolver.layer), + // Above the settings it writes when a theme is applied. + Layer.provideMerge(EnvironmentTheme.layer), Layer.provideMerge(layerServerSettings), Layer.provideMerge(layerSourceControlProviderRegistry), Layer.provideMerge(layerGit), @@ -597,19 +622,25 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge( Layer.mergeAll( Keybindings.layer, - EnvironmentTheme.layer, UsageLimitSources.layer, HostAppUpdates.layer.pipe(Layer.provide(layerDesktopTelemetryReceiver)), ), ), Layer.provideMerge(ProviderRegistry.layer), - Layer.provideMerge(ProviderInstanceRegistryHydration.layer), + Layer.provideMerge( + ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(SqlitePersistence.layerConfig)), + ), + // One gate for the server, below hydration so the Claude adapter sees it: layers memoize by + // reference, so the runtime layer shares it. + Layer.provideMerge(ProviderInstallationGate.layer), // Provider hydration builds the Claude runner, which reports agents to the same scanner the // terminal and preview layers share. Layer.provideMerge(layerPortScanner), Layer.provideMerge( Layer.mergeAll( - AntigravityInstallation.AntigravityInstallation.layer, + AntigravityInstallation.AntigravityInstallation.layer.pipe( + Layer.provide(layerServerSettings), + ), CodexInstallation.CodexInstallation.layer, ), ), @@ -657,8 +688,11 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe( Layer.provideMerge(TraceDiagnostics.layer), Layer.provideMerge(ExternalLauncher.layer), Layer.provideMerge(RemoteOpenTargets.layer), - Layer.provideMerge(DirectEndpoints.layer), + Layer.provideMerge(DirectEndpoints.layer.pipe(Layer.provide(layerServerEnvironment))), Layer.provideMerge(ServerLifecycleEvents.layer), + // GitVcsDriver.layer is memoized and some of its build sites live outside this file, so the + // fetch interval goes in context here, before the first build captures it. + Layer.provideMerge(VcsAutomaticFetchInterval.layer.pipe(Layer.provide(layerServerSettings))), Layer.provide(NetService.layer), ); @@ -762,6 +796,17 @@ const layerMakeServer = Layer.unwrap( yield* startup.markHttpListening; }), ); + const layerDesktopReadySignal = Layer.effectDiscard( + Effect.gen(function* () { + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + const receiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver; + yield* startup.awaitCommandReady.pipe( + Effect.andThen(receiver.announceServerReady), + Effect.ignore, + Effect.forkScoped, + ); + }), + ); const layerRuntimeState = Layer.effectDiscard( Effect.gen(function* () { yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie); @@ -788,6 +833,8 @@ const layerMakeServer = Layer.unwrap( ); }), ); + const tailscaleServeRootHolder = (target: { readonly host: string; readonly port: number }) => + readTailscaleServeRootHolder(config.tailscaleServePort, target); const layerTailscaleServe = config.tailscaleServeEnabled ? Layer.effectDiscard( Effect.acquireRelease( @@ -802,16 +849,31 @@ const layerMakeServer = Layer.unwrap( const localPort = address.port; const localHost = loopbackUrlHostForAddress(address); + const route = { + localPort, + urlHost: localHost, + localHost: localHost.replace(/^\[|\]$/gu, ""), + servePort: config.tailscaleServePort, + }; + const holder = yield* tailscaleServeRootHolder({ + host: route.localHost, + port: localPort, + }).pipe(Effect.orElseSucceed(() => "unreadable" as const)); + if (holder === "other" || holder === "unreadable") { + yield* Effect.logWarning( + holder === "other" + ? "Tailscale Serve left off; its port already serves another server or app" + : "Tailscale Serve left off; its current routes could not be read", + { localPort, servePort: config.tailscaleServePort }, + ); + return route; + } return yield* ensureTailscaleServe({ localPort, servePort: config.tailscaleServePort, localHost, }).pipe( - Effect.as({ - localPort, - localHost: localHost.replace(/^\[|\]$/gu, ""), - servePort: config.tailscaleServePort, - }), + Effect.as(route), Effect.tap(() => Effect.logInfo("Tailscale Serve configured", { localPort, @@ -819,11 +881,13 @@ const layerMakeServer = Layer.unwrap( }), ), Effect.catch((cause) => - Effect.logWarning("Failed to configure Tailscale Serve", { - cause, - localPort, - servePort: config.tailscaleServePort, - }).pipe(Effect.as(null)), + Effect.logWarning( + cause._tag === "TailscaleCommandExitError" && + cause.stderrDiagnostic === "unsupported-target" + ? `Tailscale Serve left off; this Tailscale install can only proxy to localhost, not ${localHost}. Bind --host 127.0.0.1 or 0.0.0.0 instead` + : "Failed to configure Tailscale Serve", + { cause, localPort, servePort: config.tailscaleServePort }, + ).pipe(Effect.as(null)), ), ); }), @@ -876,8 +940,42 @@ const layerMakeServer = Layer.unwrap( ), ) : Effect.void, + ).pipe( + // Startup is not the only time the route can go stale, so whoever finds it on a dead + // port takes it back. + Effect.tap((configured) => + configured === null + ? Effect.void + : Effect.sleep("30 seconds").pipe( + Effect.andThen( + tailscaleServeRootHolder({ + host: configured.localHost, + port: configured.localPort, + }), + ), + Effect.flatMap((holder) => + holder === "dead" + ? ensureTailscaleServe({ + localPort: configured.localPort, + servePort: configured.servePort, + localHost: configured.urlHost, + }).pipe( + Effect.andThen( + Effect.logInfo("Tailscale Serve repaired", { + localPort: configured.localPort, + servePort: configured.servePort, + }), + ), + ) + : Effect.void, + ), + Effect.ignore, + Effect.forever, + Effect.forkScoped, + ), + ), ), - ) + ).pipe(Layer.provide(NetService.layer)) : Layer.empty; const layerRuntimeServices = ServerRuntimeStartup.layerWithOptions({ @@ -903,6 +1001,7 @@ const layerMakeServer = Layer.unwrap( const layerServerApplication = Layer.mergeAll( layerRoutes, layerHttpListening, + layerDesktopReadySignal, layerRuntimeState.pipe(Layer.provide(layerLauncher)), layerTailscaleServe, HeapSnapshot.layer, @@ -922,4 +1021,7 @@ const layerMakeServer = Layer.unwrap( }), ).pipe(Layer.provide(ProcessRunner.layer)); -export const runServer = Layer.launch(layerMakeServer); +export const runServer = Layer.launch( + // For the layers above whose spawner requirement is not met by one of them. + layerMakeServer.pipe(Layer.provide(NonBlockingSpawner.layer.pipe(Layer.provide(layerSpawner)))), +); diff --git a/apps/server/src/serverLifecycleEvents.ts b/apps/server/src/serverLifecycleEvents.ts index 7d394e4dc9..d90b7fa57b 100644 --- a/apps/server/src/serverLifecycleEvents.ts +++ b/apps/server/src/serverLifecycleEvents.ts @@ -1,5 +1,6 @@ import type { ServerLifecycleStreamEvent } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as PubSub from "effect/PubSub"; @@ -22,11 +23,14 @@ export class ServerLifecycleEvents extends Context.Service< readonly publish: (event: LifecycleEventInput) => Effect.Effect; readonly snapshot: Effect.Effect; readonly stream: Stream.Stream; + /** Completes once the first ready event is published. */ + readonly awaitReady: Effect.Effect; } >()("t3/serverLifecycleEvents") {} const make = Effect.gen(function* () { const pubsub = yield* PubSub.unbounded(); + const ready = yield* Deferred.make(); const state = yield* Ref.make({ sequence: 0, events: [], @@ -45,8 +49,14 @@ const make = Effect.gen(function* () { ...current.events.filter((entry) => entry.type !== nextEvent.type), ]; return [nextEvent, { sequence: nextSequence, events: nextEvents }] as const; - }).pipe(Effect.tap((event) => PubSub.publish(pubsub, event))), + }).pipe( + Effect.tap((event) => PubSub.publish(pubsub, event)), + Effect.tap((event) => + event.type === "ready" ? Deferred.succeed(ready, undefined) : Effect.void, + ), + ), snapshot: Ref.get(state), + awaitReady: Deferred.await(ready), get stream() { return Stream.fromPubSub(pubsub); }, diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 78bbff7a63..7ea01276b6 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -79,12 +79,53 @@ const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* ( return !Number.isFinite(startedAt) || startedAt <= recordedAt + 1_000; }); +const ownershipLockPath = (stateDir: string) => NodePath.join(stateDir, "server-owner.sqlite"); + /** - * Hold an exclusive lock on the state directory until the scope closes. The - * lock is an exclusive transaction on `server-owner.sqlite`, which never holds - * data and must never be unlinked: the OS releases it when the process exits, - * even on SIGKILL, so a crashed owner never blocks the next start. + * The lock is an exclusive transaction on `server-owner.sqlite`, which never + * holds data and must never be unlinked: the OS releases it when the process + * exits, even on SIGKILL, so a crashed owner never blocks the next start. */ +const openOwnershipLock = (stateDir: string) => + Effect.try({ + try: () => { + const lockPath = ownershipLockPath(stateDir); + NodeFS.mkdirSync(stateDir, { recursive: true }); + let before = NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false }); + if (before === undefined) { + NodeFS.closeSync(NodeFS.openSync(lockPath, "a", 0o644)); + before = NodeFS.statSync(lockPath, { bigint: true }); + } + const db = new NodeSqlite.DatabaseSync(lockPath); + try { + db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;"); + const identity = NodeFS.statSync(lockPath, { bigint: true }); + return { + db, + identity, + replacedDuringAcquire: before.dev !== identity.dev || before.ino !== identity.ino, + }; + } catch (cause) { + db.close(); + throw cause; + } + }, + catch: (cause) => + isSqliteBusy(cause) + ? new ServerAlreadyRunningError({ stateDir }) + : new ServerOwnershipError({ stateDir, cause }), + }); + +/** Hold only the ownership lock until the scope closes, without claiming the runtime state. */ +export const holdServerOwnershipLock = Effect.fn("holdServerOwnershipLock")(function* ( + statePath: string, +) { + yield* Effect.acquireRelease(openOwnershipLock(NodePath.dirname(statePath)), ({ db }) => + Effect.sync(() => db.close()), + ); +}); + +/** Hold an exclusive lock on the state directory until the scope closes. */ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(function* ( statePath: string, ) { @@ -93,45 +134,17 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi const ownerId = yield* random .uuidV4() .pipe(Effect.mapError((cause) => new ServerOwnershipError({ stateDir, cause }))); - const lockPath = NodePath.join(stateDir, "server-owner.sqlite"); - const lock = yield* Effect.acquireRelease( - Effect.try({ - try: () => { - NodeFS.mkdirSync(stateDir, { recursive: true }); - let before = NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false }); - if (before === undefined) { - NodeFS.closeSync(NodeFS.openSync(lockPath, "a", 0o644)); - before = NodeFS.statSync(lockPath, { bigint: true }); - } - const db = new NodeSqlite.DatabaseSync(lockPath); - try { - db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;"); - const identity = NodeFS.statSync(lockPath, { bigint: true }); - return { - db, - identity, - replacedDuringAcquire: before.dev !== identity.dev || before.ino !== identity.ino, - }; - } catch (cause) { - db.close(); - throw cause; - } - }, - catch: (cause) => - isSqliteBusy(cause) - ? new ServerAlreadyRunningError({ stateDir }) - : new ServerOwnershipError({ stateDir, cause }), - }), - ({ db }) => - readPersistedServerRuntimeState(statePath).pipe( - Effect.flatMap((state) => - Option.isSome(state) && state.value.ownerId === ownerId - ? clearPersistedServerRuntimeState(statePath) - : Effect.void, - ), - Effect.ignore({ log: true }), - Effect.ensuring(Effect.sync(() => db.close())), + const lockPath = ownershipLockPath(stateDir); + const lock = yield* Effect.acquireRelease(openOwnershipLock(stateDir), ({ db }) => + readPersistedServerRuntimeState(statePath).pipe( + Effect.flatMap((state) => + Option.isSome(state) && state.value.ownerId === ownerId + ? clearPersistedServerRuntimeState(statePath) + : Effect.void, ), + Effect.ignore({ log: true }), + Effect.ensuring(Effect.sync(() => db.close())), + ), ); const previous = yield* readPersistedServerRuntimeState(statePath).pipe( diff --git a/apps/server/src/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.ts index 8c6393ec90..f2486cb852 100644 --- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts +++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts @@ -36,160 +36,156 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; it.effect("parks automatic pull until activation without delaying command readiness", () => - Effect.scoped( - Effect.gen(function* () { - const activation = yield* Deferred.make(); - const prepared = yield* Deferred.make(); - const commitTrial = yield* Deferred.make(); - const statusCalled = yield* Deferred.make(); - const statusInterrupted = yield* Deferred.make(); - const cwd = "/auto-pull-project"; - const updatedAt = "2026-01-01T00:00:00.000Z"; - const snapshot = { - projects: [ - { - id: ProjectId.make("auto-pull-project"), - title: "Auto pull project", - workspaceRoot: cwd, - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: updatedAt, - updatedAt, - deletedAt: null, - }, - ], - updatedAt, - }; - const recovery = { - terminalizedRuns: 0, - stoppedSessions: 0, - closedRequests: 0, - retiredEffects: 0, - requeuedEffects: 0, - }; - const importSummary = { importedThreadCount: 0, importedMessageCount: 0 }; - const dependencies: Layer.Layer< - Layer.Services> - > = Layer.mergeAll( - Layer.mock(ServerConfig.ServerConfig)({ - ...(yield* ServerConfig.deriveServerPaths(cwd, undefined).pipe( - Effect.provide(Path.layer), - )), - baseDir: cwd, - logLevel: "Error", - traceMinLevel: "Info", - traceTimingEnabled: false, - traceBatchWindowMs: 200, - traceMaxBytes: 1024, - traceMaxFiles: 1, - otlpTracesUrl: undefined, - otlpMetricsUrl: undefined, - otlpLogsUrl: undefined, - otlpTracesExport: DEFAULT_SIGNAL_EXPORT, - otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, - otlpLogsExport: DEFAULT_SIGNAL_EXPORT, - otelEnvironment: OtelEnvironment.none, - staticDir: undefined, - devAllowedOrigins: [], - desktopBootstrapToken: undefined, - logWebSocketEvents: false, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - mode: "desktop", - cwd, - host: "localhost", - port: 3773, - devUrl: undefined, - noBrowser: true, - startupPresentation: "browser", - autoBootstrapProjectFromCwd: false, + Effect.gen(function* () { + const activation = yield* Deferred.make(); + const prepared = yield* Deferred.make(); + const commitTrial = yield* Deferred.make(); + const statusCalled = yield* Deferred.make(); + const statusInterrupted = yield* Deferred.make(); + const cwd = "/auto-pull-project"; + const updatedAt = "2026-01-01T00:00:00.000Z"; + const snapshot = { + projects: [ + { + id: ProjectId.make("auto-pull-project"), + title: "Auto pull project", + workspaceRoot: cwd, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: updatedAt, + updatedAt, + deletedAt: null, + }, + ], + updatedAt, + }; + const recovery = { + terminalizedRuns: 0, + stoppedSessions: 0, + closedRequests: 0, + retiredEffects: 0, + requeuedEffects: 0, + }; + const importSummary = { importedThreadCount: 0, importedMessageCount: 0 }; + const dependencies: Layer.Layer< + Layer.Services> + > = Layer.mergeAll( + Layer.mock(ServerConfig.ServerConfig)({ + ...(yield* ServerConfig.deriveServerPaths(cwd, undefined).pipe(Effect.provide(Path.layer))), + baseDir: cwd, + logLevel: "Error", + traceMinLevel: "Info", + traceTimingEnabled: false, + traceBatchWindowMs: 200, + traceMaxBytes: 1024, + traceMaxFiles: 1, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpLogsUrl: undefined, + otlpTracesExport: DEFAULT_SIGNAL_EXPORT, + otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, + otlpLogsExport: DEFAULT_SIGNAL_EXPORT, + otelEnvironment: OtelEnvironment.none, + staticDir: undefined, + devAllowedOrigins: [], + desktopBootstrapToken: undefined, + logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, + mode: "desktop", + cwd, + host: "localhost", + port: 3773, + devUrl: undefined, + noBrowser: true, + startupPresentation: "browser", + autoBootstrapProjectFromCwd: false, + }), + Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), + Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ + pendingThreadCount: Effect.succeed(0), + reconcileShells: Effect.succeed(importSummary), + importPendingTranscripts: Effect.succeed(importSummary), + }), + Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ + recover: Effect.succeed(recovery), + prepareForShutdown: Effect.void, + reconcile: () => Effect.succeed(recovery), + }), + Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }), + Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ + publish: (event) => Effect.succeed({ ...event, sequence: 1 }), + }), + Layer.mock(ServerSettings.ServerSettingsService)({ + start: Effect.void, + getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, defaultAutoPull: true }), + }), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId: EnvironmentId.make("auto-pull-environment"), + label: "Test environment", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, }), - Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), - Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ - pendingThreadCount: Effect.succeed(0), - reconcileShells: Effect.succeed(importSummary), - importPendingTranscripts: Effect.succeed(importSummary), - }), - Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ - recover: Effect.succeed(recovery), - prepareForShutdown: Effect.void, - reconcile: () => Effect.succeed(recovery), - }), - Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), - Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.never }), - Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ - publish: (event) => Effect.succeed({ ...event, sequence: 1 }), - }), - Layer.mock(ServerSettings.ServerSettingsService)({ - start: Effect.void, - getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, defaultAutoPull: true }), - }), - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ - environmentId: EnvironmentId.make("auto-pull-environment"), - label: "Test environment", - platform: { os: "darwin", arch: "arm64" }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }), - }), - Layer.mock(ProjectStore.ProjectStoreV2)({ - listShells: () => Effect.succeed(snapshot.projects), - }), - Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed(snapshot) }), - Layer.mock(ThreadManagement.ThreadManagementService)({}), - Layer.mock(ThreadLaunch.ThreadLaunchService)({}), - Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ - managed: true, - prepareTrial: Deferred.succeed(prepared, undefined).pipe( - Effect.andThen(Deferred.await(commitTrial)), - Effect.as(undefined), + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed(snapshot.projects), + }), + Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed(snapshot) }), + Layer.mock(ThreadManagement.ThreadManagementService)({}), + Layer.mock(ThreadLaunch.ThreadLaunchService)({}), + Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ + managed: true, + prepareTrial: Deferred.succeed(prepared, undefined).pipe( + Effect.andThen(Deferred.await(commitTrial)), + Effect.as(undefined), + ), + }), + Layer.mock(GitVcsDriver.GitVcsDriver)({ + statusDetails: (root) => + Deferred.succeed(statusCalled, root).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => Deferred.succeed(statusInterrupted, undefined)), ), - }), - Layer.mock(GitVcsDriver.GitVcsDriver)({ - statusDetails: (root) => - Deferred.succeed(statusCalled, root).pipe( - Effect.andThen(Effect.never), - Effect.onInterrupt(() => Deferred.succeed(statusInterrupted, undefined)), - ), - }), - // No provider logins, so startup records no owners. - FileSystem.layerNoop({}), - Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), - NodeCrypto.layer, - Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), - Layer.mock(ExternalLauncher.ExternalLauncher)({}), - Layer.mock(HttpServer.HttpServer)({ - address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), - }), - Path.layer, - ); + }), + // No provider logins, so startup records no owners. + FileSystem.layerNoop({}), + Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), + NodeCrypto.layer, + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(HttpServer.HttpServer)({ + address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), + }), + Path.layer, + ); - yield* Effect.gen(function* () { - const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; - yield* startup.markHttpListening; + yield* Effect.gen(function* () { + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + yield* startup.markHttpListening; - yield* Effect.raceFirst(Deferred.await(prepared), Deferred.await(statusCalled)); - expect(yield* Deferred.isDone(activation)).toBe(false); - expect(yield* Deferred.isDone(statusCalled)).toBe(false); - expect(yield* Deferred.isDone(prepared)).toBe(true); + yield* Effect.raceFirst(Deferred.await(prepared), Deferred.await(statusCalled)); + expect(yield* Deferred.isDone(activation)).toBe(false); + expect(yield* Deferred.isDone(statusCalled)).toBe(false); + expect(yield* Deferred.isDone(prepared)).toBe(true); - yield* Deferred.succeed(commitTrial, undefined); - yield* Deferred.await(activation); - expect(yield* Deferred.await(statusCalled)).toBe(cwd); - yield* startup.awaitCommandReady; - }).pipe( - Effect.provide( - ServerRuntimeStartup.layerWithOptions({ - activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid), - awaitAuxiliaryParked: Effect.void, - }).pipe(Layer.provide(dependencies)), - ), - Effect.provideService(ServerActivation, Deferred.await(activation)), - ); - expect(yield* Deferred.isDone(statusInterrupted)).toBe(true); - }), - ), + yield* Deferred.succeed(commitTrial, undefined); + yield* Deferred.await(activation); + expect(yield* Deferred.await(statusCalled)).toBe(cwd); + yield* startup.awaitCommandReady; + }).pipe( + Effect.provide( + ServerRuntimeStartup.layerWithOptions({ + activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid), + awaitAuxiliaryParked: Effect.void, + }).pipe(Layer.provide(dependencies)), + ), + Effect.provideService(ServerActivation, Deferred.await(activation)), + ); + expect(yield* Deferred.isDone(statusInterrupted)).toBe(true); + }), ); diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 49d2498dec..a290b0a4a7 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -52,109 +52,113 @@ it.effect.each([ "disabled-default", "launch-failure", "project-failure", + "project-refused", ] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) => - Effect.scoped( - Effect.gen(function* () { - const projectId = ProjectId.make("bootstrap-project"); - const instanceId = ProviderInstanceId.make( - scenario === "disabled-default" ? "custom" : "codex", - ); - const events: ServerLifecycleStreamEvent[] = []; - const recovery = { - terminalizedRuns: 0, - stoppedSessions: 0, - closedRequests: 0, - retiredEffects: 0, - requeuedEffects: 0, - }; - const imports = { importedThreadCount: 0, importedMessageCount: 0 }; - const dependencies = Layer.mergeAll( - NodeCrypto.layer, - Path.layer, - Layer.mock(ServerConfig.ServerConfig)({ - ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe( - Effect.provide(Path.layer), - )), - baseDir: "/bootstrap-project", - logLevel: "Error", - traceMinLevel: "Info", - traceTimingEnabled: false, - traceBatchWindowMs: 200, - traceMaxBytes: 1024, - traceMaxFiles: 1, - otlpTracesUrl: undefined, - otlpMetricsUrl: undefined, - otlpLogsUrl: undefined, - otlpTracesExport: DEFAULT_SIGNAL_EXPORT, - otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, - otlpLogsExport: DEFAULT_SIGNAL_EXPORT, - otelEnvironment: OtelEnvironment.none, - staticDir: undefined, - devAllowedOrigins: [], - desktopBootstrapToken: undefined, - logWebSocketEvents: false, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - mode: "web", - cwd: "/bootstrap-project", - host: "localhost", - port: 3773, - devUrl: undefined, - noBrowser: true, - startupPresentation: "browser", - autoBootstrapProjectFromCwd: true, - }), - Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), - Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ - pendingThreadCount: Effect.succeed(0), - reconcileShells: Effect.succeed(imports), - importPendingTranscripts: Effect.succeed(imports), - }), - Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ - recover: Effect.succeed(recovery), - prepareForShutdown: Effect.void, - reconcile: () => Effect.succeed(recovery), - }), - Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), - Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.never }), - Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ - publish: (event) => - Effect.sync(() => { - const published = { ...event, sequence: events.length + 1 }; - events.push(published); - return published; - }), - }), - Layer.mock(ServerSettings.ServerSettingsService)({ - start: Effect.void, - getSettings: Effect.succeed({ - ...DEFAULT_SERVER_SETTINGS, - defaultModelSelection: - scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null, - providerInstances: { - [instanceId]: { - driver: ProviderDriverKind.make("codex"), - enabled: false, - config: {}, - }, - }, + Effect.gen(function* () { + const projectId = ProjectId.make("bootstrap-project"); + const instanceId = ProviderInstanceId.make( + scenario === "disabled-default" ? "custom" : "codex", + ); + const events: ServerLifecycleStreamEvent[] = []; + const recovery = { + terminalizedRuns: 0, + stoppedSessions: 0, + closedRequests: 0, + retiredEffects: 0, + requeuedEffects: 0, + }; + const imports = { importedThreadCount: 0, importedMessageCount: 0 }; + const dependencies = Layer.mergeAll( + NodeCrypto.layer, + Path.layer, + Layer.mock(ServerConfig.ServerConfig)({ + ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe( + Effect.provide(Path.layer), + )), + baseDir: "/bootstrap-project", + logLevel: "Error", + traceMinLevel: "Info", + traceTimingEnabled: false, + traceBatchWindowMs: 200, + traceMaxBytes: 1024, + traceMaxFiles: 1, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpLogsUrl: undefined, + otlpTracesExport: DEFAULT_SIGNAL_EXPORT, + otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, + otlpLogsExport: DEFAULT_SIGNAL_EXPORT, + otelEnvironment: OtelEnvironment.none, + staticDir: undefined, + devAllowedOrigins: [], + desktopBootstrapToken: undefined, + logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, + mode: "web", + cwd: "/bootstrap-project", + host: "localhost", + port: 3773, + devUrl: undefined, + noBrowser: true, + startupPresentation: "browser", + autoBootstrapProjectFromCwd: true, + }), + Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), + Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ + pendingThreadCount: Effect.succeed(0), + reconcileShells: Effect.succeed(imports), + importPendingTranscripts: Effect.succeed(imports), + }), + Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ + recover: Effect.succeed(recovery), + prepareForShutdown: Effect.void, + reconcile: () => Effect.succeed(recovery), + }), + Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }), + Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ + publish: (event) => + Effect.sync(() => { + const published = { ...event, sequence: events.length + 1 }; + events.push(published); + return published; }), + }), + Layer.mock(ServerSettings.ServerSettingsService)({ + start: Effect.void, + getSettings: Effect.succeed({ + ...DEFAULT_SERVER_SETTINGS, + defaultModelSelection: + scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null, + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("codex"), + enabled: false, + config: {}, + }, + }, }), - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ - environmentId: EnvironmentId.make("bootstrap-environment"), - label: "Test environment", - platform: { os: "linux", arch: "x64" }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }), + }), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId: EnvironmentId.make("bootstrap-environment"), + label: "Test environment", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, }), - Layer.mock(ProjectStore.ProjectStoreV2)({}), - Layer.mock(ProjectService.ProjectService)({ - bootstrap: () => - scenario === "project-failure" - ? Effect.die("project bootstrap failed") + }), + Layer.mock(ProjectStore.ProjectStoreV2)({}), + Layer.mock(ProjectService.ProjectService)({ + bootstrap: () => + scenario === "project-failure" + ? Effect.die("project bootstrap failed") + : scenario === "project-refused" + ? Effect.fail( + new ProjectService.ProjectInvalidError({ projectId, detail: "refused folder" }), + ) : Effect.succeed({ created: true, project: { @@ -173,107 +177,105 @@ it.effect.each([ : null, }, }), - }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - listActiveShellIndex: () => Effect.succeed([]), - }), - Layer.mock(ThreadLaunch.ThreadLaunchService)({ - launch: (input) => { - assert.equal(input.modelSelection.instanceId, instanceId); - return scenario === "launch-failure" - ? Effect.fail( - new ThreadLaunch.ThreadLaunchError({ - operation: "create-thread", - commandId: CommandId.make("bootstrap-command"), - projectId, - cause: "test launch failure", - }), - ) - : Effect.fail( - new ThreadManagement.ThreadManagementProviderInstanceDisabledError({ - projectId, - instanceId, - }), - ); - }, - }), - Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ - managed: false, - prepareTrial: Effect.undefined, - }), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - // No provider logins, so startup records no owners. - FileSystem.layerNoop({}), - Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), - Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), - Layer.mock(ExternalLauncher.ExternalLauncher)({}), - Layer.mock(HttpServer.HttpServer)({ - address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), - }), - ); - yield* Effect.gen(function* () { - const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; - yield* startup.markHttpListening; - const ready = yield* Effect.exit(startup.awaitCommandReady); - assert.equal(Exit.isSuccess(ready), scenario !== "project-failure"); - const welcome = events.find((event) => event.type === "welcome"); - if (scenario === "project-failure") { - assert.isUndefined(welcome); - } else { - assert.isDefined(welcome); - if (welcome?.type === "welcome") { - assert.equal(welcome.payload.bootstrapProjectId, projectId); - assert.isUndefined(welcome.payload.bootstrapThreadId); - } + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + listActiveShellIndex: () => Effect.succeed([]), + }), + Layer.mock(ThreadLaunch.ThreadLaunchService)({ + launch: (input) => { + assert.equal(input.modelSelection.instanceId, instanceId); + return scenario === "launch-failure" + ? Effect.fail( + new ThreadLaunch.ThreadLaunchError({ + operation: "create-thread", + commandId: CommandId.make("bootstrap-command"), + projectId, + cause: "test launch failure", + }), + ) + : Effect.fail( + new ThreadManagement.ThreadManagementProviderInstanceDisabledError({ + projectId, + instanceId, + }), + ); + }, + }), + Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ + managed: false, + prepareTrial: Effect.undefined, + }), + Layer.mock(GitVcsDriver.GitVcsDriver)({}), + // No provider logins, so startup records no owners. + FileSystem.layerNoop({}), + Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(HttpServer.HttpServer)({ + address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), + }), + ); + yield* Effect.gen(function* () { + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + yield* startup.markHttpListening; + const ready = yield* Effect.exit(startup.awaitCommandReady); + assert.equal(Exit.isSuccess(ready), scenario !== "project-failure"); + const welcome = events.find((event) => event.type === "welcome"); + if (scenario === "project-failure") { + assert.isUndefined(welcome); + } else { + assert.isDefined(welcome); + if (welcome?.type === "welcome") { + assert.equal( + welcome.payload.bootstrapProjectId, + scenario === "project-refused" ? undefined : projectId, + ); + assert.isUndefined(welcome.payload.bootstrapThreadId); } - }).pipe( - Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))), - Effect.provideService(ServerActivation, Effect.never), - ); - }), - ), + } + }).pipe( + Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))), + Effect.provideService(ServerActivation, Effect.never), + ); + }), ); it.effect("queues commands until startup signals readiness", () => - Effect.scoped( - Effect.gen(function* () { - const gate = yield* ServerRuntimeStartup.makeCommandGate; - const count = yield* Ref.make(0); - const queued = yield* gate - .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1)) - .pipe(Effect.forkScoped); + Effect.gen(function* () { + const gate = yield* ServerRuntimeStartup.makeCommandGate; + const count = yield* Ref.make(0); + const queued = yield* gate + .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1)) + .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.equal(yield* Ref.get(count), 0); - yield* gate.signalCommandReady; - assert.equal(yield* Fiber.join(queued), 1); - }), - ), + yield* Effect.yieldNow; + assert.equal(yield* Ref.get(count), 0); + yield* gate.signalCommandReady; + assert.equal(yield* Fiber.join(queued), 1); + }), ); it.effect("enqueueCommand fails queued work when readiness fails", () => - Effect.scoped( - Effect.gen(function* () { - const commandGate = yield* ServerRuntimeStartup.makeCommandGate; - const failure = yield* Deferred.make(); + Effect.gen(function* () { + const commandGate = yield* ServerRuntimeStartup.makeCommandGate; + const failure = yield* Deferred.make(); - const queuedCommandFiber = yield* commandGate - .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) - .pipe(Effect.forkScoped); + const queuedCommandFiber = yield* commandGate + .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) + .pipe(Effect.forkScoped); - yield* commandGate.failCommandReady( - new ServerRuntimeStartup.ServerRuntimeStartupError({ - mode: "web", - host: "127.0.0.1", - port: 3773, - cause: new Error("test startup failure"), - }), - ); + yield* commandGate.failCommandReady( + new ServerRuntimeStartup.ServerRuntimeStartupError({ + mode: "web", + host: "127.0.0.1", + port: 3773, + cause: new Error("test startup failure"), + }), + ); - const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); - assert.equal(error.message, "Server runtime startup failed before command readiness."); - }), - ), + const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); + assert.equal(error.message, "Server runtime startup failed before command readiness."); + }), ); it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () => diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 57fa8fbc56..c95ec3781b 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -12,6 +12,7 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import * as Cause from "effect/Cause"; import * as Console from "effect/Console"; @@ -48,12 +49,7 @@ import * as ServerSettings from "./serverSettings.ts"; import { forkParked, forkParkedFiber } from "./serverActivation.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import { - formatHeadlessServeOutput, - formatHostForUrl, - isWildcardHost, - issueHeadlessServeAccessInfo, -} from "./startupAccess.ts"; +import { formatHeadlessServeOutput, issueHeadlessServeAccessInfo } from "./startupAccess.ts"; export class ServerRuntimeStartupError extends Schema.TaggedError()( "ServerRuntimeStartupError", @@ -241,12 +237,24 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () { if (serverConfig.autoBootstrapProjectFromCwd) { const threadModelSelection = getAutoBootstrapThreadModelSelection(); - const { project } = yield* projects.bootstrap({ - commandId: CommandId.make(yield* randomUUID), - projectId: ProjectId.make(yield* randomUUID), - title: path.basename(serverConfig.cwd) || "project", - workspaceRoot: serverConfig.cwd, - }); + const bootstrapped = yield* projects + .bootstrap({ + commandId: CommandId.make(yield* randomUUID), + projectId: ProjectId.make(yield* randomUUID), + title: path.basename(serverConfig.cwd) || "project", + workspaceRoot: serverConfig.cwd, + }) + .pipe( + // A folder the project rules refuse must not stop the server from starting there. + Effect.catchTags({ + ProjectInvalidError: (error) => + Effect.logWarning("Skipped bootstrap project", { detail: error.detail }).pipe( + Effect.as(undefined), + ), + }), + ); + if (bootstrapped === undefined) return {} satisfies AutoBootstrapWelcomeTargets; + const { project } = bootstrapped; const existingThread = (yield* threads.listActiveShellIndex()).find( (thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage), ); diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts index 49d9a48f99..fc5c85a2a9 100644 --- a/apps/server/src/serverRuntimeState.ts +++ b/apps/server/src/serverRuntimeState.ts @@ -5,9 +5,9 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; +import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification"; import packageJson from "../package.json" with { type: "json" }; import type * as ServerConfig from "./config.ts"; -import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts"; export const PersistedServerRuntimeState = Schema.Struct({ version: Schema.Literal(1), @@ -192,3 +192,16 @@ export const readPersistedServerRuntimeState = Effect.fn( ), }), ); + +/** + * The runtime record, only while its server process is alive. Read this before sending + * credentials to the recorded origin: a killed server leaves its record behind, and + * another process may own its port by now. + */ +export const readLiveServerRuntimeState = Effect.fn( + "serverRuntimeState.readLiveServerRuntimeState", +)((path: string) => + readPersistedServerRuntimeState(path).pipe( + Effect.map(Option.filter((state) => isProcessAlive(state.pid))), + ), +); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 347b43dd6f..873649cb16 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1,3 +1,4 @@ +import { deriveProviderInstanceConfigMap } from "./provider/ProviderInstanceRegistryHydration.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { @@ -539,6 +540,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" (yield* serverSettings.getSettings).providerInstances[instanceId]?.displayName ?? "", ), ); + + // An inherited Object.prototype member is not an instance that already exists. + for (const name of ["constructor", "toString", "valueOf"]) { + const prototypeNamedId = ProviderInstanceId.make(name); + const created = yield* serverSettings.updateProviderInstance({ + operation: "create", + instanceId: prototypeNamedId, + instance: { driver: ProviderDriverKind.make("codex") }, + }); + assert.isTrue(Object.hasOwn(created.providerInstances, prototypeNamedId)); + } }).pipe(Effect.provide(layerServerSettings())), ); @@ -1457,7 +1469,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" { kind: "eas", id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", accessToken: "expo-secret", maxSessionMinutes: 30, idleMinutes: 10, @@ -1774,7 +1786,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" { kind: "eas", id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", accessToken: easReference, maxSessionMinutes: 30, idleMinutes: 10, @@ -1894,7 +1906,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" { kind: "eas", id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", accessToken: personal("Expo/token"), maxSessionMinutes: 30, idleMinutes: 10, @@ -2063,6 +2075,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" }); const environment = yield* resolveProviderInstanceTerminalEnvironment({ + deriveProviderInstanceConfigMap, serverSettings, path, rawProviderInstanceId: instanceId, diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 251becba12..4dc30d29a6 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -237,7 +237,7 @@ function ensureProviderInstanceMutationAllowed( ): Effect.Effect { if ( mutation.operation === "create" && - settings.providerInstances[mutation.instanceId] !== undefined + Object.hasOwn(settings.providerInstances, mutation.instanceId) ) { return Effect.fail( new ServerSettingsError({ diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index 22ea8ae882..a38072d198 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -235,7 +235,7 @@ function mapSecretFieldGroups( ) as EasDeviceHostConfig, ); - // Its own prefix: an EAS and a Simlock host may share an id. + // Its own prefix: an Expo and a Simlock host may share an id. const simlockDeviceHosts = settings.simlockDeviceHosts.map( (host) => mapFields( diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts index 2b76ccb09b..efa3aa00e5 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts @@ -1,10 +1,22 @@ -import { SourceControlProviderKind, VcsProcessSpawnError } from "@t3tools/contracts"; +import { + SourceControlProviderKind, + type VcsError, + VcsProcessExitError, + VcsProcessSpawnError, + VcsProcessTimeoutError, +} from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import { providerAuth } from "@t3tools/source-control-core/server/discovery"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import { + providerAuth, + type SourceControlProviderDiscoverySpec, +} from "@t3tools/source-control-core/server/discovery"; import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import { fakeDiscovery, @@ -29,7 +41,29 @@ const run = ( SourceControlHost.SourceControlProcessInput, "operation" | "command" | "args" | "cwd" >, -): Effect.Effect => { +): Effect.Effect => { + const context = { operation: input.operation, command: input.command, cwd: input.cwd }; + if (input.command === "slow-cli") { + return Effect.fail(new VcsProcessTimeoutError({ ...context, timeoutMs: 5_000 })); + } + if (input.command === "broken-cli") { + return Effect.fail( + new VcsProcessExitError({ ...context, exitCode: 1, detail: "broken-cli: bad install" }), + ); + } + if (input.command === "absent-cli") { + return Effect.fail( + new VcsProcessSpawnError({ + ...context, + cause: PlatformError.systemError({ + _tag: "NotFound", + module: "ChildProcess", + method: "spawn", + pathOrDescriptor: input.command, + }), + }), + ); + } if (input.args[0] === "--version") { return input.command === "missing-cli" ? Effect.fail( @@ -47,29 +81,37 @@ const run = ( ); }; -const cliDiscovery = (name: string) => ({ +const cliDiscovery = ( + name: string, + executable = name === "beta" ? "missing-cli" : `${name}-cli`, +) => ({ type: "cli" as const, kind: kind(name), label: name, installHint: `Install ${name}.`, - executable: name === "beta" ? "missing-cli" : `${name}-cli`, + executable, versionArgs: ["--version"], authArgs: ["auth", "status"], parseAuth: ({ stdout }: { readonly stdout: string }) => providerAuth({ status: "authenticated", account: /as (\S+)/.exec(stdout)?.[1] }), }); -const layerDiscovery = (runProcess = run) => +const defaultDiscoveries = [ + cliDiscovery("alpha"), + cliDiscovery("beta"), + fakeDiscovery("gamma", { + probeAuth: Effect.succeed(providerAuth({ status: "authenticated", account: "api-user" })), + }), +]; + +const layerDiscovery = ( + runProcess = run, + discoveries: ReadonlyArray = defaultDiscoveries, +) => Layer.effect( SourceControlProviderRegistry.SourceControlProviderRegistry, SourceControlProviderRegistry.makeWithProviders( - [ - cliDiscovery("alpha"), - cliDiscovery("beta"), - fakeDiscovery("gamma", { - probeAuth: Effect.succeed(providerAuth({ status: "authenticated", account: "api-user" })), - }), - ].map((discovery) => ({ + discoveries.map((discovery) => ({ kind: discovery.kind, provider: fakeSourceControlProvider(discovery.kind), discovery, @@ -133,6 +175,49 @@ it.effect("reports every hosting integration in registry order with its sign-in" }).pipe(Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery())))), ); +it.effect("explains a CLI whose version probe failed instead of advising an install", () => + Effect.gen(function* () { + const discovery = yield* SourceControlDiscovery.SourceControlDiscovery; + const result = yield* discovery.discover; + const item = (name: string) => { + const found = result.sourceControlProviders.find((entry) => entry.kind === kind(name)); + assert.isDefined(found); + return found; + }; + const authDetail = (name: string) => Option.getOrElse(item(name).auth.detail, () => ""); + + assert.notInclude(item("slow").installHint, "Install slow."); + assert.include(item("slow").installHint, "timed out after 5000ms"); + assert.strictEqual(authDetail("slow"), item("slow").installHint); + + assert.notInclude(item("broken").installHint, "Install broken."); + assert.include(item("broken").installHint, "exited with status 1"); + assert.strictEqual(authDetail("broken"), item("broken").installHint); + + assert.strictEqual(item("absent").installHint, "Install absent."); + + const git = result.versionControlSystems.find((entry) => entry.kind === "git"); + assert.isDefined(git); + assert.notInclude(git.installHint, "Install Git from"); + assert.include(git.installHint, "`git --version` exited with status 1"); + }).pipe( + Effect.provide( + SourceControlDiscovery.layer.pipe( + Layer.provide( + layerDiscovery( + (input) => run(input.command === "git" ? { ...input, command: "broken-cli" } : input), + [ + cliDiscovery("slow", "slow-cli"), + cliDiscovery("broken", "broken-cli"), + cliDiscovery("absent", "absent-cli"), + ], + ), + ), + ), + ), + ), +); + it.effect.each(["darwin", "linux"] as const)( "names incompatible executables only on macOS (%s)", (platform) => { @@ -171,3 +256,63 @@ it.effect.each(["darwin", "linux"] as const)( ); }, ); + +// Spawns a real login shell and `jj`, so it runs on wall-clock time; the fixture shell is POSIX sh. +it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "rescans with tools the login shell gained after the server started", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-login-shell-" }); + const home = path.join(root, "home"); + const fakebin = path.join(home, "fakebin"); + const loginShell = path.join(root, "loginsh"); + yield* fs.makeDirectory(fakebin, { recursive: true }); + // Stands in for `$SHELL -ilc ` and sources only the fixture + // profile, so the host's own shell init cannot change the result. + yield* fs.writeFileString( + loginShell, + `#!/bin/sh\nexport HOME=${home}\n. "$HOME/.profile"\nshift\nexec /bin/sh -c "$1"\n`, + { mode: 0o755 }, + ); + const env = yield* HostProcess.Environment; + yield* Effect.acquireRelease( + Effect.sync(() => { + const saved = { PATH: env.PATH, SHELL: env.SHELL }; + env.SHELL = loginShell; + return saved; + }), + (saved) => + Effect.sync(() => { + env.PATH = saved.PATH; + if (saved.SHELL === undefined) delete env.SHELL; + else env.SHELL = saved.SHELL; + }), + ); + + // The user installs a tool after launch; their login shell now finds it. + yield* fs.writeFileString(path.join(fakebin, "jj"), "#!/bin/sh\necho 'jj 0.99.0-test'\n", { + mode: 0o755, + }); + yield* fs.writeFileString(path.join(home, ".profile"), 'export PATH="$HOME/fakebin:$PATH"\n'); + + const discovery = yield* SourceControlDiscovery.SourceControlDiscovery; + const jj = (yield* discovery.discover).versionControlSystems.find( + (item) => item.kind === "jj", + ); + + assert.deepStrictEqual( + { status: jj?.status, version: jj?.version }, + { status: "available", version: Option.some("jj 0.99.0-test") }, + ); + }).pipe( + Effect.scoped, + Effect.provide( + SourceControlDiscovery.layer.pipe( + Layer.provide(VcsProcess.layer), + Layer.provideMerge(layerDiscovery()), + ), + ), + ), +); diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.ts b/apps/server/src/sourceControl/SourceControlDiscovery.ts index 0657e90de8..e69f0d3761 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.ts @@ -4,16 +4,19 @@ import { type VcsDriverKind, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +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 ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ServerConfig from "../config.ts"; +import { refreshPathFromLoginShell } from "../os-jank.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import { detailFromCause, + failedProbeHint, firstNonEmptyLine, - unavailableInstallHint, } from "@t3tools/source-control-core/server/discovery"; import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts"; @@ -73,6 +76,14 @@ export const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const process = yield* VcsProcess.VcsProcess; const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // Discovery re-reads the login shell so a tool installed since launch + // resolves here and in every later spawn. Thread views, the palette and + // mobile also run discovery, so one interactive shell serves a short window. + const refreshPath = yield* refreshPathFromLoginShell().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.cachedWithTTL(Duration.seconds(10)), + ); const probe = ( input: VcsProbe & { readonly kind: Kind }, @@ -108,7 +119,7 @@ export const make = Effect.gen(function* () { ), Effect.catch((cause) => Effect.gen(function* () { - const installHint = yield* unavailableInstallHint(executable, input.installHint, cause); + const installHint = yield* failedProbeHint(input, cause); return { kind: input.kind, label: input.label, @@ -125,13 +136,16 @@ export const make = Effect.gen(function* () { }; return SourceControlDiscovery.of({ - discover: Effect.all({ - versionControlSystems: Effect.all( - VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray>, - { concurrency: "unbounded" }, - ), - sourceControlProviders: sourceControlProviders.discover, - }), + discover: Effect.andThen( + refreshPath, + Effect.all({ + versionControlSystems: Effect.all( + VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray>, + { concurrency: "unbounded" }, + ), + sourceControlProviders: sourceControlProviders.discover, + }), + ), }); }); diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts index c532d93e81..9d472fe6e7 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts @@ -283,7 +283,7 @@ it.effect( url, ); } - }).pipe(Effect.scoped), + }), ); it.effect("does not refine a context whose server address is empty", () => diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts index 326b7931da..bebdeef9ec 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts @@ -3,12 +3,15 @@ import * as NodePath from "@effect/platform-node/NodePath"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; import { ChildProcessSpawner } from "effect/process"; +import * as TestClock from "effect/testing/TestClock"; import { GitCommandError, @@ -75,6 +78,7 @@ function layer(input: { Layer.provide( Layer.mock(GitVcsDriver.GitVcsDriver)({ execute: () => Effect.succeed(processOutput()), + invalidateRefs: () => Effect.void, ensureRemote: () => Effect.succeed("origin"), pushCurrentBranch: () => Effect.succeed({ @@ -217,7 +221,7 @@ it.effect.each(["--bare", "source.git"])( }); assert.strictEqual(result.cwd, destinationPath); assert.isTrue(yield* fs.exists(path.join(destinationPath, ".git"))); - }).pipe(Effect.provide(layer({ git: { execute: git.execute } }))); + }).pipe(Effect.provide(layer({ git }))); }).pipe( Effect.provide( GitVcsDriver.layer.pipe( @@ -232,6 +236,72 @@ it.effect.each(["--bare", "source.git"])( ), ); +it.effect.each([ + { readsWhen: "before git creates the repository", readBeforeInit: true }, + { readsWhen: "while HEAD is unborn", readBeforeInit: false }, +])("lists the cloned branches after a ref list was read $readsWhen", ({ readBeforeInit }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const git = yield* GitVcsDriver.GitVcsDriver; + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-refs-" }); + const source = path.join(parent, "source"); + const destinationPath = path.join(parent, "checkout"); + const run = (cwd: string, args: ReadonlyArray) => + git.execute({ operation: "test.git", cwd, args }); + yield* run(parent, ["init", "--initial-branch=staging", source]); + yield* run(source, [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "--allow-empty", + "-m", + "init", + ]); + const refNames = git + .listRefs({ cwd: destinationPath }) + .pipe(Effect.map((result) => result.refs.map((ref) => ref.name))); + let duringClone: ReadonlyArray | null = null; + // Stands in for git clone so the read lands at a chosen point inside it. + const cloneInTwoSteps = Effect.gen(function* () { + yield* fs.makeDirectory(destinationPath).pipe(Effect.orDie); + if (readBeforeInit) duringClone = yield* refNames; + yield* run(parent, ["init", "--initial-branch=staging", destinationPath]); + if (!readBeforeInit) duringClone = yield* refNames; + return yield* run(destinationPath, ["pull", source, "staging"]); + }); + yield* Effect.gen(function* () { + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; + yield* service.cloneRepository({ remoteUrl: source, destinationPath }); + }).pipe( + Effect.provide( + layer({ + git: { + ...git, + execute: (input) => (input.args[0] === "clone" ? cloneInTwoSteps : git.execute(input)), + }, + }), + ), + ); + + assert.deepStrictEqual(duringClone, []); + assert.deepStrictEqual(yield* refNames, ["staging"]); + }).pipe( + Effect.provide( + GitVcsDriver.layer.pipe( + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-clone-refs-config-", + }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + it.effect("reports clone progress from git's stderr and keeps its error text on failure", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -292,6 +362,65 @@ it.effect("reports clone progress from git's stderr and keeps its error text on }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); +it.effect("says a clone that ran out of time timed out, not git's last remote line", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fs.makeTempDirectoryScoped({ + prefix: "t3-source-control-clone-timeout-", + }); + const started = yield* Deferred.make(); + const clone = yield* Effect.gen(function* () { + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; + return yield* Effect.flip( + service.cloneRepository({ + remoteUrl: CLONE_URLS.url, + destinationPath: path.join(parent, "t3code"), + }), + ); + }).pipe( + Effect.provide( + layer({ + git: { + // Like the real driver: the transfer outlives its deadline and git's last line is + // a remote summary. + execute: (input) => + Effect.gen(function* () { + yield* ( + input.progress?.onStderrLine?.( + "remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0", + ) ?? Effect.void + ); + yield* Deferred.succeed(started, undefined); + return yield* Effect.never; + }).pipe( + Effect.timeoutOrElse({ + duration: input.timeoutMs ?? Infinity, + orElse: () => + Effect.fail( + new GitCommandError({ + operation: input.operation, + command: "git", + cwd: input.cwd, + detail: "Git command timed out.", + }), + ), + }), + ), + }, + }), + ), + Effect.forkChild, + ); + + yield* Deferred.await(started); + yield* TestClock.adjust("2 minutes"); + const error = yield* Fiber.join(clone); + + assert.match(error.detail, /timed out/i); + }).pipe(Effect.provide(NodeServices.layer)), +); + function rejectingSsh( urls: Array, httpsFails: boolean, diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts index 07c7b28d82..b4b2dc0e92 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts @@ -1,4 +1,5 @@ import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -349,12 +350,15 @@ export const make = Effect.gen(function* () { }; // Git misreads @ in a pathless URL's query as userinfo and echoes its suffix as the host. const normalizedCloneUrl = cloneUrl.replace(/^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)\?/i, "$1/?"); - yield* git + const provider = input.provider ?? SourceControlProviderKind.make("unknown"); + const timeoutMs = options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs; + const clone = git .execute({ operation: "SourceControlRepositoryService.cloneRepository", cwd: path.dirname(destinationPath), args: ["clone", "--progress", "--", normalizedCloneUrl, path.basename(destinationPath)], - timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs, + // The deadline is applied below so a timeout is reported as one, not as git's last line. + timeoutMs: null, // Buffered output is unused and progress can be huge; cap it while retaining line callbacks. maxOutputBytes: 256 * 1024, appendTruncationMarker: true, @@ -367,7 +371,7 @@ export const make = Effect.gen(function* () { (cause) => new SourceControlRepositoryError({ operation: "cloneRepository", - provider: input.provider ?? SourceControlProviderKind.make("unknown"), + provider, detail: stderrTail.length > 0 ? stderrTail.join(" ") @@ -376,6 +380,21 @@ export const make = Effect.gen(function* () { }), ), ); + if (timeoutMs === null) return yield* clone; + // Interrupting the clone closes the scope that owns git, which kills it. + return yield* clone.pipe( + Effect.timeoutOrElse({ + duration: timeoutMs, + orElse: () => + Effect.fail( + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider, + detail: `The clone timed out after ${Duration.format(Duration.millis(timeoutMs))}.`, + }), + ), + }), + ); }); const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* ( @@ -410,6 +429,8 @@ export const make = Effect.gen(function* () { ), ); + // A ref list read while the clone ran saw an unborn HEAD and no refs. + yield* git.invalidateRefs(prepared.destinationPath); return { cwd: prepared.destinationPath, remoteUrl, diff --git a/apps/server/src/speech/SpeechService.test.ts b/apps/server/src/speech/SpeechService.test.ts index 8d980f2846..3f580b0743 100644 --- a/apps/server/src/speech/SpeechService.test.ts +++ b/apps/server/src/speech/SpeechService.test.ts @@ -449,14 +449,19 @@ it.effect("honors exact aliases and phrase boundaries in batch and streamed text { term: "GitHub", aliases: [] }, { term: "McDonald’s", aliases: [] }, { term: "King’s Cross", aliases: [] }, + { term: "C#", aliases: [] }, + { term: "React", aliases: ["瑞安特"] }, + { term: "Kubernetes", aliases: [] }, ], }; const spoken = 'a test with a i and ay eye. Robert, Roberts. "the publisher" and the publisher. (git hub), git (hub). ' + - "git hub's API, git hub’s API, git’s hub, mac donald's menu, king's cross."; + "git hub's API, git hub’s API, git’s hub, mac donald's menu, king's cross. vitamin c and plan c. " + + "我用github和瑞安特,部署到kubernetis上。Robert用git hub。githubで管理する。"; const expected = "a test with AI and AI. Bob, Roberts. O'Reilly and the publisher. (GitHub), git (hub). " + - "GitHub's API, GitHub’s API, git’s hub, McDonald’s menu, King’s Cross."; + "GitHub's API, GitHub’s API, git’s hub, McDonald’s menu, King’s Cross. vitamin c and plan c. " + + "我用GitHub和React,部署到Kubernetes上。Bob用GitHub。GitHubで管理する。"; native.transcribe.mockResolvedValueOnce({ text: spoken }); native.finish.mockResolvedValueOnce(spoken); expect(yield* speech.transcribe(pcm(), options)).toBe(expected); @@ -533,6 +538,24 @@ it.effect("unloads after the chosen idle period and reloads on the next recordin ); it.effect.each([ + { + cue: undefined, + remove: true, + text: "First paragraph.\n\nSecond paragraph.", + expected: "First paragraph.\n\nSecond paragraph.", + }, + { + cue: undefined, + remove: true, + text: "First um\n\nuh Second.", + expected: "First\n\nSecond.", + }, + { + cue: undefined, + remove: true, + text: "First um\r\n\r\nuh Second.", + expected: "First\r\n\r\nSecond.", + }, { cue: "um", remove: true, text: "Make it red, um, blue.", expected: "Make it red, um, blue." }, { cue: "uh no", diff --git a/apps/server/src/speech/SpeechService.ts b/apps/server/src/speech/SpeechService.ts index b4ae198b94..58fc6a9e1f 100644 --- a/apps/server/src/speech/SpeechService.ts +++ b/apps/server/src/speech/SpeechService.ts @@ -582,8 +582,9 @@ const make = Effect.gen(function* () { const silenceModelPath = Effect.fn("SpeechService.silenceModelPath")(function* ( loaded: LoadedModel, options: SpeechTranscriptionOptions, + nativeStreaming: boolean, ) { - if (!options.speechSilenceFiltering && (loaded.supportsStreaming || loaded.supportsLongForm)) + if (!options.speechSilenceFiltering && (nativeStreaming || loaded.supportsLongForm)) return undefined; return yield* acquireSilenceModel("recording"); }); @@ -619,7 +620,7 @@ const make = Effect.gen(function* () { ), catch: (cause) => speechError("model preparation", cause), }); - const vadPath = yield* silenceModelPath(loaded, options); + const vadPath = yield* silenceModelPath(loaded, options, false); const dictionary = normalizeSpeechCustomWords(options.speechCustomWords); const customWords = dictionary.map(({ term }) => term); // The vocabulary capability guarantees plain transcription, not translation. @@ -755,7 +756,7 @@ const make = Effect.gen(function* () { loadModel(modelPath, definition, signal, settings.speechAcceleration), ); loaded = streamModel; - const vadPath = yield* silenceModelPath(streamModel, options); + const vadPath = yield* silenceModelPath(streamModel, options, streamModel.supportsStreaming); let translateToEnglish = false; const beginStream = async () => { translateToEnglish = diff --git a/apps/server/src/speech/customWords.ts b/apps/server/src/speech/customWords.ts index e788c9188a..981632c461 100644 --- a/apps/server/src/speech/customWords.ts +++ b/apps/server/src/speech/customWords.ts @@ -1,5 +1,11 @@ import type { SpeechCustomWords } from "@t3tools/contracts"; +// These scripts are written without spaces, so a neighbor in one of them still ends a word. +const UNSPACED_SCRIPTS = "\\p{scx=Han}\\p{scx=Hiragana}\\p{scx=Katakana}"; +const LETTER = `[[\\p{L}\\p{M}\\p{N}]--[${UNSPACED_SCRIPTS}]]`; +const WORD_CHARACTER = `[[\\p{L}\\p{M}\\p{N}\\p{Pc}]--[${UNSPACED_SCRIPTS}]]`; +const TOKEN = new RegExp(`${LETTER}(?:[^\\s${UNSPACED_SCRIPTS}]*${LETTER})?`, "gv"); + /** Fuzzy-matches preferred terms and rewrites aliases to their preferred spelling. */ export function makeSpeechTextCorrector( words: readonly string[], @@ -71,8 +77,14 @@ export function makeSpeechTextCorrector( const customWordKeys = (words: readonly string[]): CustomWordKey[] => words.flatMap((word) => { - const keys = [matchKey(word)]; - if (word.includes("&")) keys.push(matchKey(word.replaceAll("&", " and "))); + const sources = [word]; + if (word.includes("&")) sources.push(word.replaceAll("&", " and ")); + const keys = sources.flatMap((source) => { + const key = matchKey(source); + // A term that loses its symbols to one letter (C# -> c) would claim every standalone letter. + const lostSymbols = key !== source.replace(/\s+/gu, "").toLocaleLowerCase(); + return key.length < 2 && lostSymbols ? [] : [key]; + }); return [...new Set(keys)].filter(isAsciiKey).map((key) => ({ word, key })); }); @@ -106,7 +118,7 @@ export function makeSpeechTextCorrector( const apply = (text: string): string => { if (keys.length === 0) return text; // Leave surrounding punctuation in the source; only horizontal whitespace can join words. - const tokens = [...text.matchAll(/[\p{L}\p{M}\p{N}](?:\S*[\p{L}\p{M}\p{N}])?/gu)] + const tokens = [...text.matchAll(TOKEN)] .filter(([word]) => /^[\p{L}\p{M}\p{N}'’-]+$/u.test(word)) .map((match) => ({ value: match[0], @@ -162,10 +174,9 @@ export function makeSpeechTextCorrector( const lookup = new Map( spellings.map(({ spelling, term }) => [spelling.toLocaleLowerCase(), term]), ); - const word = "[\\p{L}\\p{M}\\p{N}\\p{Pc}]"; const pattern = new RegExp( - `(? escapePattern(spelling)).join("|")})(?!${word})`, - "giu", + `(? escapePattern(spelling)).join("|")})(?!${WORD_CHARACTER})`, + "giv", ); return (text: string) => { let output = ""; diff --git a/apps/server/src/speech/fillerWords.ts b/apps/server/src/speech/fillerWords.ts index 5061341833..e939e275fb 100644 --- a/apps/server/src/speech/fillerWords.ts +++ b/apps/server/src/speech/fillerWords.ts @@ -38,5 +38,8 @@ export function removeSpeechFillerWords( "giu", ); const filtered = text.replace(pattern, (_match, cue: string | undefined) => cue ?? ""); - return filtered.replace(/\s{2,}/g, " ").trim(); + return filtered + .replace(/[^\S\r\n]{2,}/g, " ") + .replace(/[^\S\r\n]*([\r\n])[^\S\r\n]*/g, "$1") + .trim(); } diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index d86f77fbdb..07f2fe6b99 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -269,7 +269,7 @@ effectIt.effect( handler(new Request("http://localhost/api/voice/models"), context), ); expect(yield* Effect.promise(() => listed.text())).not.toContain("/home/someone"); - }).pipe(Effect.scoped), + }), ); effectIt.effect.each([ @@ -361,5 +361,5 @@ effectIt.effect.each([ code: "invalid_request", reason, }); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/speech/native.test.ts b/apps/server/src/speech/native.test.ts index 8712c63ed3..cb7254891a 100644 --- a/apps/server/src/speech/native.test.ts +++ b/apps/server/src/speech/native.test.ts @@ -1,4 +1,8 @@ // @effect-diagnostics nodeBuiltinImport:off - verifies isolated native worker processes and their exit events. +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + import { expect, it } from "vite-plus/test"; import { loadNativeSpeechModel } from "./native.ts"; @@ -155,6 +159,37 @@ it("kills a hung streaming feed without waiting for native cleanup", async () => await model.dispose(); await rejected; }); + +it("skips process exit teardown when the backend dies during native inference", async () => { + const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-speech-orphan-")); + const marker = NodePath.join(directory, "exit-teardown"); + // The exit hook stands in for native atexit teardown; the interval for the threadpool call. + const model = await loadNativeSpeechModel( + "unused.gguf", + new AbortController().signal, + streamingFixture(`async () => { + const { writeFileSync } = process.getBuiltinModule("node:fs"); + process.once("exit", () => writeFileSync(${JSON.stringify(marker)}, "ran")); + setInterval(() => {}, 1 << 30); + process.disconnect(); + return await new Promise(() => {}); + }`), + ); + try { + await model.begin({ timestamps: "none" }, false); + await expect(model.feed(new Float32Array(512).fill(0.25))).rejects.toThrow( + "Speech process exited", + ); + expect( + NodeFS.existsSync(marker), + "orphaned worker ran exit teardown while native inference was in flight", + ).toBe(false); + } finally { + await model.dispose(); + NodeFS.rmSync(directory, { recursive: true, force: true }); + } +}); + const vadFixture = ({ streaming = false, failVad = false, @@ -264,6 +299,28 @@ it("decodes complete stable chunks before Stop and returns the ordered final tai } }); +it("uses bounded offline chunks for a native streaming model without opening a session", async () => { + const moduleUrl = `data:text/javascript,${encodeURIComponent(` + export const TranscribeModel = { load: async () => ({ + capabilities: { supportsStreaming: true, maxAudioMs: 4000 }, + supports: () => false, + createSession: () => { throw new Error("Offline inference must not open a stream"); }, + transcribe: async pcm => { + if (pcm.length > 32000) throw new Error("Model input limit exceeded"); + return { text: String(pcm.length) }; + }, + }) }; + `)}`; + const model = await loadNativeSpeechModel("asr.gguf", new AbortController().signal, moduleUrl); + try { + expect( + await model.transcribe(new Float32Array(48002).fill(0.8), { timestamps: "none" }, false), + ).toEqual({ text: "32000 16002" }); + } finally { + await model.dispose(); + } +}); + it("preserves withheld audio on VAD failure while keeping ASR failures distinct", async () => { for (const streaming of [false, true]) { const model = await loadNativeSpeechModel( diff --git a/apps/server/src/speech/native.ts b/apps/server/src/speech/native.ts index 8331e1b5e0..2bd2631c63 100644 --- a/apps/server/src/speech/native.ts +++ b/apps/server/src/speech/native.ts @@ -28,7 +28,7 @@ const resetAsr = () => { stream = session = undefined; }; const newAudio = (filterSilence) => createSpeechAudio({ - frameSamples: 512, filterSilence, nativeStreaming: model.capabilities.supportsStreaming, + frameSamples: 512, filterSilence, nativeStreaming, longForm: model.supports("long_form"), maxAudioMs: model.capabilities.maxAudioMs, }); const openAsr = async () => { @@ -45,7 +45,7 @@ const begin = async (message, live) => { scored = revision = 0; heardAudio = false; useVad = Boolean(message.vadPath) && (message.filterSilence || - (!model.capabilities.supportsStreaming && !model.supports("long_form"))); + (!nativeStreaming && !model.supports("long_form"))); if (useVad) { try { if (!vadModel) { @@ -182,7 +182,8 @@ process.on("message", async (message) => { error: error instanceof Error ? error.stack ?? error.message : String(error) }); } }); -process.on("disconnect", () => process.exit(0)); +// Exit teardown under in-flight native inference segfaults, so terminate without it. +process.on("disconnect", () => process.kill(process.pid, "SIGKILL")); `; type Reply = { diff --git a/apps/server/src/speech/postProcessing.test.ts b/apps/server/src/speech/postProcessing.test.ts new file mode 100644 index 0000000000..3dd64c9b1b --- /dev/null +++ b/apps/server/src/speech/postProcessing.test.ts @@ -0,0 +1,81 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { ProviderInstanceId, type ModelSelection } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; + +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as TextGeneration from "../textGeneration/TextGeneration.ts"; +import * as SpeechPostProcessing from "./postProcessing.ts"; + +const textGenerationSelection = { + instanceId: ProviderInstanceId.make("fakeapi"), + model: "fake-model", +}; +const acpSelection = { instanceId: ProviderInstanceId.make("acp_local"), model: "default" }; + +it.effect("cleanup pinned to a provider that cannot generate text uses the text model", () => + Effect.gen(function* () { + const used = yield* Ref.make(null); + const layer = SpeechPostProcessing.layer.pipe( + Layer.provide( + Layer.succeed(TextGeneration.TextGeneration, { + generateTranscriptionPostProcessing: (input: { modelSelection: ModelSelection }) => + Ref.set(used, input.modelSelection).pipe(Effect.as({ transcription: "Hello, world." })), + } as unknown as TextGeneration.TextGeneration["Service"]), + ), + Layer.provide( + Layer.succeed(ProviderRegistry.ProviderRegistry, { + getProviders: Effect.succeed([ + { + instanceId: acpSelection.instanceId, + driver: "acpRegistry", + enabled: true, + installed: true, + supportsTextGeneration: false, + }, + ]), + } as unknown as ProviderRegistry.ProviderRegistry["Service"]), + ), + Layer.provide( + ServerSettings.layerTest({ + providerInstances: { + [acpSelection.instanceId]: { + driver: "acpRegistry", + enabled: true, + config: { source: "local", commandPath: "acp-agent" }, + }, + }, + textGenerators: { + [textGenerationSelection.instanceId]: { + kind: "openaiCompatible", + baseUrl: "http://127.0.0.1:18999/v1", + enabled: true, + }, + }, + textGenerationModelSelection: textGenerationSelection, + speechPostProcessingModelSelection: acpSelection, + }), + ), + Layer.provide(NodeServices.layer), + ); + yield* Effect.gen(function* () { + const postProcessing = yield* SpeechPostProcessing.SpeechPostProcessing; + yield* postProcessing.process({ + options: { + speechCustomWords: [], + speechPostProcessingPrompt: { mode: "default", customInstructions: "" }, + }, + transcript: "um hello world", + draft: { text: "", selection: { start: 0, end: 0 } }, + } as never); + }).pipe(Effect.provide(layer)); + const selection = yield* Ref.get(used); + assert.deepStrictEqual( + { instanceId: selection?.instanceId, model: selection?.model }, + textGenerationSelection, + ); + }), +); diff --git a/apps/server/src/speech/postProcessing.ts b/apps/server/src/speech/postProcessing.ts index 3208afd057..92f4af1769 100644 --- a/apps/server/src/speech/postProcessing.ts +++ b/apps/server/src/speech/postProcessing.ts @@ -8,6 +8,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import { resolveSpeechPostProcessingModelSelection } from "@t3tools/shared/serverSettings"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; import { buildTranscriptionPostProcessingPrompt } from "../textGeneration/TranscriptionPostProcessing.ts"; @@ -27,11 +28,13 @@ const make = Effect.gen(function* () { const settingsService = yield* ServerSettings.ServerSettingsService; const fileSystem = yield* FileSystem.FileSystem; const textGeneration = yield* TextGeneration.TextGeneration; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; return SpeechPostProcessing.of({ process: Effect.fn("SpeechPostProcessing.process")( function* (input) { if (input.transcript.trim().length === 0) return { text: input.transcript }; const settings = yield* settingsService.getSettings; + const providers = yield* providerRegistry.getProviders; const { mode, customInstructions } = input.options.speechPostProcessingPrompt; const instructions = (mode === "custom" ? customInstructions.trim() : "") || @@ -46,7 +49,7 @@ const make = Effect.gen(function* () { input.draft, input.options.speechCorrectionWord, ), - modelSelection: resolveSpeechPostProcessingModelSelection(settings), + modelSelection: resolveSpeechPostProcessingModelSelection(settings, providers), }); const text = generated.transcription.trim(); return { diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index fd56b4a4c8..159778b3c7 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -1,9 +1,11 @@ import type * as NodeOS from "node:os"; import { describe, expect, it } from "@effect/vitest"; +import * as NetAddress from "effect/net/NetAddress"; import { acceptsPrivateNetworkConnection, + loopbackUrlHostForAddress, resolveHeadlessConnectionString, } from "./startupAccess.ts"; @@ -19,6 +21,7 @@ const ipv4 = (address: string, internal = false): NodeOS.NetworkInterfaceInfo => it("resolves wildcard hosts to a concrete external interface when one is available", () => { const connectionString = resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces: { en0: [ipv4("192.168.1.42")], lo0: [ipv4("127.0.0.1", true)] }, + platform: "linux", }); expect(connectionString).toBe("http://192.168.1.42:3773"); @@ -32,16 +35,21 @@ it("skips public and container addresses for a private-network listener", () => eth1: [ipv4("10.0.0.5")], }; - expect(resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces })).toBe( + expect(resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces, platform: "linux" })).toBe( "http://203.0.113.7:3773", ); expect( - resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces, privateNetworkOnly: true }), + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces, + privateNetworkOnly: true, + platform: "linux", + }), ).toBe("http://10.0.0.5:3773"); expect( resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces: { eth0: [ipv4("203.0.113.7")] }, privateNetworkOnly: true, + platform: "linux", }), ).toBe("http://localhost:3773"); }); @@ -51,10 +59,33 @@ it("prefers a LAN address over a tailnet one for a private-network pairing URL", resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces: { tailscale0: [ipv4("100.101.102.103")], en0: [ipv4("192.168.1.42")] }, privateNetworkOnly: true, + platform: "linux", }), ).toBe("http://192.168.1.42:3773"); }); +it("skips NixOS container and systemd-nspawn veths for a private-network pairing URL", () => { + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces: { "ve-jellyfin": [ipv4("192.168.53.193")], eth0: [ipv4("192.168.0.18")] }, + privateNetworkOnly: true, + platform: "linux", + }), + ).toBe("http://192.168.0.18:3773"); +}); + +it("targets the bound interface when the listener binds a specific address", () => { + const hostFor = (ip: string) => + loopbackUrlHostForAddress(NetAddress.inetAddressFromIpStringUnsafe(ip, 3773)); + + expect(hostFor("0.0.0.0")).toBe("127.0.0.1"); + expect(hostFor("::")).toBe("127.0.0.1"); + expect(hostFor("::1")).toBe("[::1]"); + expect(hostFor("127.0.0.1")).toBe("127.0.0.1"); + expect(hostFor("127.0.0.2")).toBe("127.0.0.2"); + expect(hostFor("100.101.102.103")).toBe("100.101.102.103"); +}); + describe("acceptsPrivateNetworkConnection", () => { const accepts = (localAddress: string | undefined, remoteAddress: string | undefined) => acceptsPrivateNetworkConnection({ localAddress, remoteAddress }); diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index 4a43b720be..06164fd39d 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -1,7 +1,13 @@ import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; -import { isPrivateNetworkHost, isSharedAddressSpaceHost } from "@t3tools/shared/hostClassification"; +import { + formatHostForUrl, + isPrivateNetworkHost, + isSharedAddressSpaceHost, + isWildcardHost, +} from "@t3tools/shared/hostClassification"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { QrCode } from "@t3tools/shared/qrCode"; import { buildPairingAppLink } from "@t3tools/shared/remote"; import * as Effect from "effect/Effect"; @@ -33,21 +39,25 @@ export const isLoopbackHost = (host: string | undefined): boolean => { ); }; -export const isWildcardHost = (host: string | undefined): boolean => - host === "0.0.0.0" || host === "::" || host === "[::]"; - -export const formatHostForUrl = (host: string): string => - host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; - /** * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and * macOS's `bridge100`+) have private addresses only this machine reaches. A * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so * it stays listed. */ -export const VIRTUAL_INTERFACE = +const VIRTUAL_INTERFACE = /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/; +/** + * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side + * veths after the machine. Windows aliases are user-renameable, so these + * prefixes only apply to Linux interface discovery. + */ +const LINUX_CONTAINER_INTERFACE = /^(ve-|vb-|vz-)/; + +export const isVirtualInterface = (name: string, platform: NodeJS.Platform): boolean => + VIRTUAL_INTERFACE.test(name) || (platform === "linux" && LINUX_CONTAINER_INTERFACE.test(name)); + /** * Loopback or private-range IPv4 (LAN, tailnet, CGNAT), not link-local, in * plain or IPv4-mapped IPv6 form. @@ -72,9 +82,9 @@ export const acceptsPrivateNetworkConnection = (socket: { ); export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string => - address._tag === "InetAddressV6" && NetAddress.isLoopback(address.address) - ? "[::1]" - : "127.0.0.1"; + NetAddress.isUnspecified(address.address) + ? "127.0.0.1" + : NetAddress.formatUrlHostString(NetAddress.formatIp(address.address)); const normalizeHost = (host: string): string => host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; @@ -87,6 +97,7 @@ const resolveHeadlessConnectionHost = ( host: string | undefined, interfaces: NetworkInterfacesMap, privateNetworkOnly: boolean, + platform: NodeJS.Platform, ): string => { if (!host) { return "localhost"; @@ -97,7 +108,7 @@ const resolveHeadlessConnectionHost = ( } const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) => - privateNetworkOnly && VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? []), + privateNetworkOnly && isVirtualInterface(name, platform) ? [] : (entries ?? []), ); const externalIpv4Entries = interfaceEntries.filter( (entry) => @@ -129,12 +140,14 @@ export const resolveHeadlessConnectionString = ( options: { readonly interfaces?: NetworkInterfacesMap; readonly privateNetworkOnly?: boolean | undefined; - } = {}, + readonly platform: NodeJS.Platform; + }, ): string => { const connectionHost = resolveHeadlessConnectionHost( host, options.interfaces ?? NodeOS.networkInterfaces(), options.privateNetworkOnly === true, + options.platform, ); return `http://${formatHostForUrl(connectionHost)}:${port}`; }; @@ -197,10 +210,11 @@ export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessI const serverConfig = yield* ServerConfig.ServerConfig; const httpServer = yield* HttpServer.HttpServer; const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const platform = yield* HostProcess.Platform; const connectionString = resolveHeadlessConnectionString( serverConfig.host, resolveListeningPort(httpServer.address, serverConfig.port), - { privateNetworkOnly: serverConfig.privateNetworkOnly }, + { privateNetworkOnly: serverConfig.privateNetworkOnly, platform }, ); const issued = yield* serverAuth.issueStartupPairingCredential(); diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index de1ccfefcf..cf56bde07f 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -2,6 +2,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; import * as Context from "effect/Context"; +import type * as Digest from "effect/crypto/Digest"; +import * as Base64Url from "effect/encoding/Base64Url"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -14,6 +16,8 @@ import * as Stream from "effect/Stream"; import { SCAN_CACHE_FILE_NAME } from "./usage/usageScanCache.ts"; import { TestClock } from "effect/testing"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Sqlite from "./persistence/Sqlite.ts"; +import { checkpointRefForScopeOrdinal } from "./orchestration-v2/CheckpointService.ts"; import { DEFAULT_SERVER_SETTINGS, type WorktreeKeepWhen, @@ -26,17 +30,20 @@ import * as ServerConfig from "./config.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import * as GitManager from "./git/GitManager.ts"; +import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as Settings from "./serverSettings.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; +import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { CodexProviderCapabilitiesV2 } from "./orchestration-v2/Adapters/CodexAdapterV2.ts"; import { ServerActivation } from "./serverActivation.ts"; import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import { describe, expect, it } from "@effect/vitest"; import { + CheckpointScopeId, EventId, ProjectId, ProviderDriverKind, @@ -46,6 +53,7 @@ import { RuntimeRequestId, ThreadId, type OrchestrationV2DomainEvent, + type OrchestrationV2ServerCommand, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -205,6 +213,13 @@ describe("V2 storage cleanup eligibility", () => { resetIn: -1_000, idle: false, }, + { + name: "never armed because its reset is days overdue", + armed: false, + autoResumeSetting: true, + resetIn: -5 * DAY_MS, + idle: true, + }, { name: "not armed with recovery settings off", armed: false, @@ -318,6 +333,7 @@ const cleanupFixture = ( worktreeAfterDays: 8, worktreeOnDelete: true, }, + sqlOverride?: SqlClient.SqlClient, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -350,6 +366,7 @@ const cleanupFixture = ( let sessionLiveChecks = 0; let onLiveCheck: Effect.Effect = Effect.void; let outboxStatus: string | null = null; + let scheduledThreadIds: string[] = []; let fullStatusCalls = 0; let gitInspections = 0; let snapshotReads = 0; @@ -419,6 +436,31 @@ const cleanupFixture = ( getThreadShell: (threadId: ThreadId) => Effect.sync(() => threads.find((thread) => thread.id === threadId) ?? null), } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), + Effect.provideService(ThreadManagement.ThreadManagementService, { + getShellSnapshot: (input?: { threadIds?: ReadonlyArray }) => + Effect.sync(() => ({ + threads: threads.filter((thread) => input?.threadIds?.includes(thread.id) ?? true), + archivedThreads: [], + })), + dispatch: (command: OrchestrationV2ServerCommand) => + Effect.sync(() => { + if (command.type === "thread.metadata.update" && command.branch != null) { + const branch = command.branch; + threads = threads.map((thread) => + thread.id === command.threadId && thread.branch === command.expectedBranch + ? { ...thread, branch } + : thread, + ); + } + return { sequence: 0, storedEvents: [] }; + }), + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + Effect.provideService(GitWorkflowService.GitWorkflowService, { + currentBranch: (cwd: string) => + command(cwd, ["branch", "--show-current"]).pipe( + Effect.map((result) => result.stdout.trim() || null), + ), + } as unknown as GitWorkflowService.GitWorkflowService["Service"]), Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, { isLive: () => Effect.sync(() => { @@ -429,39 +471,49 @@ const cleanupFixture = ( Effect.provideService(Orchestrator.OrchestratorV2, { streamDomainEvents: Stream.suspend(() => events), } as unknown as Orchestrator.OrchestratorV2["Service"]), - Effect.provideService(SqlClient.SqlClient, ((strings: TemplateStringsArray) => - Effect.sync(() => - openSessionCwd !== null && strings.join("").includes("projection_provider_sessions") - ? [ - { - payload_json: JSON.stringify({ - id: "session-1", - driver: "codex", - providerInstanceId: "codex", - status: "ready", - cwd: openSessionCwd, - model: null, - capabilities: CodexProviderCapabilitiesV2, - createdAt: "2026-06-01T12:00:00.000Z", - updatedAt: "2026-06-01T12:00:00.000Z", - lastError: null, - }), - }, - ] - : outboxStatus !== null && strings.join("").includes("orchestration_v2_effect_outbox") - ? [{ status: outboxStatus }] - : strings.join("").includes("deleted_at IS NOT NULL") - ? deletedThreads.map((thread) => ({ - payload_json: JSON.stringify(thread), - workspaceRoot: repo, - })) - : strings.join("").includes('AS "worktreePath"') + Effect.provideService( + SqlClient.SqlClient, + sqlOverride ?? + (((strings: TemplateStringsArray) => + Effect.sync(() => + strings.join("").includes("retained_checkpoint_threads") + ? [] + : openSessionCwd !== null && + strings.join("").includes("projection_provider_sessions") ? [ - ...threads.flatMap((thread) => thread.worktreePath ?? []), - ...storedWorktreePaths, - ].map((worktreePath) => ({ worktreePath })) - : [], - )) as unknown as SqlClient.SqlClient), + { + payload_json: JSON.stringify({ + id: "session-1", + driver: "codex", + providerInstanceId: "codex", + status: "ready", + cwd: openSessionCwd, + model: null, + capabilities: CodexProviderCapabilitiesV2, + createdAt: "2026-06-01T12:00:00.000Z", + updatedAt: "2026-06-01T12:00:00.000Z", + lastError: null, + }), + }, + ] + : outboxStatus !== null && + strings.join("").includes("orchestration_v2_effect_outbox") + ? [{ status: outboxStatus }] + : strings.join("").includes("deleted_at IS NOT NULL") + ? deletedThreads.map((thread) => ({ + payload_json: JSON.stringify(thread), + workspaceRoot: repo, + })) + : strings.join("").includes('AS "worktreePath"') + ? [ + ...threads.flatMap((thread) => thread.worktreePath ?? []), + ...storedWorktreePaths, + ].map((worktreePath) => ({ worktreePath })) + : strings.join("").includes("scheduled_tasks") + ? scheduledThreadIds.map((threadId) => ({ threadId })) + : [], + )) as unknown as SqlClient.SqlClient), + ), Effect.provideService(GitManager.GitManager, { invalidateStatus: () => Effect.void, } as unknown as GitManager.GitManager["Service"]), @@ -520,12 +572,16 @@ const cleanupFixture = ( setThreads: (next: typeof threads) => { threads = next; }, + threadBranches: () => threads.map((thread) => thread.branch), setOnLiveCheck: (hook: Effect.Effect) => { onLiveCheck = hook; }, setOutboxStatus: (status: string | null) => { outboxStatus = status; }, + setScheduledThreadIds: (next: string[]) => { + scheduledThreadIds = next; + }, setDeletedThreads: (next: OrchestrationV2ThreadShell[]) => { deletedThreads = next; }, @@ -593,17 +649,249 @@ const cleanupTestLayer = GitVcsDriver.layer.pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "storage-cleanup-" })), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); +const annexWorktree = Effect.fnUntraced(function* ( + fixture: Effect.Success>, + worktree: string, +) { + const adminDir = (yield* fixture.command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout; + yield* fixture.fs.remove(`${worktree}/.git`); + yield* fixture.fs.symlink(adminDir.trim(), `${worktree}/.git`); +}); + const runCleanupTest = ( effect: Effect.Effect< A, E, | FileSystem.FileSystem + | Digest.Digest | ServerConfig.ServerConfig | GitVcsDriver.GitVcsDriver | Path.Path | Scope.Scope >, -) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped); +) => effect.pipe(Effect.provide(cleanupTestLayer)); + +const legacyCheckpointRef = (threadId: string, turn: number) => + `refs/t3/checkpoints/${Base64Url.encode(threadId)}/turn/${turn}`; + +const checkpointCleanupFixture = Effect.fn("test.checkpointCleanupFixture")(function* () { + const sql = yield* SqlClient.SqlClient; + const git = yield* GitVcsDriver.GitVcsDriver; + const fixture = yield* cleanupFixture(DEFAULT_SERVER_SETTINGS.storageCleanup, sql); + const { repo, worktree, command } = fixture; + const timestamp = DateTime.formatIso(at(0)); + yield* sql`INSERT INTO projection_projects ${sql.insert({ + project_id: "project-1", + title: "Checkpoint cleanup", + workspace_root: repo, + scripts_json: "[]", + created_at: timestamp, + updated_at: timestamp, + deleted_at: timestamp, + })}`; + const addThread = Effect.fn("test.addCheckpointThread")(function* ( + id: string, + options: { deleted?: boolean; archived?: boolean; source?: string; legacyOnly?: boolean } = {}, + ) { + const scopeId = CheckpointScopeId.make(`scope:${id}`); + yield* sql`INSERT INTO orchestration_v2_projection_threads ${sql.insert({ + thread_id: id, + project_id: "project-1", + title: id, + default_provider: "codex", + runtime_mode: "full-access", + interaction_mode: "default", + created_at: timestamp, + updated_at: timestamp, + archived_at: options.archived ? timestamp : null, + deleted_at: options.deleted ? timestamp : null, + payload_json: JSON.stringify({ + worktreePath: worktree, + forkedFrom: options.source ? { type: "run", threadId: options.source } : null, + }), + })}`; + if (!options.legacyOnly) + yield* sql`INSERT INTO orchestration_v2_projection_checkpoint_scopes ${sql.insert({ + scope_id: scopeId, + thread_id: id, + node_id: `node:${id}`, + kind: "root_run", + ordinal_within_parent: 0, + advances_app_run_count: 1, + created_at: timestamp, + payload_json: JSON.stringify({ cwd: worktree }), + })}`; + const refs: string[] = options.legacyOnly + ? [legacyCheckpointRef(id, 0)] + : [ + yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 0 }), + yield* checkpointRefForScopeOrdinal({ scopeId, ordinalWithinScope: 1 }), + legacyCheckpointRef(id, 0), + ]; + for (const ref of refs) yield* command(repo, ["update-ref", ref, "HEAD"]); + return refs; + }); + const listRefs = () => + git + .execute({ + operation: "cleanup-test.list-checkpoints", + cwd: repo, + args: ["for-each-ref", "--format=%(refname)", "refs/t3/"], + maxOutputBytes: 16 * 1024 * 1024, + }) + .pipe(Effect.map(({ stdout }) => stdout.trim().split("\n").filter(Boolean).sort())); + return { ...fixture, sql, addThread, listRefs }; +}); + +describe("checkpoint ref cleanup", () => { + it.live("prunes refs owned by deleted threads after their worktree is removed", () => + runCleanupTest( + Effect.gen(function* () { + const { service, repo, worktree, command, addThread, listRefs } = + yield* checkpointCleanupFixture(); + yield* addThread("deleted", { deleted: true }); + yield* addThread("imported-deleted", { deleted: true, legacyOnly: true }); + const retained = [ + ...(yield* addThread("active")), + ...(yield* addThread("archived", { archived: true })), + legacyCheckpointRef("unknown-owner", 0), + ]; + yield* command(repo, ["update-ref", retained.at(-1)!, "HEAD"]); + yield* command(repo, ["pack-refs", "--all"]); + yield* command(repo, ["worktree", "remove", worktree]); + yield* service.runNow; + expect(yield* listRefs()).toEqual(retained.sort()); + }).pipe(Effect.provide(Sqlite.layerMemory)), + ), + ); + + it.live("keeps deleted fork ancestry while a live or archived descendant needs it", () => + runCleanupTest( + Effect.gen(function* () { + const { service, sql, addThread, listRefs } = yield* checkpointCleanupFixture(); + const root = yield* addThread("root", { deleted: true }); + const intermediate = yield* addThread("intermediate", { deleted: true, source: "root" }); + const child = yield* addThread("child", { archived: true, source: "intermediate" }); + yield* service.runNow; + expect(yield* listRefs()).toEqual([...root, ...intermediate, ...child].sort()); + yield* sql`UPDATE orchestration_v2_projection_threads SET deleted_at = 'deleted' WHERE thread_id = 'child'`; + yield* service.runNow; + expect(yield* listRefs()).toEqual([]); + }).pipe(Effect.provide(Sqlite.layerMemory)), + ), + ); + + it.live("waits for a deleted thread's pending checkpoint effects", () => + runCleanupTest( + Effect.gen(function* () { + const { service, sql, addThread, listRefs } = yield* checkpointCleanupFixture(); + const refs = yield* addThread("capturing", { deleted: true }); + yield* sql`INSERT INTO orchestration_v2_effect_outbox ${sql.insert({ + effect_id: "capture", + command_id: "capture", + thread_id: "capturing", + effect_type: "checkpoint.capture", + payload_json: "{}", + status: "running", + available_at: "2026-01-01T00:00:00Z", + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + })}`; + yield* service.runNow; + expect(yield* listRefs()).toEqual(refs.toSorted()); + yield* sql`UPDATE orchestration_v2_effect_outbox SET status = 'succeeded'`; + yield* service.runNow; + expect(yield* listRefs()).toEqual([]); + }).pipe(Effect.provide(Sqlite.layerMemory)), + ), + ); + + it.live("deletes a symbolic checkpoint ref without its target or neighbouring refs", () => + runCleanupTest( + Effect.gen(function* () { + const { service, repo, command, addThread, listRefs } = yield* checkpointCleanupFixture(); + const refs = yield* addThread("deleted", { deleted: true }); + yield* command(repo, ["symbolic-ref", refs[0]!, "refs/heads/main"]); + const retained = [ + "refs/t3/unrelated/0", + `${refs[1]}-other`, + refs[1]!.replace(/1$/, "2/nested"), + ]; + for (const ref of retained) yield* command(repo, ["update-ref", ref, "HEAD"]); + yield* service.runNow; + expect(yield* listRefs()).toEqual(retained.sort()); + yield* command(repo, ["show-ref", "--verify", "refs/heads/main"]); + }).pipe(Effect.provide(Sqlite.layerMemory)), + ), + ); + + it.live("cleans more checkpoint refs than default git output holds", () => + runCleanupTest( + Effect.gen(function* () { + const { service, repo, addThread, listRefs } = yield* checkpointCleanupFixture(); + const git = yield* GitVcsDriver.GitVcsDriver; + const prefix = (yield* addThread("many-checkpoints", { deleted: true }))[0]!.slice(0, -1); + yield* git.execute({ + operation: "cleanup-test.seed-checkpoints", + cwd: repo, + args: ["update-ref", "--stdin"], + stdin: Array.from( + { length: 12_283 }, + (_, ordinal) => `update ${prefix}${ordinal} HEAD\n`, + ).join(""), + }); + yield* service.runNow; + expect(yield* listRefs()).toEqual([]); + }).pipe(Effect.provide(Sqlite.layerMemory)), + ), + ); +}); + +it.live.each(["repository", "uppercase", "bare"] as const)( + "keeps a worktree holding an ignored nested %s", + (kind) => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, repo, worktree, command, setPolicy } = yield* cleanupFixture(); + setPolicy("tracked-changes"); + const nested = `${worktree}/dist/nested`; + if (kind === "uppercase") { + yield* command(repo, ["worktree", "add", "-b", "nested", nested]); + } else { + yield* command(repo, [ + "clone", + "--no-hardlinks", + ...(kind === "bare" ? ["--bare"] : []), + repo, + nested, + ]); + } + if (kind === "uppercase") yield* fs.rename(`${nested}/.git`, `${nested}/.GIT`); + yield* fs.writeFileString(`${nested}/uncommitted.txt`, "irreplaceable work\n"); + expect((yield* command(worktree, ["status", "--porcelain"])).stdout).toBe(""); + const report = yield* service.runNow; + expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ + outcome: "kept", + reason: "Contains a nested Git repository", + }); + expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("irreplaceable work\n"); + expect( + (yield* command(nested, [ + ...(kind === "uppercase" + ? [ + `--git-dir=${(yield* fs.readFileString(`${nested}/.GIT`)).trim().slice(8)}`, + "--work-tree=.", + ] + : []), + "-c", + "safe.bareRepository=all", + "rev-parse", + "--is-bare-repository", + ])).stdout.trim(), + ).toBe(String(kind === "bare")); + }), + ), +); const submoduleCleanupFixture = () => Effect.gen(function* () { @@ -629,11 +917,71 @@ const submoduleCleanupFixture = () => return { ...fixture, submodule, child, recordSubmodules }; }); -it.live("removes clean submodules recursively, including deinitialized repositories", () => +it.live("inspects a pnpm store excluded from reclaimed bytes for nested repositories", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, repo, worktree, command, setPolicy } = yield* cleanupFixture(); + setPolicy("tracked-changes"); + const storeDir = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-store-" }); + const nested = `${worktree}/node_modules/.pnpm/nested`; + yield* command(repo, ["clone", "--no-hardlinks", repo, nested]); + yield* fs.writeFileString(`${nested}/uncommitted.txt`, "keep me"); + yield* fs.writeFileString( + `${worktree}/node_modules/.modules.yaml`, + JSON.stringify({ storeDir, virtualStoreDir: ".pnpm" }), + ); + const report = yield* service.runNow; + expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ + outcome: "kept", + reason: "Contains a nested Git repository", + }); + expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("keep me"); + }), + ), +); + +it.live("keeps an ignored repository inside a registered submodule", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, submodule, command, recordSubmodules } = + const { service, fs, repo, worktree, submodule, command, setPolicy } = yield* submoduleCleanupFixture(); + setPolicy("tracked-changes"); + const nested = `${submodule}/dist/nested`; + yield* command(repo, ["clone", "--no-hardlinks", repo, nested]); + yield* fs.writeFileString(`${nested}/uncommitted.txt`, "keep me"); + const report = yield* service.runNow; + expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ + outcome: "kept", + reason: "Contains a nested Git repository", + }); + expect(yield* fs.readFileString(`${nested}/uncommitted.txt`)).toBe("keep me"); + }), + ), +); + +it.live("removes clean submodules recursively, including deinitialized repositories", () => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const git = yield* GitVcsDriver.GitVcsDriver; + let editedDuringClean = false; + const { service, repo, worktree, submodule, command, recordSubmodules, setPolicy } = + yield* submoduleCleanupFixture().pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, { + ...git, + execute: (input) => + git.execute(input).pipe( + Effect.tap(() => { + if (input.args[0] !== "clean") return Effect.void; + editedDuringClean = true; + return fs.writeFileString(`${input.cwd}/tracked.txt`, "late edit\n"); + }), + ), + }), + ); + setPolicy("tracked-changes"); + yield* fs.writeFileString(`${worktree}/notes.txt`, "untracked\n"); + yield* fs.writeFileString(`${worktree}/.env`, "ignored\n"); yield* command(submodule, [ "-c", "protocol.file.allow=always", @@ -642,10 +990,55 @@ it.live("removes clean submodules recursively, including deinitialized repositor repo, "stored", ]); + const legacy = `${worktree}/legacy`; + yield* command(repo, ["clone", "--no-hardlinks", repo, legacy]); + yield* command(worktree, ["submodule", "add", repo, "legacy"]); + expect((yield* fs.stat(`${legacy}/.git`)).type).toBe("Directory"); + yield* command(legacy, [ + "-c", + "protocol.file.allow=always", + "submodule", + "add", + repo, + "child", + ]); + yield* command(legacy, [ + "-c", + "protocol.file.allow=always", + "submodule", + "add", + repo, + "stored", + ]); + yield* command(legacy, [ + "-c", + "user.name=Cleanup test", + "-c", + "user.email=cleanup@example.test", + "commit", + "-am", + "record legacy children", + ]); + yield* command(legacy, ["push", "origin", "HEAD:legacy"]); + yield* command(legacy, ["submodule", "deinit", "stored"]); yield* recordSubmodules(); yield* command(submodule, ["submodule", "deinit", "stored"]); + const checkpoint = (yield* command(submodule, [ + "commit-tree", + "HEAD^{tree}", + "-p", + "HEAD", + "-m", + "checkpoint", + ])).stdout.trim(); + yield* command(submodule, [ + "update-ref", + "refs/t3/orchestration-v2/checkpoints/test", + checkpoint, + ]); const admin = (yield* command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); const report = yield* service.runNow; + expect(editedDuringClean).toBe(false); expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ outcome: "removed", }); @@ -751,15 +1144,21 @@ it.live("keeps unpushed submodule history after checkout and deinitialization", it.live("keeps submodules when stored repository metadata is malformed", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, worktree, submodule, child, command } = yield* submoduleCleanupFixture(); + const { service, fs, worktree, submodule, child, command, setPolicy } = + yield* submoduleCleanupFixture(); + setPolicy("tracked-changes"); const childGit = (yield* command(child, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); yield* command(submodule, ["submodule", "deinit", "child"]); yield* fs.writeFileString(`${childGit}/HEAD`, "not a ref\n"); + yield* fs.writeFileString(`${worktree}/notes.txt`, "keep while the worktree stays\n"); expect( (yield* service.runNow).entries.find((entry) => entry.path === worktree), ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("inspected") }); expect(yield* fs.exists(worktree)).toBe(true); expect(yield* fs.readFileString(`${childGit}/HEAD`)).toBe("not a ref\n"); + expect(yield* fs.readFileString(`${worktree}/notes.txt`)).toBe( + "keep while the worktree stays\n", + ); }), ), ); @@ -879,10 +1278,10 @@ describe("subagent worktree ownership", () => { ? "Thread is running or has pending work" : "Not settled", }); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); - it.live.each([ + it.effect.each([ "parent-unsettled", "parent-resettled", "child-unsettled", @@ -891,6 +1290,7 @@ describe("subagent worktree ownership", () => { ] as const)("cancels inherited settlement during measurement (%s)", (change) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0, @@ -947,6 +1347,8 @@ describe("subagent worktree ownership", () => { it.effect.each([ "idle", "grandchild", + "branchless", + "branchless-running", "null-branch", "stale-branch", "isolated-owner", @@ -978,7 +1380,7 @@ describe("subagent worktree ownership", () => { }, }); const root = shell({ - branch: "feature", + branch: ["branchless", "branchless-running"].includes(scenario) ? null : "feature", worktreePath: fixture.worktree, settledAt: scenario === "child-settled-only" ? null : at(-20 * DAY_MS), ...(scenario === "isolated-owner" || scenario === "fork-owner" @@ -1020,7 +1422,7 @@ describe("subagent worktree ownership", () => { : "subagent", ...(scenario === "side-chat" ? { sideChat: true } : {}), }, - status: scenario === "running" ? "running" : "completed", + status: ["running", "branchless-running"].includes(scenario) ? "running" : "completed", pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [], latestRunCompletedAt: scenario === "recent-activity" || scenario === "recent-inactive" @@ -1069,7 +1471,7 @@ describe("subagent worktree ownership", () => { outcome: removed ? "removed" : "kept", reason: removed ? "Settled for 20 days" - : scenario === "running" || scenario === "pending" + : ["running", "pending", "branchless-running"].includes(scenario) ? "Thread is running or has pending work" : shared ? "Shared by 2 threads" @@ -1081,12 +1483,60 @@ describe("subagent worktree ownership", () => { ? "Inactive for 2 of 8 days" : ["recent-grace", "recent-settle", "child-settled-now"].includes(scenario) ? "Settled moments ago" - : "Not settled", + : scenario === "branchless" + ? "Thread has no branch" + : "Not settled", }); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); - it.live.each([ + it.effect("keeps a checkout two top-level threads store through a symlinked parent", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 8, + }); + const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; + yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); + const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; + fixture.setThreads([ + shell({ ...settled, worktreePath: fixture.worktree }), + shell({ ...settled, id: ThreadId.make("other"), worktreePath: `${linkedParent}/feature` }), + ]); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), + ]); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }).pipe(Effect.provide(cleanupTestLayer)), + ); + + it.effect("keeps a checkout two top-level threads store in different case on Windows", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 8, + }).pipe(Effect.provideService(HostProcess.Platform, "win32")); + const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; + fixture.setThreads([ + shell({ ...settled, worktreePath: fixture.worktree }), + shell({ + ...settled, + id: ThreadId.make("other"), + worktreePath: fixture.worktree.toUpperCase(), + }), + ]); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), + ]); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }).pipe(Effect.provide(cleanupTestLayer)), + ); + + it.effect.each([ "running", "pending", "activity", @@ -1098,6 +1548,7 @@ describe("subagent worktree ownership", () => { ] as const)("cancels removal when a child changes during measurement (%s)", (change) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const root = shell({ branch: "feature", worktreePath: fixture.worktree }); const child = { @@ -1187,7 +1638,29 @@ describe("deleted thread worktrees", () => { reason: "Thread was deleted", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), + ); + + it.effect("leaves a deleted owner's subagent on the owner's saved branch", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeAfterDays: null, + worktreeOnDelete: true, + }); + const owner = parent(fixture.worktree); + fixture.setDeletedThreads([owner]); + fixture.setThreads([subagent(owner)]); + yield* fixture.command(fixture.worktree, ["switch", "-c", "renamed"]); + expect((yield* fixture.service.runNow).entries[0]).toMatchObject({ + threadId: owner.id, + outcome: "kept", + reason: "Repository or branch changed", + }); + // The deleted owner cannot follow, so moving its subagent would split their records. + expect(fixture.threadBranches()).toEqual(["feature"]); + }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), ); it.effect("applies the remaining subagent's rules when deletion cleanup is off", () => @@ -1209,7 +1682,7 @@ describe("deleted thread worktrees", () => { reason: "Inactive for 30 days", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); // Releases one stopped-session event after the startup sweep and returns the snapshot reads it caused. @@ -1268,7 +1741,7 @@ describe("deleted thread worktrees", () => { const fixture = yield* cleanupFixture(); const reads = yield* stopSessionAfterStartupSweep(fixture, ThreadId.make("thread-1")); expect(reads, "a live thread's stopped session re-read every thread").toBe(0); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("removes a deleted thread's worktree once its session stops", () => @@ -1290,7 +1763,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("removes a deleted thread's worktree once a live thread's session in it stops", () => @@ -1320,7 +1793,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1366,7 +1839,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1399,7 +1872,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("does not sweep for a kept deleted worktree when a session elsewhere stops", () => @@ -1421,7 +1894,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBe(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1451,7 +1924,7 @@ describe("deleted thread worktrees", () => { fixture.repo, ); expect(reads).toBe(0); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1525,7 +1998,7 @@ describe("deleted thread worktrees", () => { yield* Deferred.await(delivered); yield* fixture.service.drain; expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("waits out the settle grace of a subagent that just settled", () => @@ -1546,7 +2019,7 @@ describe("deleted thread worktrees", () => { reason: "Settled moments ago", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); }); @@ -1635,7 +2108,7 @@ describe("orphan worktree reports", () => { ), ); - it.live.each(["nested", "direct"] as const)( + it.live.each(["nested", "direct", "annexed"] as const)( "reports a linked orphan's size without removing its files (%s)", (location) => runCleanupTest( @@ -1644,8 +2117,13 @@ describe("orphan worktree reports", () => { fixture.setThreads([]); const orphan = `${fixture.config.worktreesDir}/${location === "nested" ? "repository/" : ""}orphan`; yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]); - const sizes = yield* Effect.forEach(yield* fixture.fs.readDirectory(orphan), (name) => - allocatedBytes(fixture.fs, `${orphan}/${name}`), + if (location === "annexed") yield* annexWorktree(fixture, orphan); + const sizes = yield* Effect.forEach( + // Links are not measured, and the annexed `.git` is one. + (yield* fixture.fs.readDirectory(orphan)).filter( + (name) => location !== "annexed" || name !== ".git", + ), + (name) => allocatedBytes(fixture.fs, `${orphan}/${name}`), ); const outside = yield* fixture.fs.makeTempDirectoryScoped(); yield* fixture.fs.writeFileString(`${outside}/external`, "outside data"); @@ -1755,6 +2233,57 @@ describe("orphan worktree reports", () => { ), ); + it.live.each([ + { home: "an installed", worktreeHome: false, customFolderOutcome: "removed" }, + { home: "a git worktree's dev", worktreeHome: true, customFolderOutcome: "kept" }, + ] as const)( + "on $home home, a custom worktrees folder ends $customFolderOutcome", + ({ worktreeHome, customFolderOutcome }) => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const config = yield* ServerConfig.ServerConfig; + const checkout = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-dev-checkout-" }); + yield* fs.writeFileString(`${checkout}/.git`, "gitdir: /repo/.git/worktrees/dev\n"); + const baseDir = worktreeHome ? `${checkout}/.t3` : config.baseDir; + const fixture = yield* cleanupFixture().pipe( + Effect.provideService(ServerConfig.ServerConfig, { + ...config, + baseDir, + worktreesDir: `${baseDir}/worktrees`, + }), + ); + const customFolder = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-real-worktrees-" }), + ); + const realWorktree = `${customFolder}/seeded`; + yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "seeded", realWorktree]); + fixture.setSettings({ worktreesDirectory: customFolder }); + fixture.setThreads([ + shell({ branch: "feature", worktreePath: fixture.worktree }), + shell({ + id: ThreadId.make("seeded"), + lineage: { + rootThreadId: ThreadId.make("seeded"), + parentThreadId: null, + relationshipToParent: null, + }, + branch: "seeded", + worktreePath: realWorktree, + }), + ]); + + const { entries } = yield* fixture.service.runNow; + + expect(entries.find((entry) => entry.path === realWorktree)?.outcome).toBe( + customFolderOutcome, + ); + expect(yield* fs.exists(realWorktree)).toBe(customFolderOutcome === "kept"); + expect(yield* fs.exists(fixture.worktree)).toBe(false); + }), + ), + ); + it.live("skips symbolic links at both directory levels and disabled cleanup", () => runCleanupTest( Effect.gen(function* () { @@ -2067,7 +2596,8 @@ describe("storage cleanup reports and local file policies", () => { occurredAt: at(0), payload: { ...shell({ deletedAt: at(0) }), lastVisitedAt: null }, }); - expect(fixture.snapshotReads()).toBe(startupReads + 3 * Number(worktreeOnDelete)); + // Deletion always sweeps so the deleted thread's checkpoint refs are pruned. + expect(fixture.snapshotReads()).toBe(startupReads + 2 * Number(worktreeOnDelete) + 1); expect(fixture.sessionLiveChecks()).toBe(worktreeOnDelete ? 6 : 0); }), ), @@ -2107,18 +2637,153 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live.each(["before-check", "while-measuring"] as const)( - "keeps a worktree protected by a missing project root (%s)", - (timing) => + it.effect("removes an idle No project thread's scratch folder past the retention", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + const scratchRoot = `${fixture.config.baseDir}/scratch`; + const folder = `${scratchRoot}/quiet-otter`; + yield* fixture.fs.makeDirectory(folder, { recursive: true }); + yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); + fixture.setProjectRoots([scratchRoot]); + fixture.setStoredWorktreePaths([]); + // Only this rule lets cleanup delete untracked files, which is all a scratch folder has. + fixture.setPolicy("tracked-changes"); + fixture.setThreads([ + shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), + ]); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ path: folder, outcome: "removed" }), + ]); + expect(yield* fixture.fs.exists(folder)).toBe(false); + }), + ), + ); + it.effect.each([ + { + name: "a Git repository in a subfolder", + policy: "tracked-changes", + repository: "clone/.git", + reason: "Contains a nested Git repository", + }, + { + name: "a Git repository of its own", + policy: "tracked-changes", + repository: ".git", + reason: "Contains a nested Git repository", + }, + { name: "files under the default keep rule", reason: "Has local files (notes.md)" }, + { + name: "a scheduled task", + policy: "tracked-changes", + scheduled: true, + reason: "Thread has a scheduled task", + }, + ] as const)( + "keeps an idle No project thread's scratch folder with $name", + ({ + policy, + repository, + scheduled, + reason, + }: { + readonly policy?: WorktreeKeepWhen; + readonly repository?: string; + readonly scheduled?: boolean; + readonly reason: string; + }) => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + const scratchRoot = `${fixture.config.baseDir}/scratch`; + const folder = `${scratchRoot}/quiet-otter`; + yield* fixture.fs.makeDirectory( + repository === undefined ? folder : `${folder}/${repository}`, + { recursive: true }, + ); + yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); + // No thread owns this one, so it is listed and never removed. + const leftover = `${scratchRoot}/leftover`; + yield* fixture.fs.makeDirectory(leftover); + yield* fixture.fs.utimes(leftover, 1, 1); + fixture.setProjectRoots([scratchRoot]); + fixture.setStoredWorktreePaths([]); + if (policy !== undefined) fixture.setPolicy(policy); + if (scheduled) fixture.setScheduledThreadIds(["thread-1"]); + fixture.setThreads([ + shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), + ]); + const report = yield* fixture.service.runNow; + expect( + report.entries.map(({ path, outcome, reason }) => ({ path, outcome, reason })), + ).toEqual([ + { path: leftover, outcome: "kept", reason: "No thread uses this folder" }, + { path: folder, outcome: "kept", reason }, + ]); + expect(yield* fixture.fs.exists(`${folder}/notes.md`)).toBe(true); + }), + ), + ); + it.effect("keeps a thread's worktree folder that lost its .git link", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + fixture.setThreads([ + shell({ branch: "feature", worktreePath: fixture.worktree, archivedAt: at(-DAY_MS) }), + ]); + yield* fixture.fs.remove(`${fixture.worktree}/.git`); + yield* fixture.fs.makeDirectory(`${fixture.worktree}/node_modules`); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ path: fixture.worktree, outcome: "kept" }), + ]); + expect(yield* fixture.fs.exists(`${fixture.worktree}/node_modules`)).toBe(true); + }), + ), + ); + it.live("skips a stored worktree path whose parent is a regular file", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const legacyRoot = `${fixture.config.worktreesDir}/legacy-root`; + yield* fixture.fs.writeFileString(legacyRoot, ""); + fixture.setThreads([ + shell({ branch: "feature", worktreePath: `${legacyRoot}/stored-workspace` }), + ]); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([]); + expect(report.counts).toEqual({ removed: 0, kept: 0, failed: 0 }); + }), + ), + ); + it.live.each([ + ["before-check", "stored"], + ["while-measuring", "stored"], + ["before-check", "symlinked parent"], + ["while-measuring", "symlinked parent"], + ] as const)( + "keeps a worktree protected by a missing project root (%s, %s spelling)", + ([timing, spelling]) => runCleanupTest( Effect.gen(function* () { const fixture = yield* pausedMeasurementFixture(); + let worktree = fixture.worktree; + if (spelling === "symlinked parent") { + const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; + yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); + worktree = `${linkedParent}/feature`; + fixture.setThreads([shell({ branch: "feature", worktreePath: worktree })]); + } if (timing === "before-check") - fixture.setProjectRoots([fixture.repo, `${fixture.worktree}/removed-checkout`]); + fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); if (timing === "while-measuring") { yield* Deferred.await(fixture.measuring); - fixture.setProjectRoots([fixture.repo, `${fixture.worktree}/removed-checkout`]); + fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); } yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(cleanup); @@ -2168,9 +2833,14 @@ describe("storage cleanup reports and local file policies", () => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const storeDir = yield* fs.makeTempDirectoryScoped({ prefix: "pnpm-store-" }); + const statted: string[] = []; const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, + lstat: (target) => { + statted.push(target); + return fs.lstat(target); + }, stat: (target) => fs .stat(target) @@ -2211,6 +2881,9 @@ describe("storage cleanup reports and local file policies", () => { ); const report = yield* service.runNow; expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes }); + expect(statted.includes(`${nodeModules}/.pnpm/pkg@1.0.0/index.js`)).toBe( + store !== "same-device", + ); }), ), ); @@ -2244,12 +2917,13 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live.each([ + it.effect.each([ { days: 8, reason: "Inactive for 1 of 8 days" }, { days: null, reason: "No rules apply" }, ])("keeps an ineligible age/delete-only worktree without Git ($days)", ({ days, reason }) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: days, @@ -2259,9 +2933,7 @@ describe("storage cleanup reports and local file policies", () => { shell({ branch: "feature", worktreePath: fixture.worktree, - latestUserMessageAt: DateTime.makeUnsafe( - DateTime.toEpochMillis(yield* DateTime.now) - DAY_MS, - ), + latestUserMessageAt: at(-DAY_MS), }), ]); yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "local edit\n"); @@ -2305,7 +2977,18 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live("still removes a worktree when measuring its size fails", () => + it.live("removes a worktree whose .git file git-annex replaced with a symlink", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const { service, worktree, fs } = fixture; + yield* annexWorktree(fixture, worktree); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); + expect(yield* fs.exists(worktree)).toBe(false); + }), + ), + ); + it.live("keeps a worktree when the inspection cannot read its directories", () => runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -2316,13 +2999,48 @@ describe("storage cleanup reports and local file policies", () => { }), ); const report = yield* service.runNow; - expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes: null, files: null }); + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Worktree could not be fully inspected", + bytes: null, + files: null, + }); expect(report.bytesFreed).toBe(0); - expect(yield* fs.exists(worktree)).toBe(false); + expect(yield* fs.exists(worktree)).toBe(true); }), ), ); - it.live.each([ + it.effect("removes a worktree owned by a repository other than the project root", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + const { fs, command, config } = fixture; + const oldRepo = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-old-repo-" }), + ); + yield* command(oldRepo, ["init", "-b", "main"]); + yield* command(oldRepo, ["config", "user.email", "cleanup@example.test"]); + yield* command(oldRepo, ["config", "user.name", "Cleanup test"]); + yield* fs.writeFileString(`${oldRepo}/tracked.txt`, "original\n"); + yield* command(oldRepo, ["add", "."]); + yield* command(oldRepo, ["commit", "-m", "initial"]); + yield* fs.makeDirectory(`${config.worktreesDir}/old-repo`, { recursive: true }); + const oldWorktree = `${config.worktreesDir}/old-repo/feature`; + yield* command(oldRepo, ["worktree", "add", "-b", "feature", oldWorktree]); + fixture.setThreads([shell({ branch: "feature", worktreePath: oldWorktree })]); + const report = yield* fixture.service.runNow; + expect(report.entries.find((entry) => entry.path === oldWorktree)).toMatchObject({ + outcome: "removed", + }); + expect(yield* fs.exists(oldWorktree)).toBe(false); + expect((yield* command(oldRepo, ["worktree", "list", "--porcelain"])).stdout).not.toContain( + oldWorktree, + ); + }), + ), + ); + it.effect.each([ [ "its owner's branch is cleared", (worktree: string) => [shell({ branch: null, worktreePath: worktree, updatedAt: at(0) })], @@ -2359,6 +3077,7 @@ describe("storage cleanup reports and local file policies", () => { ] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const { fs, worktree } = fixture; fixture.setPolicy("tracked-changes"); @@ -2379,6 +3098,20 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("follows a branch switched while nothing watched the worktree", () => + runCleanupTest( + Effect.gen(function* () { + const { service, worktree, command, threadBranches } = yield* cleanupFixture(); + yield* command(worktree, ["switch", "-c", "renamed"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ + outcome: "kept", + reason: "Repository or branch changed", + }); + expect(threadBranches()).toEqual(["renamed"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); + }), + ), + ); it.live("does not measure a worktree kept for an open provider session", () => runCleanupTest( Effect.gen(function* () { @@ -2410,24 +3143,39 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps a worktree for a live session in a missing folder under its stored alias", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; + yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); + fixture.setThreads([shell({ branch: "feature", worktreePath: `${linkedParent}/feature` })]); + fixture.setOpenSessionCwd(`${linkedParent}/feature/removed-folder`); + const report = yield* fixture.service.runNow; + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Provider session is still open", + }); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }), + ), + ); it.live("compares the checked-out branch without a full status", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, command, setThreads, fullStatusCalls } = + const { service, fs, repo, worktree, command, fullStatusCalls, threadBranches } = yield* cleanupFixture(); const changed = { outcome: "kept", reason: "Repository or branch changed" }; yield* command(worktree, ["checkout", "--detach"]); expect((yield* service.runNow).entries[0]).toMatchObject(changed); yield* command(worktree, ["switch", "--orphan", "other"]); expect((yield* service.runNow).entries[0]).toMatchObject(changed); - yield* command(worktree, ["switch", "-c", "(feature)", "feature"]); - setThreads([shell({ branch: "(feature)", worktreePath: worktree })]); - expect((yield* service.runNow).entries[0]).toMatchObject(changed); - setThreads([shell({ branch: "feature", worktreePath: worktree })]); yield* command(worktree, ["tag", "feature", "feature"]); // Newer Git refuses to create a tag named HEAD, but still reads one. yield* command(worktree, ["update-ref", "refs/tags/HEAD", "refs/heads/feature"]); yield* command(worktree, ["switch", "feature"]); + expect((yield* service.runNow).entries[0]).toMatchObject(changed); + expect(threadBranches()).toEqual(["feature"]); const index = (yield* command(worktree, ["rev-parse", "--git-path", "index"])).stdout; yield* fs.writeFileString(`${index.trim()}.lock`, ""); const locked = (yield* service.runNow).entries[0]; @@ -2494,7 +3242,7 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live.each([ + it.effect.each([ ["unchanged", "removed", "No commits beyond the project branch"], ["unmerged", "kept", "Has commits beyond the project branch"], ["detached", "kept", "Project branch is unavailable"], @@ -2502,6 +3250,7 @@ describe("storage cleanup reports and local file policies", () => { ] as const)("cleans archived local-only worktrees: %s", ([state, outcome, reason]) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: state !== "merged-only", @@ -2524,15 +3273,55 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps an unsettled new thread's unchanged worktree after its first turn", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, setThreads } = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 11, + worktreeOnMerge: true, + worktreeUnchanged: true, + }); + const now = yield* DateTime.now; + const minutesAgo = (minutes: number) => DateTime.subtract(now, { minutes }); + const thread = shell({ + branch: "feature", + worktreePath: worktree, + status: "completed", + createdAt: minutesAgo(40), + latestUserMessageAt: minutesAgo(40), + latestRunRequestedAt: minutesAgo(40), + latestRunStartedAt: minutesAgo(40), + latestRunCompletedAt: minutesAgo(20), + updatedAt: minutesAgo(20), + }); + setThreads([thread]); + + const report = yield* service.runNow; + expect(report.entries[0]).toMatchObject({ outcome: "kept" }); + expect(yield* fs.exists(worktree)).toBe(true); + + setThreads([{ ...thread, settledAt: minutesAgo(10), updatedAt: minutesAgo(10) }]); + const settled = yield* service.runNow; + expect(settled.entries[0]).toMatchObject({ + outcome: "removed", + reason: "No commits beyond the project branch", + }); + }), + ), + ); it.live( "discovers trunk without a remote HEAD or tracking ref and removes an integrated worktree", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, command } = yield* cleanupFixture({ + const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); + setThreads([ + shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), + ]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); @@ -2554,10 +3343,13 @@ describe("storage cleanup reports and local file policies", () => { () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, command } = yield* cleanupFixture({ + const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); + setThreads([ + shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), + ]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); @@ -2582,10 +3374,11 @@ describe("storage cleanup reports and local file policies", () => { it.live("keeps the worktree when the remote default is unavailable even if main exists", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, command } = yield* cleanupFixture({ + const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); + setThreads([shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) })]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); @@ -2663,6 +3456,120 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live.each(["--assume-unchanged", "--skip-worktree"] as const)( + "keeps tracked edits that git status hides (%s)", + (flag) => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, command } = yield* cleanupFixture(); + yield* command(worktree, ["update-index", flag, "tracked.txt"]); + yield* fs.writeFileString(`${worktree}/tracked.txt`, "hidden edit\n"); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); + expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("hidden edit\n"); + }), + ), + ); + // macOS and Windows file systems reject names that are not valid UTF-8. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "keeps hidden edits to files whose names are not valid UTF-8", + () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, command } = yield* cleanupFixture(); + const git = yield* GitVcsDriver.GitVcsDriver; + // Git unquotes C-quoted paths on stdin, which reaches a name a JS string cannot. + const quoted = '"bad-\\377.txt"'; + const stdin = (args: string[], input: string) => + git.execute({ operation: "cleanup-test", cwd: worktree, args, stdin: input }); + const blob = (content: string) => + stdin(["hash-object", "-w", "--stdin"], content).pipe( + Effect.map((result) => result.stdout.trim()), + ); + const original = yield* blob("original\n"); + yield* stdin(["update-index", "--index-info"], `100644 ${original}\t${quoted}\n`); + yield* stdin(["checkout-index", "--stdin"], `${quoted}\n`); + yield* command(worktree, ["commit", "-m", "bad name"]); + // The committed content moves on while the file on disk keeps the other version. + const edited = yield* blob("edited\n"); + yield* stdin(["update-index", "--index-info"], `100644 ${edited}\t${quoted}\n`); + yield* command(worktree, ["commit", "-m", "edit"]); + yield* stdin(["update-index", "--assume-unchanged", "--stdin"], `${quoted}\n`); + expect((yield* command(worktree, ["status", "--porcelain"])).stdout).toBe(""); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept" }); + expect((yield* fs.readDirectory(worktree)).some((name) => name.startsWith("bad-"))).toBe( + true, + ); + }), + ), + ); + it.live("removes worktrees whose flagged files are unchanged or outside a sparse checkout", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, command } = yield* cleanupFixture(); + yield* command(worktree, ["update-index", "--skip-worktree", "tracked.txt"]); + yield* fs.remove(`${worktree}/tracked.txt`); + yield* command(worktree, ["update-index", "--assume-unchanged", ".gitignore"]); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); + }), + ), + ); + it.live.each([ + ["missing", "symlink"], + ["tracked.txt", "symlink"], + ["missing", "file"], + ["tracked.txt", "file"], + ] as const)("compares flagged tracked symlinks by target (%s as a %s)", ([target, kind]) => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, command } = yield* cleanupFixture(); + yield* fs.symlink("tracked.txt", `${worktree}/link`); + yield* command(worktree, ["add", "link"]); + yield* command(worktree, ["commit", "-m", "link"]); + yield* command(worktree, ["update-index", "--assume-unchanged", "link"]); + yield* fs.remove(`${worktree}/link`); + // Without core.symlinks, Git checks a link out as a regular file holding its target. + if (kind === "file") { + yield* command(worktree, ["config", "core.symlinks", "false"]); + yield* fs.writeFileString(`${worktree}/link`, target); + } else yield* fs.symlink(target, `${worktree}/link`); + expect((yield* service.runNow).entries[0]).toMatchObject( + target === "missing" + ? { outcome: "kept", reason: expect.stringContaining("(link)") } + : { outcome: "removed" }, + ); + }), + ), + ); + it.live.each([ + ["uncommitted-changes", "untracked", "Local changes exceed the inspection limit"], + ["any-local-files", "ignored", "Ignored files exceed the inspection limit"], + ] as const)( + "keeps a worktree under %s when its %s file listing exceeds the inspection limit", + ([policy, kind, reason]) => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); + setPolicy(policy); + const files = Array.from({ length: 3000 }, (_, i) => + kind === "untracked" + ? `${worktree}/many/untracked-file-with-a-long-name-${i}.txt` + : `${worktree}/many/ignored-directory-with-a-long-name-${i}/.env`, + ); + yield* fs.makeDirectory(`${worktree}/many`); + yield* Effect.forEach( + files, + (file) => + Effect.gen(function* () { + if (kind === "ignored") yield* fs.makeDirectory(file.slice(0, -"/.env".length)); + yield* fs.writeFileString(file, "local\n"); + }), + { concurrency: 64, discard: true }, + ); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "kept", reason }); + expect(yield* fs.exists(files[0]!)).toBe(true); + }), + ), + ); it.live("serializes concurrent requests and returns each run's report", () => runCleanupTest( Effect.gen(function* () { @@ -2777,11 +3684,12 @@ describe("storage cleanup reports and local file policies", () => { }); describe("settled worktree rechecks", () => { - it.live.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)( + it.effect.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)( "keeps a usage-limited checkout when %s is enabled during measurement", (preference) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); fixture.setSettings({ autoResumeLimitedThreads: false, snoozeLimitedThreads: false }); fixture.setThreads([ @@ -2799,16 +3707,20 @@ describe("settled worktree rechecks", () => { fixture.setSettings({ [preference]: true }); yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(run); - expect(report.entries[0]?.outcome).toBe("kept"); + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Settings changed since check", + }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); - it.live.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( + it.effect.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( "keeps a checkout changed during measurement (%j)", (change) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const thread = shell({ branch: "feature", @@ -2836,9 +3748,10 @@ describe("settled worktree rechecks", () => { ); }); -it.live("keeps saved usage data when removing a settled checkout", () => +it.effect("keeps saved usage data when removing a settled checkout", () => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); fixture.setSettings({ storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0 }, diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index a1f49efea7..348c60d3ae 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -1,10 +1,14 @@ // apps/server/src/storageCleanup.ts // removes eligible managed artifacts while retaining active or changed work +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFSP from "node:fs/promises"; import { + CheckpointScopeId, GitCommandError, OrchestrationV2AppThreadJson, OrchestrationV2ProviderSessionJson, } from "@t3tools/contracts"; +import * as Base64Url from "effect/encoding/Base64Url"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import type { @@ -19,6 +23,7 @@ import type { ThreadId, } from "@t3tools/contracts"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; +import { resolveWorktreeT3Home } from "@t3tools/shared/devHome"; import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -39,17 +44,23 @@ import { parse as parseYaml } from "yaml"; import * as ServerConfig from "./config.ts"; import * as GitManager from "./git/GitManager.ts"; +import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; +import { scratchFolderRoot } from "./project/ManagedProjectFolders.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; +import { checkpointRefForScopeOrdinal } from "./orchestration-v2/CheckpointService.ts"; import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts"; +import { MAX_OVERDUE_ARM_MS } from "./orchestration-v2/UsageLimitRecoveryWorker.ts"; +import * as WorktreeBranchSync from "./orchestration-v2/WorktreeBranchSync.ts"; import { forkParked } from "./serverActivation.ts"; import * as Settings from "./serverSettings.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; -import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts"; +import { isNonRepositoryGitStderr } from "./vcs/GitVcsDriverCore.ts"; +import { isLinkedWorktree, removeLinkedWorktree } from "./vcs/worktreeRemoval.ts"; import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -78,6 +89,15 @@ class PnpmModulesManifestParseError extends Schema.TaggedError()( + "WorktreeDirectoryReadError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read a worktree directory."; + } +} + const DAY_MS = 86_400_000; // Give settle scripts time to open terminals that protect the worktree. const SETTLE_SCRIPT_GRACE_MS = 60_000; @@ -87,6 +107,8 @@ const ORPHAN_WORKTREE_GRACE_MS = 60 * 60 * 1_000; const sentence = (text: string) => text.charAt(0).toUpperCase() + text.slice(1); const REPORT_ENTRY_LIMIT = 200; const isGitCommandError = Schema.is(GitCommandError); +const errorCode = (error: PlatformError) => + error.cause instanceof Error && "code" in error.cause ? error.cause.code : undefined; function cleanupFailureReason(error: { readonly message: string }) { return isGitCommandError(error) @@ -181,10 +203,12 @@ function heldForLimitRecovery( // An auto-resume holds until its continuation replaces the failed run. return recovery.autoResume || (recovery.snooze === true && resetMs > now); // The recovery worker arms this failure on a later tick; hold it until then. - // Like the worker, skip a reset that had already passed when the run ended. + // Like the worker, skip a reset that had already passed when the run ended + // or that is too overdue to arm. if ( !Number.isFinite(resetMs) || - resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) + resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) || + now - resetMs > MAX_OVERDUE_ARM_MS ) return false; return settings.autoResumeLimitedThreads || (settings.snoozeLimitedThreads && resetMs > now); @@ -304,6 +328,8 @@ const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const git = yield* GitVcsDriver.GitVcsDriver; const gitManager = yield* GitManager.GitManager; + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const reconcileBranch = yield* WorktreeBranchSync.makeReconcile; const terminals = yield* TerminalManager.TerminalManager; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -330,20 +356,6 @@ const make = Effect.gen(function* () { !path.isAbsolute(relative) ); }; - const hasTerminal = (worktreePath: string) => - [...liveTerminals.values()] - .flatMap((entries) => [...entries.values()]) - .some((terminal) => { - if (terminal.status !== "starting" && terminal.status !== "running") return false; - const cwd = path.resolve(terminal.cwd); - return ( - (terminal.worktreePath !== null && - pathKey(terminal.worktreePath) === pathKey(worktreePath)) || - pathKey(cwd) === pathKey(worktreePath) || - inside(worktreePath, cwd) - ); - }); - // pnpm imports packages by clone or reflink when its store shares a device // with the worktree. Those files have one link but share blocks with the // store, so removing them frees almost nothing. A store on another device @@ -374,52 +386,107 @@ const make = Effect.gen(function* () { ); const measureWorktree = Effect.fn("storageCleanup.measureWorktree")( - function* (worktreePath: string) { + function* (worktreePath: string, inspectRepositories: boolean | "plain-folder" = false) { const root = yield* fs.realPath(worktreePath); const skipped = yield* sharedPnpmVirtualStore(root); + const incomplete = { bytes: null, reason: "worktree could not be fully inspected" }; + // A plain folder is not a checkout, so a repository at its root counts like one below it. + const repositories = new Set(inspectRepositories === "plain-folder" ? [] : [pathKey(root)]); + const moduleStores: string[] = []; + if (inspectRepositories === true && (yield* fs.exists(path.join(root, ".gitmodules")))) { + const submodules = yield* git.execute({ + operation: "StorageCleanup.nestedRepositories", + cwd: root, + args: [ + "submodule", + "foreach", + "--recursive", + "--quiet", + 'printf "%s\\0" "$toplevel/$sm_path"', + ], + maxOutputBytes: 64 * 1024, + }); + if (submodules.stdoutTruncated || submodules.stderrTruncated) return incomplete; + for (const submodule of submodules.stdout.split("\0").filter(Boolean)) { + repositories.add(pathKey(path.resolve(submodule))); + repositories.add(pathKey(path.resolve(submodule, ".git"))); + moduleStores.push(pathKey(path.resolve(submodule, ".git", "modules"))); + } + } + // Git status omits ignored repositories, and worktree remove deletes them. + // Registered submodules have their own recursive safety checks. + const isNestedRepository = (target: string, names: ReadonlyArray) => { + const key = pathKey(target); + if ( + repositories.has(key) || + moduleStores.some((store) => key === store || inside(store, key)) + ) + return false; + const markers = new Set(names.map((name) => name.toLowerCase())); + return ( + markers.has(".git") || + (markers.has("head") && markers.has("objects") && markers.has("refs")) + ); + }; const pending = [root]; let entries = 1; let bytes = 0; while (pending.length > 0) { - const target = pending.pop()!; - if (target === skipped) continue; - // Effect's stat follows links. Probe with readLink first to get lstat - // semantics, including skipping dangling links and directory links. - const isLink = yield* fs.readLink(target).pipe( - Effect.as(true), - Effect.catchIf( - (error) => - error.cause instanceof Error && - "code" in error.cause && - error.cause.code === "EINVAL", - () => Effect.succeed(false), - ), + const inspected = yield* Effect.forEach( + pending.splice(-8), + // Untraced: this runs once per entry, and a worktree can hold millions. + Effect.fnUntraced(function* (target) { + const empty = { target, bytes: 0, names: [], children: [] }; + const inStore = skipped !== null && (target === skipped || inside(skipped, target)); + if (inStore && !inspectRepositories) return empty; + const stat = yield* fs.lstat(target); + if (stat.type === "SymbolicLink") return empty; + if ((yield* fs.realPath(target)) !== target) return null; + if (stat.type === "Directory") { + if (!inStore) { + const names = yield* fs.readDirectory(target); + return { target, bytes: 0, names, children: names }; + } + // The store is excluded from reclaimed bytes; only walk its directories. + const dirents = yield* Effect.tryPromise({ + try: () => NodeFSP.readdir(target, { withFileTypes: true }), + catch: (cause) => new WorktreeDirectoryReadError({ cause }), + }); + return { + target, + bytes: 0, + names: dirents.map((entry) => entry.name), + children: dirents.filter((entry) => entry.isDirectory()).map((entry) => entry.name), + }; + } + // Removing a shared hardlink leaves its blocks allocated. + if (stat.type !== "File" || Option.getOrElse(stat.nlink, () => 1n) !== 1n) return empty; + const bytes = Option.match(stat.blocks, { + onNone: () => Number(stat.size), + onSome: (blocks) => Number(blocks * 512n), + }); + return { ...empty, bytes }; + }), + { concurrency: "unbounded" }, ); - if (isLink) continue; - if ((yield* fs.realPath(target)) !== target) return null; - const stat = yield* fs.stat(target); - if (stat.type === "File") { - // Removing a shared hardlink leaves its blocks allocated. - if (Option.getOrElse(stat.nlink, () => 1n) !== 1n) continue; - bytes += Option.match(stat.blocks, { - onNone: () => Number(stat.size), - onSome: (blocks) => Number(blocks * 512n), - }); - } else if (stat.type === "Directory") { - const names = yield* fs.readDirectory(target); - entries += names.length; - if (entries > 2_000_000) return null; - for (const name of names) { - const child = path.join(target, name); - if (!inside(root, child)) return null; + for (const result of inspected) { + if (result === null) return incomplete; + if (inspectRepositories && isNestedRepository(result.target, result.names)) + return { bytes: null, reason: "contains a nested Git repository" }; + bytes += result.bytes; + entries += result.names.length; + if (entries > 2_000_000) return incomplete; + for (const name of result.children) { + const child = path.join(result.target, name); + if (!inside(root, child)) return incomplete; pending.push(child); } } } - return bytes; + return { bytes, reason: null }; }, Effect.timeout("30 seconds"), - Effect.orElseSucceed(() => null), + Effect.orElseSucceed(() => ({ bytes: null, reason: "worktree could not be fully inspected" })), ); // Large snapshots take seconds; use the reader worker instead of blocking the event loop. @@ -430,18 +497,21 @@ const make = Effect.gen(function* () { }); const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* ( - worktreePath: string, + worktreePaths: ReadonlyArray, projects: ReadonlyArray<{ readonly workspaceRoot: string }>, ) { + const contains = (projectPath: string) => + worktreePaths.some( + (worktreePath) => + pathKey(projectPath) === pathKey(worktreePath) || inside(worktreePath, projectPath), + ); for (const project of projects) { const projectPath = path.resolve(project.workspaceRoot); - if (pathKey(projectPath) === pathKey(worktreePath) || inside(worktreePath, projectPath)) - return true; + if (contains(projectPath)) return true; const realPath = yield* fs .realPath(projectPath) .pipe(Effect.orElseSucceed(() => projectPath)); - if (pathKey(realPath) === pathKey(worktreePath) || inside(worktreePath, realPath)) - return true; + if (contains(realPath)) return true; } return false; }); @@ -450,6 +520,7 @@ const make = Effect.gen(function* () { roots: ReadonlyArray, projects: ReadonlyArray<{ readonly workspaceRoot: string }>, entries: StorageCleanupReportEntry[], + scratchRoot: string | null, ) { const rows = yield* sql<{ worktreePath: string }>` SELECT DISTINCT json_extract(payload_json, '$.worktreePath') AS "worktreePath" @@ -488,12 +559,14 @@ const make = Effect.gen(function* () { (root) => !inside(root, managedRoot) && (pathKey(root) === pathKey(target) || inside(root, target)), ); - const directories = Effect.fnUntraced(function* (parent: string, managedRoot: string) { - if (inProject(parent, managedRoot)) return []; + // The scratch root is itself a project, so its folders skip the project check. + const directories = Effect.fnUntraced(function* (parent: string, managedRoot: string | null) { + const skipped = (target: string) => managedRoot !== null && inProject(target, managedRoot); + if (skipped(parent)) return []; const result: string[] = []; for (const name of yield* fs.readDirectory(parent).pipe(Effect.orElseSucceed(() => []))) { const target = path.join(parent, name); - if (!inside(parent, target) || inProject(target, managedRoot)) continue; + if (!inside(parent, target) || skipped(target)) continue; const directory = yield* Effect.gen(function* () { if (pathKey(yield* fs.realPath(target)) !== pathKey(target)) return false; return (yield* fs.stat(target)).type === "Directory"; @@ -508,7 +581,7 @@ const make = Effect.gen(function* () { let firstMeasurement = true; const reported = new Set(); const report = Effect.fnUntraced( - function* (worktreePath: string) { + function* (worktreePath: string, scratch = false) { const key = pathKey(worktreePath); if ( reported.has(key) || @@ -520,7 +593,7 @@ const make = Effect.gen(function* () { const modified = Option.getOrNull((yield* fs.stat(worktreePath)).mtime); if (modified !== null && modified.getTime() > now - ORPHAN_WORKTREE_GRACE_MS) return; const gitPath = path.join(worktreePath, ".git"); - const linked = (yield* fs.exists(gitPath)) && (yield* fs.stat(gitPath)).type === "File"; + const linked = (yield* fs.exists(gitPath)) && (yield* isLinkedWorktree(worktreePath)); reported.add(key); const remaining = measurementDeadline - (yield* Clock.currentTimeMillis); if (!orphanSizes.has(key) && (firstMeasurement || remaining > 0)) { @@ -528,7 +601,7 @@ const make = Effect.gen(function* () { firstMeasurement ? Effect.asSome : Effect.timeoutOption(remaining), ); firstMeasurement = false; - if (Option.isSome(measured)) orphanSizes.set(key, measured.value); + if (Option.isSome(measured)) orphanSizes.set(key, measured.value.bytes); } const bytes = orphanSizes.get(key) ?? null; entries.push({ @@ -536,7 +609,9 @@ const make = Effect.gen(function* () { outcome: "kept", reason: linked ? "No thread uses this worktree" - : "No thread uses this folder, and it isn't a git worktree", + : scratch + ? "No thread uses this folder" + : "No thread uses this folder, and it isn't a git worktree", path: worktreePath, projectPath: null, threadId: null, @@ -563,7 +638,7 @@ const make = Effect.gen(function* () { (worktree) => Effect.gen(function* () { if (pathKey(yield* fs.realPath(worktree)) !== pathKey(worktree)) return false; - return (yield* fs.stat(path.join(worktree, ".git"))).type === "File"; + return yield* isLinkedWorktree(worktree); }).pipe(Effect.orElseSucceed(() => false)), ); }); @@ -574,7 +649,7 @@ const make = Effect.gen(function* () { if (referenced.has(pathKey(projectDirectory))) return; const gitPath = path.join(projectDirectory, ".git"); if (yield* fs.exists(gitPath)) { - if ((yield* fs.stat(gitPath)).type === "File") yield* report(projectDirectory); + if (yield* isLinkedWorktree(projectDirectory)) yield* report(projectDirectory); return; } for (const worktreePath of yield* directories(projectDirectory, root)) { @@ -584,6 +659,8 @@ const make = Effect.gen(function* () { }).pipe(Effect.orElseSucceed(() => undefined)); } } + if (scratchRoot !== null) + for (const folder of yield* directories(scratchRoot, null)) yield* report(folder, true); for (const key of orphanSizes.keys()) { if (!reported.has(key)) orphanSizes.delete(key); } @@ -620,8 +697,7 @@ const make = Effect.gen(function* () { ); if (result === null) return null; if (result.exitCode === 0 || result.exitCode === allowedExitCode) return result; - if (/not a git repository|gitfile does not point to a valid repository/i.test(result.stderr)) - return null; + if (isNonRepositoryGitStderr(result.stderr)) return null; return yield* failure( result.stderr.trim().split(/\r?\n/)[0]?.slice(0, 1000) || "command failed", ); @@ -637,7 +713,130 @@ const make = Effect.gen(function* () { if (head === null) return true; const ref = head.exitCode === 0 ? head.stdout.trim() : ""; const name = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length).trim() : null; - return (name?.startsWith("(") ? null : name) !== branch; + return name !== branch; + }); + + // Nothing watches an idle worktree, so its threads still record the branch it left. + // Record the checked-out one so the next sweep can apply the rules to it. + const followBranch = Effect.fn("StorageCleanup.followBranch")( + function* (worktreePath: string) { + const cwd = yield* fs.realPath(worktreePath); + yield* reconcileBranch({ cwd, refName: yield* gitWorkflow.currentBranch(cwd) }); + }, + (effect, worktreePath) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to reconcile worktree branch", { cwd: worktreePath, cause }), + ), + ), + ); + + // Git status and non-forced worktree removal both skip assume-unchanged and skip-worktree files. + const hiddenTrackedChange = Effect.fn("StorageCleanup.hiddenTrackedChange")(function* ( + cwd: string, + ) { + const inspect = (args: string[], stdin?: string) => + git.execute({ + operation: "StorageCleanup.hiddenTrackedChanges", + cwd, + args, + ...(stdin === undefined ? {} : { stdin }), + maxOutputBytes: 1024 * 1024, + }); + const sparse = yield* inspect([ + "config", + "--type=bool", + "--default=false", + "core.sparseCheckout", + ]); + // Sparse checkouts flag every file outside the cone; Git 2.37+ unflags those it finds on disk. + const hiddenTag = sparse.stdout.trim() === "true" ? /^[a-z]$/ : /^(?:S|[a-z])$/; + const flagged: Array<{ readonly mode: string; readonly id: string; readonly file: string }> = + []; + let overflow = false; + yield* git.execute({ + operation: "StorageCleanup.hiddenTrackedChanges", + cwd, + args: ["-c", "core.quotePath=false", "ls-files", "-s", "-v"], + maxOutputBytes: 64 * 1024, + appendTruncationMarker: true, + keepLineCallbacksAfterTruncation: true, + progress: { + onStdoutLine: (line) => + Effect.sync(() => { + const match = /^(\S) (\d+) ([0-9a-f]+) \d\t(.*)$/s.exec(line); + if (match === null || !hiddenTag.test(match[1]!) || match[2] === "160000") return; + if (flagged.length < 10_000) + flagged.push({ mode: match[2]!, id: match[3]!, file: match[4]! }); + else overflow = true; + }), + }, + }); + if (overflow) return "hidden tracked files exceed the inspection limit"; + const reason = (file: string) => `has uncommitted changes hidden from git status (${file})`; + // Quoted names (control characters, quotes, backslashes) and names that are not valid UTF-8 + // decode to text that is not the path on disk. + const unreadable = flagged.find(({ file }) => file.startsWith('"') || file.includes("\uFFFD")); + if (unreadable !== undefined) return reason(unreadable.file); + const onDisk = yield* Effect.forEach( + flagged, + (entry) => { + const file = path.join(cwd, entry.file); + return fs.readLink(file).pipe( + Effect.map((target) => ({ ...entry, type: "SymbolicLink", target })), + Effect.catchIf( + (error) => errorCode(error) === "EINVAL", + () => fs.stat(file).pipe(Effect.map((info) => ({ ...entry, type: info.type }))), + ), + Effect.catchIf( + (error) => errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR", + () => Effect.succeed(null), + ), + ); + }, + { concurrency: 16 }, + ); + const files: Array<{ readonly id: string; readonly file: string }> = []; + // Without core.symlinks a tracked link is a regular file holding its target, compared unfiltered. + const linkFiles: typeof files = []; + for (const entry of onDisk) { + if (entry === null) continue; + if (entry.type === "File") (entry.mode === "120000" ? linkFiles : files).push(entry); + else if (!("target" in entry) || entry.mode !== "120000") return reason(entry.file); + // Hashing a link's path would hash the file it points to. + else if ( + (yield* inspect(["hash-object", "--stdin"], entry.target)).stdout.trim() !== entry.id + ) + return reason(entry.file); + } + const hashPaths = (entries: ReadonlyArray<{ readonly file: string }>, flags: string[]) => + entries.length === 0 + ? Effect.succeed([]) + : inspect( + ["hash-object", ...flags, "--stdin-paths"], + entries.map(({ file }) => `${file}\n`).join(""), + ).pipe(Effect.map((result) => result.stdout.split("\n"))); + const worktreeIds = yield* hashPaths(files, []); + const linkIds = yield* hashPaths(linkFiles, ["--no-filters"]); + const changed = + files.find(({ id }, i) => worktreeIds[i] !== id) ?? + linkFiles.find(({ id }, i) => linkIds[i] !== id); + return changed === undefined ? null : reason(changed.file); + }); + + // A worktree can outlive its project moving to another clone. Git removes a + // worktree through the repository that registered it, not through the + // project's current checkout, so resolve the owning repository first. + const worktreeRepository = Effect.fn("StorageCleanup.worktreeRepository")(function* ( + worktreePath: string, + ) { + const commonDir = yield* git.execute({ + operation: "StorageCleanup.worktreeRepository", + cwd: worktreePath, + args: ["rev-parse", "--git-common-dir"], + }); + const resolved = path.resolve(worktreePath, commonDir.stdout.trim()); + return path.basename(resolved) === ".git" ? path.dirname(resolved) : resolved; }); const localChangesReason = Effect.fn("StorageCleanup.localChangesReason")(function* ( @@ -657,6 +856,7 @@ const make = Effect.gen(function* () { : "--untracked-files=all", ], maxOutputBytes: 64 * 1024, + appendTruncationMarker: true, }); if (status.stdoutTruncated) return "local changes exceed the inspection limit"; const records = status.stdout.split("\0").filter(Boolean); @@ -666,12 +866,15 @@ const make = Effect.gen(function* () { if (/^[RC]|^.[RC]/.test(records[i]!)) i++; } if (count > 0) return `has uncommitted changes (${count} ${count === 1 ? "file" : "files"})`; + const hidden = yield* hiddenTrackedChange(cwd); + if (hidden !== null) return hidden; if (rules.worktreeKeepWhen !== "any-local-files") return null; const ignored = yield* git.execute({ operation: "StorageCleanup.ignoredFiles", cwd, args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], maxOutputBytes: 64 * 1024, + appendTruncationMarker: true, }); if (ignored.stdoutTruncated) return "ignored files exceed the inspection limit"; const file = ignored.stdout @@ -733,6 +936,8 @@ const make = Effect.gen(function* () { "rev-list", "--max-count=1", "HEAD", + // Checkpoint refs hold workspace snapshots, not commits a user could lose. + "--exclude=refs/t3/*", "--all", "--reflog", "--not", @@ -827,18 +1032,50 @@ const make = Effect.gen(function* () { let waiting = false; const kept: string[] = []; const roots: Array = []; - for (const directory of managedWorktreesDirectories( - serverSettings, - config.worktreesDir, - path, - yield* HostProcess.HomeDirectory, - )) { + // A git worktree's dev home is seeded from real data, so its threads and any + // copied settings can point at the developer's real worktrees. + const isWorktreeDevHome = + (yield* resolveWorktreeT3Home(config.baseDir)) === path.resolve(config.baseDir); + for (const directory of isWorktreeDevHome + ? [config.worktreesDir] + : managedWorktreesDirectories( + serverSettings, + config.worktreesDir, + path, + yield* HostProcess.HomeDirectory, + )) { const root = yield* fs.exists(directory).pipe( Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))), Effect.orElseSucceed(() => null), ); if (root !== null && !isFilesystemRoot(root, path)) roots.push(root); } + const scratchRoot = yield* fs + .realPath(scratchFolderRoot(config.baseDir, path)) + .pipe(Effect.orElseSucceed(() => null)); + // Nothing can bring a scratch folder's files back, so these hold whatever the retention says. + const scratchKeepReason = Effect.fn("StorageCleanup.scratchKeepReason")(function* ( + folder: string, + threadIds: ReadonlyArray, + rules: WorktreeCleanupRules, + ) { + const realParent = yield* fs.realPath(path.dirname(folder)); + if ((yield* fs.realPath(folder)) !== path.join(realParent, path.basename(folder))) + return "folder is a symbolic link"; + // Every file here is untracked, and only "tracked-changes" lets cleanup delete those. + if (rules.worktreeKeepWhen !== "tracked-changes") { + const file = (yield* fs.readDirectory(folder)).find((name) => name !== "node_modules"); + if (file !== undefined) return `has local files (${file})`; + } + // Each run of a scheduled task works on what its earlier runs left in the folder. + const scheduled = yield* sql<{ threadId: string }>` + SELECT thread_id AS "threadId" FROM scheduled_tasks + WHERE enabled = 1 AND thread_id IS NOT NULL + `.pipe(NodeSqliteClient.readOnly); + if (scheduled.some((task) => threadIds.includes(task.threadId))) + return "thread has a scheduled task"; + return null; + }); const worktreePathReason = Effect.fn("StorageCleanup.worktreePathReason")(function* ( worktreePath: string, ) { @@ -849,8 +1086,10 @@ const make = Effect.gen(function* () { return "worktree is a symbolic link"; if (!roots.some((root) => inside(root, realPath))) return "outside the managed worktree folder"; - if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") - return "not a linked worktree"; + const linked = yield* isLinkedWorktree(worktreePath).pipe( + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)), + ); + if (!linked) return "not a linked worktree"; return null; }); const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>` @@ -868,20 +1107,58 @@ const make = Effect.gen(function* () { const threadsById = new Map(snapshot.threads.map((thread) => [thread.id, thread])); const refreshedDefaultRefs = new Map>(); const defaultBranches = new Map(); - const groups = Map.groupBy( - snapshot.threads.filter((thread) => thread.worktreePath !== null), - (thread) => path.resolve(thread.worktreePath!), + // Threads may store one checkout through different symlinked spellings; compare real paths. + // Keys are only compared, never opened, so they take pathKey's Windows case folding. + const canonicalPaths = new Map(); + const canonical = Effect.fnUntraced(function* (target: string) { + const resolved = path.resolve(target); + const cached = canonicalPaths.get(resolved); + if (cached !== undefined) return cached; + const realPath = yield* fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)); + const key = pathKey(realPath); + canonicalPaths.set(resolved, key); + return key; + }); + // A cwd in a deleted folder cannot be resolved, so stored spellings are compared too. + const occupies = Effect.fnUntraced(function* ( + worktreePaths: ReadonlyArray, + target: string, + ) { + const targets = [path.resolve(target), yield* canonical(target)]; + return worktreePaths.some((worktree) => + targets.some((cwd) => pathKey(cwd) === pathKey(worktree) || inside(worktree, cwd)), + ); + }); + const hasTerminal = Effect.fnUntraced(function* (worktreePaths: ReadonlyArray) { + for (const terminal of [...liveTerminals.values()].flatMap((entries) => [ + ...entries.values(), + ])) { + if (terminal.status !== "starting" && terminal.status !== "running") continue; + if ( + (terminal.worktreePath !== null && + (yield* occupies(worktreePaths, terminal.worktreePath))) || + (yield* occupies(worktreePaths, terminal.cwd)) + ) + return true; + } + return false; + }); + const liveThreads = snapshot.threads.filter((thread) => thread.worktreePath !== null); + const liveKeys = yield* Effect.forEach(liveThreads, (thread) => + canonical(thread.worktreePath!), ); - const deletedByPath = Map.groupBy(deletedThreads, (thread) => - path.resolve(thread.worktreePath!), + const groups = Map.groupBy(liveThreads, (_thread, index) => liveKeys[index]!); + const deletedKeys = yield* Effect.forEach(deletedThreads, (thread) => + canonical(thread.worktreePath!), ); + const deletedByPath = Map.groupBy(deletedThreads, (_thread, index) => deletedKeys[index]!); const candidates = [ ...[...groups].map( - ([worktreePath, group]) => + ([worktreeKey, group]) => // A deleted thread still owns the worktree its remaining subagents share, // but only deletion cleanup acts on it; otherwise the live rules apply. deletedByPath - .get(worktreePath) + .get(worktreeKey) ?.find( (deleted) => resolveWorktreeCleanup(serverSettings, deleted.projectId).worktreeOnDelete && @@ -890,13 +1167,20 @@ const make = Effect.gen(function* () { worktreeOwner(group) ?? group[0]!, ), - ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))), + ...deletedThreads.filter((_thread, index) => !groups.has(deletedKeys[index]!)), ]; for (const thread of candidates) { const settings = resolveWorktreeCleanup(serverSettings, thread.projectId); if (!worktreeCleanupEnabled(settings)) continue; const worktreePath = path.resolve(thread.worktreePath!); - const group = groups.get(worktreePath) ?? []; + const worktreeKey = yield* canonical(worktreePath); + const worktreePaths = [worktreePath, worktreeKey]; + const group = groups.get(worktreeKey) ?? []; + // No project threads have no branch; their folders sit directly in the scratch root. + const scratch = + thread.branch === null && + scratchRoot !== null && + pathKey(path.dirname(worktreeKey)) === pathKey(scratchRoot); const activityAt = Math.max(...group.map(storageCleanupActivityAt)); const deleted = "workspaceRoot" in thread; const settlementChain = deleted @@ -928,19 +1212,27 @@ const make = Effect.gen(function* () { return reason; }; yield* Effect.gen(function* () { - if (!(yield* fs.exists(worktreePath))) return; + const exists = yield* fs.exists(worktreePath).pipe( + // A stored path under a regular file cannot exist, but access() fails with ENOTDIR. + Effect.catchIf( + (error) => + error.cause instanceof Error && + "code" in error.cause && + error.cause.code === "ENOTDIR", + () => Effect.succeed(false), + ), + ); + if (!exists) return; if (deleted && !settings.worktreeOnDelete) return keep("no rules apply"); if (members.length > 1 && worktreeOwner(members) === undefined) return keep(`shared by ${members.length} threads`); if (project === undefined) return keep("project is unavailable"); - if ( - thread.branch === null || - !group.every((member) => storageCleanupThreadIdle(member, now, serverSettings)) - ) + if (!group.every((member) => storageCleanupThreadIdle(member, now, serverSettings))) return keep(waitForStop("thread is running or has pending work")); + if (thread.branch === null && !scratch) return keep("thread has no branch"); if (group.some((member) => member.branch !== thread.branch)) return keep("a subagent thread's branch differs from this worktree's branch"); - if (hasTerminal(worktreePath)) return keep(waitForStop("open terminal")); + if (yield* hasTerminal(worktreePaths)) return keep(waitForStop("open terminal")); if ( [...group, ...settlementChain.slice(1)].some( (member) => @@ -963,6 +1255,9 @@ const make = Effect.gen(function* () { settledFor !== null && settings.worktreeSettledAfterDays !== null && settledFor >= settings.worktreeSettledAfterDays * DAY_MS; + // A worktree is unchanged before its first commit, so only finished threads qualify. + const unchangedApplies = + settings.worktreeUnchanged && (settledThread !== undefined || thread.archivedAt !== null); let eligible = deleted || old || settled; let removalReason = deleted ? "thread was deleted" @@ -978,18 +1273,167 @@ const make = Effect.gen(function* () { : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days` : settings.worktreeOnMerge ? "not merged" - : settings.worktreeUnchanged + : unchangedApplies ? "has commits beyond the default branch" - : "no rules apply"; + : settings.worktreeUnchanged + ? "not settled" + : "no rules apply"; + // The merge and unchanged rules read Git, which a scratch folder does not have. + if (scratch && !eligible) + return keep( + settings.worktreeAfterDays !== null || settings.worktreeSettledAfterDays !== null + ? notDueReason + : "no rules apply", + ); // Only Git-based rules can make a not-yet-due worktree eligible, so skip Git otherwise. - if (!eligible && !settings.worktreeUnchanged && !settings.worktreeOnMerge) - return keep(notDueReason); + if (!eligible && !unchangedApplies && !settings.worktreeOnMerge) return keep(notDueReason); + // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds. + const blockedSinceCheck = Effect.fnUntraced(function* () { + const latestProjects = yield* projectStore.listShells(); + if (yield* containsProjectRoot(worktreePaths, [project, ...latestProjects])) + return "contains a project checkout"; + const bindings = yield* projections.getThreadWorktreePaths({ includeArchived: true }); + const bindingKeys = yield* Effect.forEach(bindings, (binding) => + canonical(binding.worktreePath), + ); + const latest = bindings.filter((_binding, index) => bindingKeys[index] === worktreeKey); + if (yield* hasTerminal(worktreePaths)) return waitForStop("open terminal"); + if (deleted) { + if ( + !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId) + .worktreeOnDelete + ) + return "thread or cleanup settings changed since check"; + // Durable deletion cleanup must succeed or be explicitly cancelled before removing its checkout. + const pendingCleanup = yield* sql<{ status: string }>` + SELECT status FROM orchestration_v2_effect_outbox + WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') + `.pipe(NodeSqliteClient.readOnly); + // Failed effects never retry, so only running work can finish and free the path. + if (pendingCleanup.some((row) => row.status !== "failed")) + return waitForStop("thread deletion is still pending"); + if (pendingCleanup.length > 0) return "thread deletion is still pending"; + } + const latestShells = yield* Effect.forEach(latest, (entry) => + projections.getThreadShell(entry.threadId), + ); + const latestGroup = latestShells.filter((shell) => shell !== null); + const latestKeys = yield* Effect.forEach(latestGroup, (shell) => + shell.worktreePath === null ? Effect.succeed(null) : canonical(shell.worktreePath), + ); + const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup); + if ( + latestGroup.length !== group.length || + latestOwner?.id !== thread.id || + latestOwner?.branch !== thread.branch || + latestGroup.some((shell, index) => { + const previous = group.find((member) => member.id === shell.id); + return ( + previous === undefined || + shell.branch !== thread.branch || + !Equal.equals(shell.settledAt, previous.settledAt) || + (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) || + !storageCleanupThreadIdle(shell, now, serverSettings) || + latestKeys[index] !== worktreeKey || + storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous) + ); + }) + ) + return waitForStop("thread activity or shared worktree changed since check"); + if (settlementChain.length > 1) { + const ancestors = yield* Effect.forEach(settlementChain.slice(1), (ancestor) => + projections.getThreadShell(ancestor.id), + ); + const latestSettlement = worktreeSettlementChain( + latestGroup.find((shell) => shell.id === thread.id)!, + new Map( + [...latestGroup, ...ancestors.filter((ancestor) => ancestor !== null)].map( + (ancestor) => [ancestor.id, ancestor], + ), + ), + now, + serverSettings, + ).at(-1); + if ( + latestSettlement?.id !== settledThread?.id || + !Equal.equals(latestSettlement?.settledAt, settledThread?.settledAt) || + !Equal.equals(latestSettlement?.updatedAt, settledThread?.updatedAt) + ) + return "parent settlement changed since check"; + } + // Sessions can outlive their run and can be shared across app threads. + const sessionRows = yield* sql<{ payload_json: string }>` + SELECT payload_json FROM orchestration_v2_projection_provider_sessions + WHERE status != 'stopped' + `.pipe(NodeSqliteClient.readOnly); + const sessions = yield* Effect.forEach(sessionRows, (row) => + decodeCleanupSession(row.payload_json), + ); + // Ready persisted sessions may have released their runtime; only live sessions protect the path. + for (const session of sessions) { + if ( + (yield* occupies(worktreePaths, session.cwd)) && + (yield* providerSessions.isLive(session.id)) + ) + return waitForStop("provider session is still open"); + } + return null; + }); + const settingsChangedSinceCheck = Effect.gen(function* () { + const currentSettings = yield* settingsService.getSettings; + const current = resolveWorktreeCleanup(currentSettings, thread.projectId); + return ( + currentSettings.autoResumeLimitedThreads !== serverSettings.autoResumeLimitedThreads || + currentSettings.snoozeLimitedThreads !== serverSettings.snoozeLimitedThreads || + Object.keys(settings).some( + (key) => + current[key as keyof typeof settings] !== settings[key as keyof typeof settings], + ) + ); + }); + if (scratch) { + const threadIds = group.map((member) => member.id); + const blocked = + (yield* scratchKeepReason(worktreePath, threadIds, settings)) ?? + (yield* blockedSinceCheck()); + if (blocked !== null) return keep(blocked); + const inspection = yield* measureWorktree(worktreePath, "plain-folder"); + if (inspection.reason !== null) return keep(inspection.reason); + return yield* withWorkspaceLease( + worktreePath, + Effect.gen(function* () { + // Walked again under the lease: a repository deleted with the folder is gone for good. + const finalInspection = yield* measureWorktree(worktreePath, "plain-folder"); + if (finalInspection.reason !== null) return keep(finalInspection.reason); + // The walk takes time, so the cheap checks run last, right before removal. + const blockedWhileMeasuring = + (yield* scratchKeepReason(worktreePath, threadIds, settings)) ?? + (yield* blockedSinceCheck()); + if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring); + if (yield* settingsChangedSinceCheck) return keep("settings changed since check"); + yield* fs.remove(worktreePath, { recursive: true }); + entries.push({ + ...entry, + outcome: "removed", + reason: sentence(removalReason), + bytes: inspection.bytes, + }); + // The stored path stays so the next turn recreates the folder, empty. + yield* Effect.logInfo("storage cleanup removed scratch folder", { + threadId: thread.id, + }); + }), + ); + } const pathReason = yield* worktreePathReason(worktreePath); if (pathReason !== null) return keep(pathReason); - if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) + if (yield* containsProjectRoot(worktreePaths, [project, ...snapshot.projects])) return keep("contains a project checkout"); - if (yield* branchChanged(worktreePath, thread.branch)) + if (yield* branchChanged(worktreePath, thread.branch)) { + // A deleted owner cannot follow, so its remaining subagents stay on its branch. + if (!deleted) yield* followBranch(worktreePath); return keep("repository or branch changed"); + } const changes = yield* localChangesReason(worktreePath, settings); if (changes !== null) return keep(changes); const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }); @@ -1007,8 +1451,12 @@ const make = Effect.gen(function* () { let branch: string | null | undefined; let defaultRef: string; if (remote === null) { - if (!settings.worktreeUnchanged) - return keep("no remote is configured for merged-worktree cleanup"); + if (!unchangedApplies) + return keep( + settings.worktreeUnchanged + ? notDueReason + : "no remote is configured for merged-worktree cleanup", + ); const projectHead = yield* git.execute({ operation: "StorageCleanup.resolveProjectBranch", cwd: repositoryCwd, @@ -1067,7 +1515,7 @@ const make = Effect.gen(function* () { allowNonZeroExit: true, }); const integrated = ancestor.exitCode === 0; - eligible = integrated && settings.worktreeUnchanged; + eligible = integrated && unchangedApplies; if (eligible) removalReason = remote === null @@ -1086,101 +1534,16 @@ const make = Effect.gen(function* () { }); if (eligible) removalReason = "pull request was merged"; } - if (!eligible && remote === null) return keep("has commits beyond the project branch"); + if (!eligible && remote === null) + return keep(integrated ? notDueReason : "has commits beyond the project branch"); } if (!eligible) return keep(notDueReason); - // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds. - const blockedSinceCheck = Effect.fnUntraced(function* () { - const latestProjects = yield* projectStore.listShells(); - if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects])) - return "contains a project checkout"; - const latest = (yield* projections.getThreadWorktreePaths({ - includeArchived: true, - })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath); - if (hasTerminal(worktreePath)) return waitForStop("open terminal"); - if (deleted) { - if ( - !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId) - .worktreeOnDelete - ) - return "thread or cleanup settings changed since check"; - // Durable deletion cleanup must succeed or be explicitly cancelled before removing its checkout. - const pendingCleanup = yield* sql<{ status: string }>` - SELECT status FROM orchestration_v2_effect_outbox - WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') - `.pipe(NodeSqliteClient.readOnly); - // Failed effects never retry, so only running work can finish and free the path. - if (pendingCleanup.some((row) => row.status !== "failed")) - return waitForStop("thread deletion is still pending"); - if (pendingCleanup.length > 0) return "thread deletion is still pending"; - } - const latestShells = yield* Effect.forEach(latest, (entry) => - projections.getThreadShell(entry.threadId), - ); - const latestGroup = latestShells.filter((shell) => shell !== null); - const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup); - if ( - latestGroup.length !== group.length || - latestOwner?.id !== thread.id || - latestOwner?.branch !== thread.branch || - latestGroup.some((shell) => { - const previous = group.find((member) => member.id === shell.id); - return ( - previous === undefined || - shell.branch !== thread.branch || - !Equal.equals(shell.settledAt, previous.settledAt) || - (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) || - !storageCleanupThreadIdle(shell, now, serverSettings) || - path.resolve(shell.worktreePath!) !== worktreePath || - storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous) - ); - }) - ) - return waitForStop("thread activity or shared worktree changed since check"); - if (settlementChain.length > 1) { - const ancestors = yield* Effect.forEach(settlementChain.slice(1), (ancestor) => - projections.getThreadShell(ancestor.id), - ); - const latestSettlement = worktreeSettlementChain( - latestGroup.find((shell) => shell.id === thread.id)!, - new Map( - [...latestGroup, ...ancestors.filter((ancestor) => ancestor !== null)].map( - (ancestor) => [ancestor.id, ancestor], - ), - ), - now, - serverSettings, - ).at(-1); - if ( - latestSettlement?.id !== settledThread?.id || - !Equal.equals(latestSettlement?.settledAt, settledThread?.settledAt) || - !Equal.equals(latestSettlement?.updatedAt, settledThread?.updatedAt) - ) - return "parent settlement changed since check"; - } - // Sessions can outlive their run and can be shared across app threads. - const sessionRows = yield* sql<{ payload_json: string }>` - SELECT payload_json FROM orchestration_v2_projection_provider_sessions - WHERE status != 'stopped' - `.pipe(NodeSqliteClient.readOnly); - const sessions = yield* Effect.forEach(sessionRows, (row) => - decodeCleanupSession(row.payload_json), - ); - // Ready persisted sessions may have released their runtime; only live sessions protect the path. - for (const session of sessions) { - const cwd = path.resolve(session.cwd); - if ( - (pathKey(cwd) === pathKey(worktreePath) || inside(worktreePath, cwd)) && - (yield* providerSessions.isLive(session.id)) - ) - return waitForStop("provider session is still open"); - } - return null; - }); const blocked = yield* blockedSinceCheck(); if (blocked !== null) return keep(blocked); - // Size is an estimate; provider startup must not wait for directory traversal. - const bytes = yield* measureWorktree(worktreePath); + // Inspect before the lease; provider startup must not wait for directory traversal. + const inspection = yield* measureWorktree(worktreePath, true); + if (inspection.reason !== null) return keep(inspection.reason); + const bytes = inspection.bytes; yield* withWorkspaceLease( worktreePath, Effect.gen(function* () { @@ -1197,35 +1560,25 @@ const make = Effect.gen(function* () { return keep("commit changed since check"); const finalChanges = yield* localChangesReason(worktreePath, settings); if (finalChanges !== null) return keep(finalChanges); - const currentSettings = yield* settingsService.getSettings; - const current = resolveWorktreeCleanup(currentSettings, thread.projectId); - if ( - currentSettings.autoResumeLimitedThreads !== - serverSettings.autoResumeLimitedThreads || - currentSettings.snoozeLimitedThreads !== serverSettings.snoozeLimitedThreads || - Object.keys(settings).some( - (key) => - current[key as keyof typeof settings] !== settings[key as keyof typeof settings], - ) - ) - return keep("settings changed since check"); - // Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check. - if (settings.worktreeKeepWhen === "tracked-changes") - yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); + if (yield* settingsChangedSinceCheck) return keep("settings changed since check"); const submodules = yield* submoduleRemoval(worktreePath, settings); if (submodules.reason !== null) return keep(submodules.reason); if (submodules.force) { const changes = yield* localChangesReason(worktreePath, settings); if (changes !== null) return keep(changes); } + const repository = yield* worktreeRepository(worktreePath); + // Forced removal already discards local files; do not widen its final-check window. + if (settings.worktreeKeepWhen === "tracked-changes" && !submodules.force) + yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); yield* removeLinkedWorktree({ operation: "StorageCleanup.cleanupGit", - cwd: project.workspaceRoot, + cwd: repository, worktreePath, // Git requires force for submodules; recursive checks above cannot make removal atomic. force: submodules.force, execute: git.execute, - run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"), + run: (args) => cleanupGit(repository, [...args], "git worktree remove"), }); entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes }); yield* gitManager.invalidateStatus(project.workspaceRoot); @@ -1254,6 +1607,7 @@ const make = Effect.gen(function* () { roots, yield* projectStore.list({ includeDeleted: true }), entries, + scratchRoot, ); return { waiting, kept }; }); @@ -1297,6 +1651,115 @@ const make = Effect.gen(function* () { }); const reportRef = yield* SubscriptionRef.make(null); + const cleanCheckpointRefs = Effect.fn("StorageCleanup.cleanCheckpointRefs")(function* () { + // Forks display their source history even after its thread is deleted. Keep + // that ancestry, including deleted intermediate forks and archived children. + const rows = yield* sql<{ + threadId: string; + worktreePath: string | null; + workspaceRoot: string | null; + scopeId: string | null; + cwd: string | null; + }>` + WITH RECURSIVE retained_checkpoint_threads(thread_id) AS ( + SELECT thread_id FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL + UNION + SELECT json_extract(t.payload_json, '$.forkedFrom.threadId') + FROM orchestration_v2_projection_threads t + JOIN retained_checkpoint_threads retained ON retained.thread_id = t.thread_id + WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run' + ) + SELECT t.thread_id AS "threadId", + json_extract(t.payload_json, '$.worktreePath') AS "worktreePath", + p.workspace_root AS "workspaceRoot", s.scope_id AS "scopeId", + json_extract(s.payload_json, '$.cwd') AS cwd + FROM orchestration_v2_projection_threads t + LEFT JOIN projection_projects p ON p.project_id = t.project_id + LEFT JOIN orchestration_v2_projection_checkpoint_scopes s ON s.thread_id = t.thread_id + WHERE t.deleted_at IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM retained_checkpoint_threads WHERE thread_id = t.thread_id) + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_effect_outbox e + WHERE e.thread_id = t.thread_id AND e.status IN ('pending', 'running') + ) + `.pipe(NodeSqliteClient.readOnly); + const targets = new Map>(); + for (const row of rows) { + // Derive ownership from tombstones, never from absence in this database: + // another T3 home can own refs in the same Git repository. + const prefixes = [`refs/t3/checkpoints/${Base64Url.encode(row.threadId)}/turn/`]; + if (row.scopeId !== null) { + prefixes.push( + (yield* checkpointRefForScopeOrdinal({ + scopeId: CheckpointScopeId.make(row.scopeId), + ordinalWithinScope: 0, + })).slice(0, -1), + ); + } + // A worktree may already be gone; its refs live in the shared repository. + for (const cwd of [row.cwd, row.worktreePath, row.workspaceRoot]) { + if (cwd === null) continue; + const key = path.resolve(cwd); + const owned = targets.get(key) ?? new Set(); + for (const prefix of prefixes) owned.add(prefix); + targets.set(key, owned); + } + } + const repositories = new Map }>(); + for (const [cwd, prefixes] of targets) { + yield* Effect.gen(function* () { + if (!(yield* fs.exists(cwd))) return; + const result = yield* git.execute({ + operation: "StorageCleanup.checkpointRepository", + cwd, + args: ["rev-parse", "--path-format=absolute", "--git-common-dir"], + allowNonZeroExit: true, + }); + if (result.exitCode !== 0) return; + const commonDir = yield* fs.realPath(result.stdout.trim()); + const repository = repositories.get(commonDir) ?? { cwd, prefixes: new Set() }; + for (const prefix of prefixes) repository.prefixes.add(prefix); + repositories.set(commonDir, repository); + }).pipe( + Effect.catch((cause) => + Effect.logWarning("checkpoint repository inspection failed", { cause }), + ), + ); + } + for (const { cwd, prefixes } of repositories.values()) { + yield* Effect.gen(function* () { + const result = yield* git.execute({ + operation: "StorageCleanup.listCheckpointRefs", + cwd, + args: [ + "for-each-ref", + "--format=%(refname)", + "refs/t3/checkpoints/", + "refs/t3/orchestration-v2/checkpoints/", + ], + maxOutputBytes: 16 * 1024 * 1024, + }); + const refs = result.stdout.split("\n").filter((ref) => { + const ordinalStart = ref.lastIndexOf("/") + 1; + return ( + prefixes.has(ref.slice(0, ordinalStart)) && + /^(0|[1-9]\d*)$/.test(ref.slice(ordinalStart)) + ); + }); + if (refs.length === 0) return; + yield* git.execute({ + operation: "StorageCleanup.deleteCheckpointRefs", + cwd, + // Remove a symbolic checkpoint itself, never its branch/tag target. + args: ["update-ref", "--no-deref", "-z", "--stdin"], + stdin: refs.map((ref) => `delete ${ref}\0\0`).join(""), + }); + yield* Effect.logInfo("storage cleanup removed checkpoint refs", { refCount: refs.length }); + }).pipe( + Effect.catch((cause) => Effect.logWarning("checkpoint ref cleanup failed", { cause })), + ); + } + }); // Only deleted threads' worktrees wait on session stops: any stop while one waits, or a stop inside one kept for another reason. // A deletion stays pending until a sweep that started after it finishes. let deletedWorktreeWaits = true; @@ -1311,6 +1774,9 @@ const make = Effect.gen(function* () { const serverSettings = yield* settingsService.getSettings; const settings = serverSettings.storageCleanup; const entries: StorageCleanupReportEntry[] = []; + yield* cleanCheckpointRefs().pipe( + Effect.catch((cause) => Effect.logWarning("checkpoint ref cleanup failed", { cause })), + ); const deletedWorktrees = yield* cleanWorktrees(serverSettings, now, entries).pipe( Effect.catch((error) => Effect.gen(function* () { @@ -1489,6 +1955,7 @@ const make = Effect.gen(function* () { ) return Effect.void; } + if (event.type === "thread.deleted") return requestSweep; if (!anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)) return Effect.void; return event.type === "provider-session.updated" && event.payload.status === "error" ? providerSessions diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index ed4645b18b..8499197acb 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1,14 +1,20 @@ +import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { DEFAULT_TERMINAL_ID, + ProjectId, + ThreadId, + TerminalCwdNotFoundError, type TerminalAttachStreamEvent, type TerminalEvent, type TerminalOpenInput, ProviderDriverKind, ProviderInstanceId, - ProjectId, + retainedTerminalHistory, + terminalSequenceEnd, + terminalSequenceStateAfter, TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -26,6 +32,7 @@ import * as PlatformError from "effect/PlatformError"; import * as Path from "effect/Path"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as Ref from "effect/Ref"; +import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -33,14 +40,19 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import * as TestClock from "effect/testing/TestClock"; import { expect, vi } from "vite-plus/test"; +import * as ServerConfig from "../config.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as TerminalManager from "./Manager.ts"; +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import { makePrepareTerminalLaunch } from "../workspace/restoreMissingWorktree.ts"; +import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { terminalOutputStream } from "./OutputProtocol.ts"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; +import packageJson from "../../package.json" with { type: "json" }; vi.mock("effect/SynchronizedRef", async (importOriginal) => { const original = await importOriginal(); @@ -49,10 +61,16 @@ vi.mock("effect/SynchronizedRef", async (importOriginal) => { // The server omits DOM types, which include TypeScript's WebAssembly declarations. +const POWERSHELL_ARGS = [ + "-NoLogo", + "-NoExit", + "-Command", + "[Console]::OutputEncoding = $OutputEncoding = [System.Text.UTF8Encoding]::new()", +]; const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); class FakePtyProcess implements PtyAdapter.PtyProcess { - readonly writes: string[] = []; + readonly writes: Array = []; readonly resizeCalls: Array<{ cols: number; rows: number }> = []; readonly killSignals: Array = []; readonly pid: number; @@ -68,7 +86,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess { this.pid = pid; } - write(data: string): void { + write(data: string | Buffer): void { if (this.writeFailure !== undefined) { throw this.writeFailure; } @@ -230,6 +248,7 @@ interface CreateManagerOptions { ReadonlyArray<{ readonly pid: number; readonly ppid: number; readonly name: string }>, never >; + foregroundProcessGroup?: (terminalPid: number) => Effect.Effect; subprocessPollIntervalMs?: number; processKillGraceMs?: number; registerTerminalProcesses?: Parameters< @@ -281,6 +300,8 @@ const createManager = ( ? { subprocessInspector: options.subprocessInspector } : {}), ...(options.processTable !== undefined ? { processTable: options.processTable } : {}), + // Fixture pids are not real processes; default to a shell idle at its prompt. + foregroundProcessGroup: options.foregroundProcessGroup ?? ((pid) => Effect.succeed(pid)), ...(options.subprocessPollIntervalMs !== undefined ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } : {}), @@ -327,7 +348,6 @@ function retainedHistory(text: string, maxLines: number, maxBytes = Infinity): s if (terminated) lines.pop(); const retained = lines.slice(Math.max(0, lines.length - maxLines)).join("\n"); const capped = terminated ? `${retained}\n` : retained; - if (Buffer.byteLength(capped) <= maxBytes) return capped; const points = Array.from(capped); let start = points.length; let bytes = 0; @@ -337,7 +357,11 @@ function retainedHistory(text: string, maxLines: number, maxBytes = Infinity): s bytes += next; start -= 1; } - return points.slice(start).join(""); + const kept = points.slice(start).join(""); + if (maxLines <= 0 || maxBytes <= 0) return kept; + // A cut inside a control sequence drops the rest of that sequence too. + const state = terminalSequenceStateAfter(0, text, 0, text.length - kept.length); + return kept.slice(terminalSequenceEnd(state, kept)); } it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequences, and clear", () => { @@ -355,6 +379,10 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen "\u001b[31m", "\u001b[0m", "\u001b]8;;url\u0007", + "\u001b]0;", + "\u001bP", + "\u0007", + "\u001b\\", "\ud83d", "\ude80", ]; @@ -365,7 +393,8 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen for (const maxBytes of [0, 3, 8, 64, Infinity]) { for (const maxLines of [0, 1, 3, 5, 5_000]) { - let expected = retainedHistory("before\ninitial\n", maxLines, maxBytes); + let full = "before\ninitial\n"; + let expected = retainedHistory(full, maxLines, maxBytes); const history = new TerminalManager.BoundedTerminalHistory( maxLines, "before\ninitial\n", @@ -376,18 +405,33 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen for (let step = 0; step < 300; step += 1) { if (step % 73 === 0) { history.clear(); - expected = ""; - expect(history.value()).toBe(expected); + full = ""; + expect(history.value()).toBe(""); } const chunk = nextFragment() + nextFragment(); history.append(chunk); - expected = retainedHistory(expected + chunk, maxLines, maxBytes); + full += chunk; + expected = retainedHistory(full, maxLines, maxBytes); expect(history.value()).toBe(expected); } } } }); +it("does not retain the tail of a control sequence whose introducer was trimmed", () => { + for (const [text, maxBytes, retained] of [ + ["prefix\u001b[31mOK", 6, "OK"], + ["prefix\u001b]0;HIDDEN\u0007OK", 10, "OK"], + ["prefix\u001b]0;🙂HIDDEN\u0007OK", 9, "OK"], + // libghostty leaves every string but OSC at the emoji's second byte, so HELLO was visible. + ["prefix\u001bP🙂HELLO\u001b\\OK", 9, "HELLO\u001b\\OK"], + ] as const) { + expect(new TerminalManager.BoundedTerminalHistory(5_000, text, maxBytes).value()).toBe( + retained, + ); + } +}); + it("bounds long partial lines and joins surrogate pairs across chunk boundaries", () => { const maxBytes = 65_539; let expected = ""; @@ -406,6 +450,41 @@ it("bounds long partial lines and joins surrogate pairs across chunk boundaries" } }); +it("restores bounded history across append compaction, clears and split Unicode", () => { + const maxBytes = 64; + const history = new TerminalManager.BoundedTerminalHistory(3, "", maxBytes); + let cursor: ReturnType["cursor"] | undefined; + let persisted = ""; + let compactions = 0; + const flush = () => { + const update = history.persistenceUpdate(cursor); + if (!update.append) compactions += 1; + const encoded = Buffer.from(update.data).toString(); + persisted = update.append ? persisted + encoded : encoded; + cursor = update.cursor; + expect(Buffer.byteLength(persisted)).toBeLessThanOrEqual(maxBytes * 2); + expect(retainedHistory(persisted, 3, maxBytes)).toBe(Buffer.from(history.value()).toString()); + }; + for (let index = 0; index < 100; index += 1) { + history.append(`line ${index} 名\n`); + flush(); + } + expect(compactions).toBeGreaterThan(1); + expect(compactions).toBeLessThan(50); + history.clear(); + flush(); + expect(persisted).toBe(""); + history.append("\ud83d"); + flush(); + history.append("\ude80"); + flush(); + expect(persisted).toBe("🚀"); + // More output than the retained window between flushes must replace the file. + history.append("z".repeat(maxBytes * 3)); + flush(); + expect(persisted).toBe("z".repeat(maxBytes)); +}); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -414,6 +493,91 @@ it.layer( ), { excludeTestServices: true }, )("TerminalManager", (it) => { + it.effect.each([ + { method: "open", location: "managed" }, + { method: "attach", location: "managed" }, + { method: "open", location: "subdirectory" }, + { method: "open", location: "unmanaged" }, + { method: "open", location: "no-worktree" }, + ] as const)( + "recovers $method with a $location cwd without a cleanup gap", + ({ method, location }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { manager, ptyAdapter, baseDir } = yield* createManager(); + const worktreesDir = path.join(baseDir, "worktrees"); + const worktreePath = + location === "unmanaged" + ? path.join(baseDir, "missing") + : path.join(worktreesDir, "project", "feature"); + const cwd = location === "subdirectory" ? path.join(worktreePath, "src") : worktreePath; + const cleanupQueued = yield* Deferred.make>(); + let creations = 0; + const prepareLaunch = yield* makePrepareTerminalLaunch(() => + Effect.succeed({ + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-1"), + worktreePath: location === "no-worktree" ? null : worktreePath, + branch: "feature", + }), + ).pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(ServerConfig.ServerConfig)({ + worktreesDir, + } as ServerConfig.ServerConfig["Service"]), + ServerSettings.layerTest(), + Layer.mock(ProjectService.ProjectService)({ + getById: () => Effect.succeedSome({ workspaceRoot: baseDir } as never), + }), + Layer.mock(GitWorkflowService.GitWorkflowService)({ + pruneWorktrees: () => Effect.void, + listLocalBranchNames: () => Effect.succeed(["feature"]), + createWorktree: () => + Effect.gen(function* () { + creations++; + yield* fs.makeDirectory(cwd, { recursive: true }).pipe(Effect.orDie); + const cleanup = yield* withWorkspaceLease( + worktreePath, + Effect.sync(() => { + assert.equal(ptyAdapter.spawnInputs.length, 1); + }), + ).pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(cleanupQueued, cleanup); + return {} as never; + }), + }), + ), + ), + ); + const input = openInput({ + cwd, + worktreePath: location === "subdirectory" ? null : worktreePath, + }); + const launch = prepareLaunch(input).pipe( + Effect.flatMap(({ input, recover }) => + (method === "attach" + ? manager.attachStream(input, () => Effect.void).pipe(Effect.asVoid) + : manager.open(input).pipe(Effect.asVoid) + ).pipe(Effect.provideService(TerminalManager.TerminalCwdRecovery, recover)), + ), + ); + if (location === "unmanaged" || location === "no-worktree") { + const error = yield* launch.pipe(Effect.flip); + assert.deepEqual(error, new TerminalCwdNotFoundError({ cwd })); + assert.equal(creations, 0); + assert.equal(ptyAdapter.spawnInputs.length, 0); + return; + } + yield* launch; + yield* Fiber.join(yield* Deferred.await(cleanupQueued)); + assert.equal(creations, 1); + assert.equal(ptyAdapter.spawnInputs.length, 1); + assert.isTrue(yield* fs.exists(cwd)); + }), + ); + it.effect("spawns lazily and reuses running terminal per thread", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); @@ -583,6 +747,39 @@ it.layer( }), ); + // Every attached renderer answers the same query; a second DECRQM answer breaks Vim's input. + it.effect("lets one attached viewer answer terminal queries on a shared PTY", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const attach = (terminalId: string, viewerId: string) => + manager.attachStream(openInput({ terminalId }), () => Effect.void, undefined, viewerId); + const stopFirst = yield* attach(DEFAULT_TERMINAL_ID, "first"); + const stopSecond = yield* attach(DEFAULT_TERMINAL_ID, "second"); + const stopOther = yield* attach("other", "second"); + yield* Effect.addFinalizer(() => Effect.sync(() => (stopSecond(), stopOther()))); + const [shared, other] = ptyAdapter.processes; + const modeReply = "\x1b[?12;2$y"; + const write = (terminalId: string, viewerId: string, data: string, reply?: boolean) => + manager.write( + { threadId: "thread-1", terminalId, data, ...(reply ? { reply } : {}) }, + viewerId, + ); + + yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true); + yield* write(DEFAULT_TERMINAL_ID, "second", modeReply, true); + yield* write(DEFAULT_TERMINAL_ID, "second", "iHELLO"); + yield* write("other", "second", modeReply, true); + expect(shared!.writes).toEqual([modeReply, "iHELLO"]); + expect(other!.writes).toEqual([modeReply]); + + stopFirst(); + yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true); + yield* write(DEFAULT_TERMINAL_ID, "second", modeReply, true); + yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true); + expect(shared!.writes).toEqual([modeReply, "iHELLO", modeReply]); + }), + ); + it.effect("resumed attaches after close never respawn until the terminal is reopened", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); @@ -733,9 +930,15 @@ it.layer( yield* manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); yield* manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); + yield* manager.write({ + threadId: "thread-1", + terminalId: "term-2", + data: "\x1b[M \x80(", + binary: true, + }); expect(first.writes).toEqual(["pwd\n"]); - expect(second.writes).toEqual(["ls\n"]); + expect(second.writes).toEqual(["ls\n", Buffer.from([0x1b, 0x5b, 0x4d, 0x20, 0x80, 0x28])]); expect(ptyAdapter.spawnInputs).toHaveLength(2); }), ); @@ -788,6 +991,51 @@ it.layer( }), ); + it.effect("keeps a terminal whose shell was replaced by exec open on settlement", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/bin/bash", + processTable: Effect.succeed([{ pid: 9000, ppid: 1, name: "node" }]), + }).pipe(Effect.provide(layerWithHostPlatform("linux"))); + yield* manager.open(openInput()); + + yield* manager.closeOnSettle({ threadId: "thread-1" }); + + expect(ptyAdapter.processes[0]?.killed).toBe(false); + }), + ); + + it.effect.each([ + { label: "idle prompt", platform: "linux", foregroundProcessGroup: 9000, killed: true }, + { label: "foreground job", platform: "linux", foregroundProcessGroup: 100, killed: false }, + { + label: "unknown foreground group", + platform: "linux", + foregroundProcessGroup: null, + killed: false, + }, + { label: "idle prompt", platform: "darwin", foregroundProcessGroup: 9000, killed: true }, + { label: "foreground job", platform: "darwin", foregroundProcessGroup: 100, killed: false }, + ] as const)( + "settles a shell with a childless shell-named child by its foreground group: $label ($platform)", + ({ platform, foregroundProcessGroup, killed }) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/bin/bash", + processTable: Effect.succeed([ + { pid: 9000, ppid: 1, name: "bash" }, + { pid: 100, ppid: 9000, name: "bash" }, + ]), + foregroundProcessGroup: () => Effect.succeed(foregroundProcessGroup), + }).pipe(Effect.provide(layerWithHostPlatform(platform))); + yield* manager.open(openInput()); + + yield* manager.closeOnSettle({ threadId: "thread-1" }); + + expect(ptyAdapter.processes[0]?.killed).toBe(killed); + }), + ); + it.effect("labels a running command by its whole process name, spaces included", () => Effect.gen(function* () { const { manager } = yield* createManager(5, { @@ -1042,6 +1290,168 @@ it.layer( }), ); + it.effect("clears a terminal that keeps printing while its history is saved", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + let printWhileSaving = Effect.void; + const printing = FileSystem.FileSystem.of({ + ...fs, + writeFileString: (filePath, data, options) => + printWhileSaving.pipe(Effect.andThen(fs.writeFileString(filePath, data, options))), + }); + const { manager, ptyAdapter, getEvents } = yield* createManager().pipe( + Effect.provideService(FileSystem.FileSystem, printing), + ); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + // Each save sees fresh output, so the history worker never goes idle. + printWhileSaving = Effect.gen(function* () { + const printed = yield* Deferred.make(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" ? Deferred.succeed(printed, undefined) : Effect.void, + ); + process.emitData("tick\n"); + yield* Deferred.await(printed); + unsubscribe(); + }); + + yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }); + + expect((yield* getEvents).map((event) => event.type)).toContain("cleared"); + }), + ); + + it.effect("restores a log tail that starts inside a control sequence without its remainder", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + for (const [persisted, restored] of [ + ["\u001b]0;x\u0007ABCD", "ABCD"], + ["名\u001b]0;名\u0007ABCD", "ABCD"], + ["\u001b]0;x\u0007\u001b[31mABCD", "ABCD"], + ] as const) { + const { manager, logsDir } = yield* createManager(5, { historyByteLimit: 8 }); + const path = yield* historyLogPath(logsDir); + yield* fs.makeDirectory(logsDir, { recursive: true }); + yield* fs.writeFileString(path, persisted); + expect((yield* manager.open(openInput())).history).toBe(restored); + expect(yield* fs.readFileString(path)).toBe(restored); + } + }), + ); + + it.effect("persists small terminal updates without rewriting the retained history", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const writes = yield* Queue.unbounded(); + const maxBytes = 64 * 1024; + const { manager, ptyAdapter, logsDir } = yield* createManager(5_000, { + historyByteLimit: maxBytes, + }).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + writeFileString: (path, data, options) => + fs + .writeFileString(path, data, options) + .pipe( + Effect.tap(() => + data.length > 0 ? Queue.offer(writes, Buffer.byteLength(data)) : Effect.void, + ), + ), + }), + ); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + process.emitData("a".repeat(maxBytes)); + let written = yield* Queue.take(writes); + for (let index = 0; index < 16; index += 1) { + process.emitData("b".repeat(1024)); + written += yield* Queue.take(writes); + } + expect(written).toBeLessThan(maxBytes * 2); + const expected = "a".repeat(maxBytes - 16 * 1024) + "b".repeat(16 * 1024); + const persisted = yield* fs.readFileString(yield* historyLogPath(logsDir)); + expect(Buffer.byteLength(persisted)).toBe(maxBytes + 16 * 1024); + for (const failure of [undefined, "write", "rename"] as const) { + let failed = false; + const fail = () => { + failed = true; + return Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: failure === "write" ? "writeFileString" : "rename", + cause: { code: "ENOSPC" }, + }), + ); + }; + const recovered = yield* createManager(5_000, { historyByteLimit: maxBytes }).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + writeFileString: (file, data, options) => + failure === "write" && !failed && data === expected + ? fs.writeFileString(file, "partial", options).pipe(Effect.andThen(fail)) + : fs.writeFileString(file, data, options), + rename: (from, to) => (failure === "rename" && !failed ? fail() : fs.rename(from, to)), + }), + ); + const recoveredPath = yield* historyLogPath(recovered.logsDir); + yield* fs.makeDirectory(recovered.logsDir, { recursive: true }); + yield* fs.writeFileString(recoveredPath, persisted); + const snapshot = yield* recovered.manager.open(openInput()); + expect(snapshot.status).toBe("running"); + expect(snapshot.history).toBe(expected); + expect(failed).toBe(failure !== undefined); + expect(yield* fs.readFileString(recoveredPath)).toBe( + failure === undefined ? expected : persisted, + ); + expect(yield* fs.readDirectory(recovered.logsDir)).toHaveLength(1); + } + yield* manager.close({ threadId: "thread-1" }); + expect((yield* manager.open(openInput())).history).toBe(expected); + expect(yield* fs.readFileString(yield* historyLogPath(logsDir))).toBe(expected); + }), + ); + + it.effect("rewrites history after an append fails partway through", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const writes = yield* Queue.unbounded(); + let failAppend = false; + const { manager, ptyAdapter, logsDir } = yield* createManager().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + writeFileString: (path, data, options) => { + if (options?.flag === "a" && failAppend) { + failAppend = false; + return fs.writeFileString(path, data.slice(0, 1), options).pipe( + // The file cannot also be a parent directory: fail after the partial append. + Effect.andThen(fs.writeFileString(`${path}/missing`, data)), + Effect.ensuring(Queue.offer(writes, undefined)), + ); + } + return fs + .writeFileString(path, data, options) + .pipe( + Effect.tap(() => (data.length > 0 ? Queue.offer(writes, undefined) : Effect.void)), + ); + }, + }), + ); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + process.emitData("start:"); + yield* Queue.take(writes); + failAppend = true; + process.emitData("middle"); + yield* Queue.take(writes); + expect(failAppend).toBe(false); + process.emitData(":end"); + yield* Queue.take(writes); + expect(yield* fs.readFileString(yield* historyLogPath(logsDir))).toBe("start:middle:end"); + yield* manager.close({ threadId: "thread-1" }); + }), + ); + it.effect("releases delivered output while the process queue stays busy", () => Effect.gen(function* () { // Observe retained payloads, since delivery and bounded history alone cannot detect a leak. @@ -1156,8 +1566,11 @@ it.layer( process.emitData("prompt "); process.emitData("\u001b[?2026$p\u001b[?2026;2$y\u001b[>q\u001b[?u\u001b[?31u"); + process.emitData("\u001b[=c\u001b[=0c\u001bZ"); process.emitData("\u001bP$q m\u001b\\\u001bP1$r0m\u001b\\"); process.emitData("\u001bP+q544e\u001b\\\u001bP1+r544e=1b\u001b\\"); + // BEL is DCS payload, not a terminator: only ST ends the string. + process.emitData("\u001bP$qm\u0007hidden\u001b\\\u001bP+q544e\u0007hidden\u001b\\"); process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u'); process.emitData("\u001b]0;x\u001b\u001b[?2026$p"); process.emitData("done\n"); @@ -1173,6 +1586,50 @@ it.layer( }), ); + // Ghostty executes 0x00-0x0F inside a CSI and ignores DEL and 0x10-0x1F; none change the query. + it.effect.each([ + { name: "NUL in DA", data: "A\u001b[0\u0000cB", history: "AB" }, + { name: "DEL in DA", data: "A\u001b[0\u007fcB", history: "AB" }, + { name: "NUL in DECRQM", data: "A\u001b[?2026\u0000$pB", history: "AB" }, + { name: "CR in DSR", data: "AB\u001b[5\rnC", history: "AB\rC" }, + { name: "DLE in DSR", data: "AB\u001b[5\u0010nC", history: "ABC" }, + // Ghostty reads non-ASCII there as UTF-8 bytes: it drops é and runs 0x80-0x9F as C1 controls. + { name: "é in DA", data: "A\u001b[0écB", history: "AB" }, + { name: "DECID byte in a CSI", data: "A\u001b[嚠B", history: "A\ufffdB" }, + { + name: "C1 DCS then C1 CSI in DSR", + data: "A\u001b[\u0090\u009b6nB", + history: "A\u001bP\u009cB", + }, + { name: "ESC in DSR", data: "A\u001b[5\u001b[6nB", history: "AB" }, + ])( + "strips a query with an embedded control but keeps what the terminal ran ($name)", + ({ data, history }) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + ptyAdapter.processes[0]!.emitData(data); + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + const restored = reopened.history.replaceAll("\u0000", ""); + expect(restored.split("\u001b[?1049h")[0]).toBe(history); + }), + ); + + // Ghostty aborts a CSI at a non-ASCII code point and prints it and what follows. + it.effect("keeps a CSI interrupted by non-ASCII text in history", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + ptyAdapter.processes[0]!.emitData("A\u001b[界nB"); + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + expect(reopened.history.split("\u001b[?1049h")[0]).toBe("A\u001b[界nB"); + }), + ); + it.effect.each([ { name: "OSC", sequence: "\u001b]0;unfinished" }, { name: "DCS", sequence: "\u001bPunfinished" }, @@ -1224,6 +1681,21 @@ it.layer( }), ); + it.effect("keeps a decoded U+009C inside a stripped OSC query out of history", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + // libghostty receives UTF-8 (c2 9c), which is OSC payload; only ESC \ ends this string. + process.emitData("A\u001b]11;?\u009cHIDDEN\u001b\\B\n"); + // A DCS string does end at U+009C there, so the text after it stays visible. + process.emitData("C\u001bP$qm\u009cSHOWN\u001b\\D\n"); + yield* manager.close({ threadId: "thread-1" }); + + expect((yield* manager.open(openInput())).history).toMatch(/^AB\nCSHOWN\u001b\\D\n/); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); @@ -1328,6 +1800,28 @@ it.layer( }), ); + // Case-insensitive filesystems resolve "Terminal_YQ.log" to thread "a"'s "terminal_YQ.log", + // so the mixed-case file stands in for that alias on case-sensitive hosts. + it.effect.each(["terminal_", "Terminal_"])( + "never resolves a %s legacy history name to another thread's history file", + (prefix) => + Effect.gen(function* () { + const { manager, logsDir } = yield* createManager(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const threadId = `${prefix}${Base64Url.encode("a")}`; + const otherThreadPath = path.join(logsDir, `${threadId}.log`); + yield* fs.makeDirectory(logsDir, { recursive: true }); + yield* fs.writeFileString(otherThreadPath, "thread a\n"); + + expect((yield* manager.open(openInput({ threadId }))).history).toBe(""); + yield* manager.close({ threadId, terminalId: DEFAULT_TERMINAL_ID, deleteHistory: true }); + yield* manager.close({ threadId, deleteHistory: true }); + + expect(yield* fs.readFileString(otherThreadPath)).toBe("thread a\n"); + }), + ); + it.effect("keeps reading and deleting history at an encoded path that already fit", () => Effect.gen(function* () { const threadId = "x".repeat(48); @@ -1539,6 +2033,41 @@ it.layer( }), ); + it.effect("keeps a startup failure in the snapshot every later attachment receives", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + ptyAdapter.spawnFailures.push(new Error("forkpty(3) failed.")); + const startupFailure = { + type: "snapshot", + snapshot: { + status: "error", + error: expect.stringContaining("Failed to spawn PTY process"), + }, + }; + const record = (events: TerminalAttachStreamEvent[]) => (event: TerminalAttachStreamEvent) => + Effect.sync(() => events.push(event)); + + const creating: TerminalAttachStreamEvent[] = []; + (yield* manager.attachStream(openInput(), record(creating)))(); + const resumed: TerminalAttachStreamEvent[] = []; + (yield* manager.attachStream({ ...openInput(), resume: true }, record(resumed)))(); + const observed: TerminalAttachStreamEvent[] = []; + (yield* manager.observeStream( + { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }, + record(observed), + ))(); + expect([creating, resumed, observed]).toMatchObject([ + [startupFailure], + [startupFailure], + [startupFailure], + ]); + + const restarted = yield* manager.open(openInput()); + expect(restarted.status).toBe("running"); + expect(restarted).not.toHaveProperty("error"); + }), + ); + it.effect("retries with fallback shells when preferred shell spawn fails", () => Effect.gen(function* () { const platform = yield* HostProcess.Platform; @@ -1576,6 +2105,59 @@ it.layer( }), ); + it.effect("starts an existing $SHELL whose path contains spaces before a dash", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { join } = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-shell-path-" }); + const bin = join(root, "Jane -Doe Smith", ".local", "bin"); + yield* fs.makeDirectory(bin, { recursive: true }); + yield* fs.writeFileString(join(bin, "fish"), ""); + // Temp dirs are not POSIX-absolute on Windows, so stat maps a fixed POSIX prefix onto them. + const fixtureFs = FileSystem.FileSystem.of({ + ...fs, + stat: (filePath) => + fs.stat( + filePath.startsWith("/shell-fixture/") + ? join(root, filePath.slice("/shell-fixture/".length)) + : filePath, + ), + }); + const { manager, ptyAdapter } = yield* createManager(5, { + env: { SHELL: "/shell-fixture/Jane -Doe Smith/.local/bin/fish -l" }, + }).pipe( + Effect.provide(layerWithHostPlatform("darwin")), + Effect.provideService(FileSystem.FileSystem, fixtureFs), + ); + + yield* manager.open(openInput()); + + expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual([ + "/shell-fixture/Jane -Doe Smith/.local/bin/fish", + ]); + }), + ); + + it.effect("keeps missing or quoted $SHELL paths that contain spaces", () => + Effect.gen(function* () { + for (const [shell, expected] of [ + ["/Users/Jane Doe/.local/bin/fish", "/Users/Jane Doe/.local/bin/fish"], + ['"/opt/my -shell/fish" -l', "/opt/my -shell/fish"], + ]) { + const { manager, ptyAdapter } = yield* createManager(5, { + env: { SHELL: shell }, + }).pipe(Effect.provide(layerWithHostPlatform("darwin"))); + + yield* manager.open(openInput()); + + expect( + ptyAdapter.spawnInputs.map((input) => input.shell), + shell, + ).toEqual([expected]); + } + }), + ); + it.effect( "writes completion syntax for the fallback shell instead of the configured fish shell", () => @@ -1719,8 +2301,8 @@ it.layer( "pwsh.exe", "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", ]); - expect(ptyAdapter.spawnInputs[1]?.args).toEqual(["-NoLogo"]); - expect(ptyAdapter.spawnInputs[2]?.args).toEqual(["-NoLogo"]); + expect(ptyAdapter.spawnInputs[1]?.args).toEqual(POWERSHELL_ARGS); + expect(ptyAdapter.spawnInputs[2]?.args).toEqual(POWERSHELL_ARGS); }), ); @@ -1853,6 +2435,51 @@ it.layer( }), ); + it.effect.each([ + { + platform: "linux", + parentEnv: { TERM_PROGRAM: "Apple_Terminal", TERM_PROGRAM_VERSION: "455" }, + runtimeEnv: { TERM_PROGRAM: "", TERM_PROGRAM_VERSION: "custom-version" }, + }, + { + platform: "win32", + parentEnv: { term_program: "Apple_Terminal", Term_Program_Version: "455" }, + runtimeEnv: { Term_Program: "", term_program_version: "custom-version" }, + }, + ] as const)( + "identifies as T3 Code unless the terminal env overrides it on $platform", + ({ platform, parentEnv, runtimeEnv }) => + Effect.gen(function* () { + const originalEnv = { ...parentEnv }; + const env = Object.freeze(parentEnv); + const { manager, ptyAdapter } = yield* createManager(5, { env }).pipe( + Effect.provide(layerWithHostPlatform(platform)), + ); + + yield* manager.open(openInput()); + yield* manager.open(openInput({ terminalId: "override", env: runtimeEnv })); + + expect(ptyAdapter.spawnInputs).toHaveLength(2); + for (const [index, expected] of [ + { TERM_PROGRAM: "t3code", TERM_PROGRAM_VERSION: packageJson.version }, + { TERM_PROGRAM: "", TERM_PROGRAM_VERSION: "custom-version" }, + ].entries()) { + const spawnEnv = ptyAdapter.spawnInputs[index]!.env; + for (const [key, value] of Object.entries(expected)) { + expect + .soft( + Object.entries(spawnEnv) + .filter(([candidate]) => candidate.toUpperCase() === key) + .map(([, entryValue]) => entryValue), + `${index === 0 ? "default" : "override"} ${key}`, + ) + .toEqual([value]); + } + } + expect(env).toEqual(originalEnv); + }), + ); + it.effect("filters app runtime env variables from terminal sessions", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(5, { @@ -1944,6 +2571,20 @@ it.layer( }), ); + it.effect("expands a provider home named in any case on Windows", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const home = yield* HostProcess.HomeDirectory; + const { manager, ptyAdapter } = yield* createManager(5, { + env: { GROK_HOME: "C:\\inherited-grok" }, + }); + + yield* manager.open(openInput({ env: { grok_home: "~/.grok-work" } })); + + expect(ptyAdapter.spawnInputs[0]?.env.GROK_HOME).toBe(path.join(home, ".grok-work")); + }).pipe(Effect.provide(layerWithHostPlatform("win32"))), + ); + it.effect("fails closed when a provider instance is missing", () => Effect.gen(function* () { const providerInstanceId = ProviderInstanceId.make("deleted_instance"); @@ -1993,6 +2634,7 @@ it.layer( const path = yield* Path.Path; const serverSettings = yield* ServerSettings.ServerSettingsService; const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ + deriveProviderInstanceConfigMap, serverSettings, path, rawProviderInstanceId: "configured_home", @@ -2034,6 +2676,30 @@ it.layer( }), ); + it.effect("force-kills a closed terminal that ignores SIGTERM when the manager shuts down", () => + Effect.gen(function* () { + const scope = yield* Scope.make(); + const { manager, ptyAdapter } = yield* createManager(5, { + processKillGraceMs: 1_000, + }).pipe(Effect.provideService(Scope.Scope, scope)); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const sigterm = yield* Deferred.make(); + process.onKill = (signal) => { + if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void); + }; + yield* manager.close({ threadId: "thread-1" }); + yield* Deferred.await(sigterm); + + const shutdown = yield* Scope.close(scope, Exit.void).pipe(Effect.forkChild); + yield* TestClock.adjust("1 second"); + yield* Fiber.join(shutdown); + + expect(process.killSignals).toEqual(["SIGTERM", "SIGKILL"]); + expect(process.exitListenerCount).toBe(0); + }).pipe(Effect.provide(TestClock.layer())), + ); + it.effect("attaches to a running provider terminal without resolving the provider again", () => Effect.gen(function* () { const providerInstanceId = ProviderInstanceId.make("codex_work"); @@ -2073,7 +2739,7 @@ it.layer( ["win32", "C:\\Program Files\\Git\\bin\\bash.exe", undefined], ["darwin", "/bin/zsh", ["-o", "nopromptsp"]], ["linux", "/bin/zsh", ["-o", "nopromptsp"]], - ["win32", "pwsh.exe", ["-NoLogo"]], + ["win32", "pwsh.exe", POWERSHELL_ARGS], ] as const) { const { manager, ptyAdapter } = yield* createManager(5, { shellResolver: () => shell, @@ -2138,7 +2804,7 @@ it.layer( { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[0]?.pid } }, ]); expect(ptyAdapter.processes).toHaveLength(1); - }).pipe(Effect.scoped), + }), ); it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () => @@ -2212,7 +2878,7 @@ it.layer( ptyAdapter.processes.at(-1)!.emitData("new session only\n"); expect(yield* pull).toMatchObject([{ type: "output", data: "new session only\n" }]); expect(ptyAdapter.spawnInputs).toHaveLength(4); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -2259,7 +2925,58 @@ it.layer( yield* Deferred.await(restored); expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 }); - }).pipe(Effect.scoped), + }), + ); + + it.effect("sends bounded attach streams only the history the client retains", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const maxHistoryBytes = 9; + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const published = yield* Deferred.make(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" && event.data === "yz\n" + ? Deferred.succeed(published, undefined).pipe(Effect.asVoid) + : Effect.void, + ); + process.emitData("aaaa\nx名😀"); + process.emitData("yz\n"); + yield* Deferred.await(published); + unsubscribe(); + + const full = yield* Stream.toPull(manager.attachOutputStream(openInput(), "full")); + const bounded = yield* Stream.toPull( + manager.attachOutputStream({ ...openInput(), maxHistoryBytes }, "bounded"), + ); + const expectRetained = Effect.fnUntraced(function* () { + const [fullEvents, boundedEvents] = [yield* full, yield* bounded]; + const fullSnapshot = fullEvents.at(-1); + if (fullSnapshot?.type !== "snapshot") throw new Error("Expected a full snapshot"); + expect(boundedEvents.at(-1)).toEqual({ + ...fullSnapshot, + snapshot: { + ...fullSnapshot.snapshot, + history: retainedTerminalHistory(fullSnapshot.snapshot.history, maxHistoryBytes), + }, + }); + return fullSnapshot.snapshot.history; + }); + + expect(yield* expectRetained()).toBe("aaaa\nx名😀yz\n"); + // The cap starts inside 名, so the tail begins at the next code point. + expect(retainedTerminalHistory("aaaa\nx名😀yz\n", maxHistoryBytes)).toBe("😀yz\n"); + process.emitData("after\n"); + expect(yield* full).toEqual(yield* bounded); + + yield* publishPastOutputBudget(manager, process); + expect(yield* expectRetained()).toMatch(/last\n$/); + + process.emitExit({ exitCode: 0, signal: 0 }); + expect(yield* full).toEqual(yield* bounded); + yield* manager.attachStream({ ...openInput(), restartIfNotRunning: true }, () => Effect.void); + yield* expectRetained(); + }), ); it.effect("does not replay in-flight output already included in an observer snapshot", () => @@ -2296,7 +3013,7 @@ it.layer( expect(observed.filter((event) => event.type === "output")).toMatchObject([ { data: "after\n" }, ]); - }).pipe(Effect.scoped), + }), ); it.effect("observes terminal history and live output without changing the process", () => diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index e2061df592..d7fff551fa 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -5,6 +5,10 @@ import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { DEFAULT_TERMINAL_ID, DEFAULT_MAX_TERMINAL_BUFFER_BYTES, + retainedTerminalHistory, + TERMINAL_SEQUENCE_GROUND, + terminalSequenceEnd, + terminalSequenceStateAfter, TerminalCwdError, TerminalCwdNotDirectoryError, TerminalCwdNotFoundError, @@ -62,14 +66,15 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SynchronizedRef from "effect/SynchronizedRef"; +import packageJson from "../../package.json" with { type: "json" }; import * as ServerConfig from "../config.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts"; -import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; +import type { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as ServerSettings from "../serverSettings.ts"; import { increment, terminalSessionsTotal } from "../observability/Metrics.ts"; -import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { expandHomeVariable } from "@t3tools/provider-core/server/pathExpansion"; import * as ProcessRunner from "../processRunner.ts"; import * as PortScanner from "../preview/PortScanner.ts"; import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts"; @@ -165,6 +170,10 @@ class TerminalProcessSignalError extends Schema.TaggedError Effect.Effect +>("t3/terminal/TerminalCwdRecovery", { defaultValue: () => (error) => Effect.fail(error) }) {} + export class TerminalManager extends Context.Service< TerminalManager, { @@ -207,7 +216,14 @@ export class TerminalManager extends Context.Service< registerCleanup?: (stop: () => void) => void, ) => Effect.Effect<() => void, TerminalError>; - readonly write: (input: TerminalWriteInput) => Effect.Effect; + /** + * Attached viewers share one reply owner per PTY until it detaches. Marked replies + * from other or detached viewer IDs are dropped; identity-free writes do not claim ownership. + */ + readonly write: ( + input: TerminalWriteInput, + viewerId?: string, + ) => Effect.Effect; readonly resize: ( input: TerminalResizeInput, @@ -246,6 +262,7 @@ interface TerminalSubprocessInspectResult { interface TerminalSubprocessInspector { ( terminalPid: number, + shell: string | null, ): Effect.Effect; } @@ -307,6 +324,7 @@ interface TerminalSessionState { childCommandLabel: string | null; runtimeEnv: Record | null; stopOnSettle: boolean; + startupError: string | null; } interface TerminalGrid { @@ -318,6 +336,7 @@ interface TerminalGrid { interface TerminalViewer { streams: number; grid: TerminalGrid | null; + answersQueries: boolean; } interface PersistHistoryRequest { @@ -402,6 +421,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { sequence: session.eventSequence, cols: session.cols, rows: session.rows, + ...(session.startupError === null ? {} : { error: session.startupError }), }; } @@ -518,10 +538,10 @@ function defaultShellResolver(platform: NodeJS.Platform, env: NodeJS.ProcessEnv) return env.SHELL ?? "bash"; } -function normalizeShellCommand( +const normalizeShellCommand = Effect.fn("terminal.normalizeShellCommand")(function* ( value: string | undefined, platform: NodeJS.Platform, -): string | null { +) { if (!value) return null; const trimmed = value.trim(); if (trimmed.length === 0) return null; @@ -530,10 +550,24 @@ function normalizeShellCommand( return trimmed; } - const firstToken = trimmed.split(/\s+/g)[0]?.trim(); - if (!firstToken) return null; - return firstToken.replace(/^['"]|['"]$/g, ""); -} + const quoted = /^(['"])(.*?)\1(?:\s|$)/.exec(trimmed); + if (quoted) return quoted[2] || null; + + if (trimmed.startsWith("/") && /\s/.test(trimmed)) { + const fs = yield* FileSystem.FileSystem; + const ends = [...trimmed.matchAll(/\s+/g)].map((match) => match.index); + // Unquoted paths are ambiguous; prefer the longest existing file over flag syntax. + for (const end of [trimmed.length, ...ends.reverse()]) { + const candidate = trimmed.slice(0, end); + const info = yield* fs + .stat(candidate) + .pipe(Effect.catchTags({ PlatformError: () => Effect.succeed(null) })); + if (info?.type === "File") return candidate; + } + } + + return trimmed.split(/\s+(?=-)/)[0]?.replace(/^['"]|['"]$/g, "") || null; +}); function basenameForPlatform(command: string, platform: NodeJS.Platform): string { const normalized = @@ -554,6 +588,10 @@ function joinWindowsPath(...parts: ReadonlyArray): string { .join("\\"); } +// PowerShell decodes native output with the console code page (often OEM 437), mangling UTF-8. +const POWERSHELL_UTF8_SETUP = + "[Console]::OutputEncoding = $OutputEncoding = [System.Text.UTF8Encoding]::new()"; + function shellCandidateFromCommand( command: string | null, platform: NodeJS.Platform, @@ -561,7 +599,7 @@ function shellCandidateFromCommand( if (!command || command.length === 0) return null; const shellName = basenameForPlatform(command, platform).toLowerCase(); if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) { - return { shell: command, args: ["-NoLogo"] }; + return { shell: command, args: ["-NoLogo", "-NoExit", "-Command", POWERSHELL_UTF8_SETUP] }; } if (platform !== "win32" && shellName === "zsh") { return { shell: command, args: ["-o", "nopromptsp"] }; @@ -609,13 +647,13 @@ function uniqueShellCandidates(candidates: Array): ShellC return ordered; } -function resolveShellCandidates( +const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(function* ( shellResolver: () => string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): ShellCandidate[] { +) { const requested = shellCandidateFromCommand( - normalizeShellCommand(shellResolver(), platform), + yield* normalizeShellCommand(shellResolver(), platform), platform, ); @@ -633,7 +671,7 @@ function resolveShellCandidates( return uniqueShellCandidates([ requested, - shellCandidateFromCommand(normalizeShellCommand(env.SHELL, platform), platform), + shellCandidateFromCommand(yield* normalizeShellCommand(env.SHELL, platform), platform), shellCandidateFromCommand("/bin/zsh", platform), shellCandidateFromCommand("/bin/bash", platform), shellCandidateFromCommand("/bin/sh", platform), @@ -641,7 +679,7 @@ function resolveShellCandidates( shellCandidateFromCommand("bash", platform), shellCandidateFromCommand("sh", platform), ]); -} +}); function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean { const queue: unknown[] = [error]; @@ -741,21 +779,48 @@ function processTableSnapshotFromProcesses( return { childrenByParent, commandById }; } +// A root with one of these names is still an interactive shell, e.g. after `.bashrc` runs `exec zsh`. +const INTERACTIVE_SHELL_NAMES = new Set([ + "bash", + "zsh", + "fish", + "sh", + "dash", + "ksh", + "mksh", + "tcsh", + "csh", + "nu", +]); + function deriveSubprocessInspectResult( snapshot: TerminalProcessTableSnapshot, terminalPid: number, + shell: string | null, platform: NodeJS.Platform, + foregroundProcessGroup?: number | null, ): TerminalSubprocessInspectResult { const commandName = (pid: number) => normalizeChildCommandName(snapshot.commandById.get(pid) ?? "", platform); const shellName = commandName(terminalPid); - // Async prompt themes fork childless shell helpers that are not user commands. - const childPid = (snapshot.childrenByParent.get(terminalPid) ?? []).find( - (pid) => - shellName === null || - commandName(pid) !== shellName || - (snapshot.childrenByParent.get(pid)?.length ?? 0) > 0, - ); + // `exec ` replaces the shell, leaving the command itself as the root. + const rootIsCommand = + platform !== "win32" && + shell !== null && + shellName !== null && + shellName !== normalizeChildCommandName(shell, platform) && + !INTERACTIVE_SHELL_NAMES.has(shellName.replace(/^-/, "")); + // Async prompt themes fork childless shell helpers that are not user commands; + // a foreground job owns the terminal's process group, and an unknown one counts as foreground. + const childPid = rootIsCommand + ? terminalPid + : (snapshot.childrenByParent.get(terminalPid) ?? []).find( + (pid) => + shellName === null || + commandName(pid) !== shellName || + (snapshot.childrenByParent.get(pid)?.length ?? 0) > 0 || + (foregroundProcessGroup !== undefined && foregroundProcessGroup !== terminalPid), + ); if (childPid === undefined) { return { hasRunningSubprocess: false, childCommand: null, processIds: [] }; } @@ -778,6 +843,12 @@ function deriveSubprocessInspectResult( }; } +// Field 8 of /proc//stat is the tty's foreground process group; comm (field 2) may hold spaces or parens. +function parseProcStatForegroundProcessGroup(stat: string): number | null { + const tpgid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[5]); + return Number.isInteger(tpgid) ? tpgid : null; +} + const POSIX_PS_ABSOLUTE_PATHS = ["/bin/ps", "/usr/bin/ps"] as const; // Resolve ps once; bare-name spawns repeatedly probe long PATHs during one-second polling. @@ -838,7 +909,7 @@ const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnaps > { const processRunner = yield* ProcessRunner.ProcessRunner; const command = - 'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; + '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; const result = yield* processRunner .run({ command: "powershell.exe", @@ -876,6 +947,20 @@ interface TerminalHistoryChunk { lineBreaks: number; } +interface TerminalHistoryPersistenceCursor { + readonly generation: number; + readonly offset: number; + readonly fileBytes: number; +} + +function countLineBreaks(data: string): number { + let lineBreaks = 0; + for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) { + lineBreaks += 1; + } + return lineBreaks; +} + export class BoundedTerminalHistory { private readonly maxLines: number; private readonly maxBytes: number; @@ -885,7 +970,11 @@ export class BoundedTerminalHistory { private lineBreaks = 0; // Reading the old string's tail on each append can force chunk concatenation. private lastCodeUnit: number | undefined; + // The terminal parser's state at the first retained code unit, which is where a replay starts. + private sequenceState = TERMINAL_SEQUENCE_GROUND; private cachedValue: string | null = ""; + private generation = 0; + private appendedLength = 0; constructor(maxLines: number, initial: string, maxBytes = DEFAULT_HISTORY_BYTE_LIMIT) { this.maxLines = maxLines; @@ -895,6 +984,7 @@ export class BoundedTerminalHistory { append(text: string): void { if (text.length === 0) return; + this.appendedLength += text.length; this.cachedValue = null; if (this.maxBytes <= 0 || this.maxLines <= 0) { this.clear(); @@ -915,6 +1005,8 @@ export class BoundedTerminalHistory { firstCode <= 0xdfff ) { // Joining a split surrogate changes its UTF-8 size from 3 to 4 bytes. + // The previous flush may have encoded the lone surrogate as a replacement character. + this.generation += 1; previous.data += text[0]; previous.byteLength += 1; this.byteLength += 1; @@ -944,10 +1036,7 @@ export class BoundedTerminalHistory { private appendChunk(data: string): void { const byteLength = Buffer.byteLength(data); - let lineBreaks = 0; - for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) { - lineBreaks += 1; - } + const lineBreaks = countLineBreaks(data); const previous = this.chunks.at(-1); if (previous && previous.data.length + data.length <= MAX_HISTORY_CHUNK_LENGTH) { previous.data += data; @@ -964,6 +1053,7 @@ export class BoundedTerminalHistory { private discardChunk(): void { const first = this.chunks[this.start]!; + this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data); this.byteLength -= first.byteLength; this.lineBreaks -= first.lineBreaks; this.chunks[this.start++] = undefined; @@ -975,6 +1065,7 @@ export class BoundedTerminalHistory { this.discardChunk(); return; } + this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data, 0, offset); first.data = first.data.slice(offset); first.byteLength -= byteLength; first.lineBreaks -= lineBreaks; @@ -1022,6 +1113,12 @@ export class BoundedTerminalHistory { } this.trimChunk(offset, bytes, lineBreaks); } + // A cut inside a control sequence would replay the rest of it as text. + while (this.sequenceState !== TERMINAL_SEQUENCE_GROUND && this.start < this.chunks.length) { + const first = this.chunks[this.start]!; + const dropped = first.data.slice(0, terminalSequenceEnd(this.sequenceState, first.data)); + this.trimChunk(dropped.length, Buffer.byteLength(dropped), countLineBreaks(dropped)); + } if ( this.start === this.chunks.length || (this.start > 2_048 && this.start * 2 >= this.chunks.length) @@ -1033,14 +1130,49 @@ export class BoundedTerminalHistory { } clear(): void { + this.generation += 1; + this.appendedLength = 0; this.chunks = []; this.start = 0; this.byteLength = 0; this.lineBreaks = 0; this.lastCodeUnit = undefined; + this.sequenceState = TERMINAL_SEQUENCE_GROUND; this.cachedValue = ""; } + persistenceUpdate(previous?: TerminalHistoryPersistenceCursor) { + const offset = this.appendedLength; + let data: string | undefined; + if (previous?.generation === this.generation) { + let remaining = offset - previous.offset; + const tail: string[] = []; + for (let index = this.chunks.length - 1; remaining > 0 && index >= this.start; index -= 1) { + const chunk = this.chunks[index]!.data; + const suffix = chunk.slice(Math.max(0, chunk.length - remaining)); + tail.push(suffix); + remaining -= suffix.length; + } + if (remaining === 0) data = tail.toReversed().join(""); + } + // Keep the on-disk log bounded while amortizing compaction across new output. + // Readers already cap the plain-text tail by bytes and lines. + const append = + data !== undefined && + previous !== undefined && + previous.fileBytes + Buffer.byteLength(data) <= this.maxBytes * 2; + const output = append && data !== undefined ? data : this.value(); + return { + data: output, + append, + cursor: { + generation: this.generation, + offset, + fileBytes: (append ? previous.fileBytes : 0) + Buffer.byteLength(output), + }, + }; + } + value(): string { if (this.cachedValue !== null) return this.cachedValue; this.cachedValue = this.chunks @@ -1105,7 +1237,7 @@ function shouldStripCsiSequence(body: string, finalByte: string): boolean { if (finalByte === "R" && /^[0-9;?]*$/.test(body)) { return true; } - if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) { + if (finalByte === "c" && /^[>=0-9;?]*$/.test(body)) { return true; } // Strip DECRQM/DECRPM query traffic to prevent echoed replies during replay; $ guards preserve setters. @@ -1143,16 +1275,70 @@ function stripStringTerminator(value: string): string { return value; } -function findStringTerminatorIndex(input: string, start: number): number | null { +interface C1Effect { + /** ESC form of the sequence the code point starts, or "" when it returns to ground. */ + readonly next: string; + /** Its 0x9A byte ran DECID, which replies with device attributes. */ + readonly query: boolean; + /** What replays its visible effect from ground. */ + readonly safe: string; +} + +// Outside ground and OSC, libghostty parses a code point's UTF-8 bytes one at a time: 0x80-0x9F +// act as C1 controls, the rest are dropped. Bytes left over after a return to ground print U+FFFD. +function c1Effect(codePoint: number): C1Effect | undefined { + // A lone surrogate is encoded as U+FFFD, whose bytes are all dropped. + if (codePoint >= 0xd800 && codePoint <= 0xdfff) return undefined; + let next: string | undefined; + let query = false; + let safe = ""; + for (let shift = codePoint > 0xffff ? 12 : codePoint > 0x7ff ? 6 : 0; shift >= 0; shift -= 6) { + const byte = 0x80 | ((codePoint >> shift) & 0x3f); + if (next === "") { + safe += "\ufffd"; + } else if (next?.startsWith("\u001b]")) { + next += "\ufffd"; + } else if (byte === 0x9b) { + next = "\u001b["; + } else if (byte === 0x9d) { + next = "\u001b]"; + } else if (byte === 0x90) { + next = "\u001bP"; + } else if (byte === 0x98 || byte === 0x9e || byte === 0x9f) { + next = "\u001b_"; + } else if (byte < 0xa0) { + next = ""; + query = byte === 0x9a; + // Any other C1 control but ST runs as ESC plus the byte less 0x40. + safe = query || byte === 0x9c ? "" : `\u001b${String.fromCharCode(byte - 0x40)}`; + } + } + return next === undefined ? undefined : { next, query, safe }; +} + +// BEL ends only OSC; inside DCS, PM and APC it is payload. Non-ASCII is the reverse: libghostty +// keeps it inside OSC, while a C1 byte in it ends the other strings. +function findStringEnd( + input: string, + start: number, + isOsc: boolean, +): { end: number; c1?: { effect: C1Effect; index: number } } | null { for (let index = start; index < input.length; index += 1) { const codePoint = input.charCodeAt(index); - if (codePoint === 0x07 || codePoint === 0x9c || isControlSequenceCancel(codePoint)) { - return index + 1; + if ((isOsc && codePoint === 0x07) || isControlSequenceCancel(codePoint)) { + return { end: index + 1 }; } // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence. if (codePoint === 0x1b) { if (index + 1 >= input.length) return null; - return input.charCodeAt(index + 1) === 0x5c ? index + 2 : index; + return { end: input.charCodeAt(index + 1) === 0x5c ? index + 2 : index }; + } + if (codePoint >= 0x80 && !isOsc) { + const fullCodePoint = input.codePointAt(index) ?? codePoint; + const end = index + (fullCodePoint > 0xffff ? 2 : 1); + const effect = c1Effect(fullCodePoint); + if (effect) return { end, c1: { effect, index } }; + index = end - 1; } } return null; @@ -1198,6 +1384,8 @@ function sanitizeTerminalHistoryChunk( const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); let visibleText = ""; let index = 0; + // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it. + let c1Introducer = ""; const append = (value: string) => { visibleText += value; @@ -1206,29 +1394,68 @@ function sanitizeTerminalHistoryChunk( while (index < input.length) { const codePoint = input.charCodeAt(index); - if (codePoint === 0x1b) { - const nextCodePoint = input.charCodeAt(index + 1); + if (c1Introducer.length > 0 || codePoint === 0x1b) { + // Empty for a sequence the input introduces itself, which starts with ESC at `index`. + const prefix = c1Introducer; + c1Introducer = ""; + const contentStart = prefix.length > 0 ? index : index + 2; + const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1); if (Number.isNaN(nextCodePoint)) { return { visibleText, pendingControlSequence: input.slice(index) }; } if (nextCodePoint === 0x5b) { - let cursor = index + 2; + let cursor = contentStart; + // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would + // print in ground state. None join the parameters; only executed ones survive a strip. + let body = ""; + let executedControls = ""; while (cursor < input.length) { - const cancelled = isControlSequenceCancel(input.charCodeAt(cursor)); - if (cancelled || isCsiFinalByte(input.charCodeAt(cursor))) { - const sequence = input.slice(index, cursor + 1); - const body = input.slice(index + 2, cursor); + const cursorCodePoint = input.charCodeAt(cursor); + const cancelled = isControlSequenceCancel(cursorCodePoint); + if (cancelled || isCsiFinalByte(cursorCodePoint)) { if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { - append(sequence); + append(prefix + input.slice(index, cursor + 1)); + } else { + append(executedControls); } index = cursor + 1; break; } + if (cursorCodePoint >= 0x80) { + const fullCodePoint = input.codePointAt(cursor) ?? cursorCodePoint; + const end = cursor + (fullCodePoint > 0xffff ? 2 : 1); + const c1 = c1Effect(fullCodePoint); + if (c1) { + // The CSI ends here undispatched, so it is kept only when the terminal is back in + // ground with nothing to answer. + if (c1.next.length === 0 && !c1.query) { + append(prefix + input.slice(index, end)); + } else { + append(executedControls + c1.safe); + } + c1Introducer = c1.next; + index = end; + break; + } + cursor = end; + continue; + } + // An ESC abandons the CSI and starts the next sequence, which may be stripped. + if (cursorCodePoint === 0x1b) { + append(executedControls); + index = cursor; + break; + } + if (cursorCodePoint < 0x10) { + executedControls += input[cursor]; + } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) { + body += input[cursor]; + } cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: input.slice(index) }; + return { visibleText, pendingControlSequence: prefix + input.slice(index) }; } continue; } @@ -1239,22 +1466,32 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5e || nextCodePoint === 0x5f ) { - const terminatorIndex = findStringTerminatorIndex( + const stringEnd = findStringEnd( input, - Math.max(index + 2, pendingScanStart), + Math.max(contentStart, pendingScanStart), + nextCodePoint === 0x5d, ); - if (terminatorIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + if (stringEnd === null) { + return { visibleText, pendingControlSequence: prefix + input.slice(index) }; } - const sequence = input.slice(index, terminatorIndex); - const content = stripStringTerminator(input.slice(index + 2, terminatorIndex)); + const { end, c1 } = stringEnd; + const content = stripStringTerminator( + prefix.slice(2) + input.slice(contentStart, c1?.index ?? end), + ); const strip = (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); - if (!strip) { - append(sequence); + if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { + if (!strip) { + append(prefix + input.slice(index, end)); + } + } else { + // ST stands in for a code point that cannot be replayed as it came. + const closed = strip ? "" : `${prefix}${input.slice(index, c1.index)}\u009c`; + append(closed + c1.effect.safe); + c1Introducer = c1.effect.next; } - index = terminatorIndex; + index = end; continue; } @@ -1262,7 +1499,10 @@ function sanitizeTerminalHistoryChunk( if (escapeSequenceEndIndex === null) { return { visibleText, pendingControlSequence: input.slice(index) }; } - append(input.slice(index, escapeSequenceEndIndex)); + // ESC Z (DECID) is the legacy primary device attributes query. + if (nextCodePoint !== 0x5a) { + append(input.slice(index, escapeSequenceEndIndex)); + } index = escapeSequenceEndIndex; continue; } @@ -1274,7 +1514,7 @@ function sanitizeTerminalHistoryChunk( index = nextSequenceStart; } - return { visibleText, pendingControlSequence: "" }; + return { visibleText, pendingControlSequence: c1Introducer }; } function legacySafeThreadId(threadId: string): string { @@ -1363,16 +1603,27 @@ function createTerminalSpawnEnv( for (const [key, value] of Object.entries(baseEnv)) { if (value === undefined) continue; if (shouldExcludeTerminalEnvKey(key)) continue; + if (platform === "win32") { + const normalizedKey = key.toUpperCase(); + if (normalizedKey === "TERM_PROGRAM" || normalizedKey === "TERM_PROGRAM_VERSION") continue; + } spawnEnv[key] = value; } + // The server inherits its launcher's identity (e.g. Apple_Terminal); shells + // and tools inside the integrated terminal should see T3 Code instead. + spawnEnv.TERM_PROGRAM = "t3code"; + spawnEnv.TERM_PROGRAM_VERSION = packageJson.version; if (runtimeEnv) { for (const [key, value] of Object.entries(runtimeEnv)) { const existingKey = platform === "win32" ? Object.keys(spawnEnv).find((candidate) => candidate.toLowerCase() === key.toLowerCase()) : undefined; - spawnEnv[existingKey ?? key] = - key === "CODEX_HOME" || key === "CLAUDE_CONFIG_DIR" ? expandHomePath(value, home) : value; + spawnEnv[existingKey ?? key] = expandHomeVariable( + platform === "win32" ? key.toUpperCase() : key, + value, + home, + ); } } if (!spawnEnv.COLORTERM && runtimeEnv?.COLORTERM === undefined) { @@ -1415,6 +1666,7 @@ interface TerminalManagerOptions { ReadonlyArray, TerminalSubprocessCheckError >; + foregroundProcessGroup?: (terminalPid: number) => Effect.Effect; subprocessPollIntervalMs?: number; processKillGraceMs?: number; maxRetainedInactiveSessions?: number; @@ -1439,6 +1691,7 @@ interface TerminalManagerOptions { export const resolveProviderInstanceTerminalEnvironment = Effect.fn( "terminal.resolveProviderInstanceTerminalEnvironment", )(function* (input: { + readonly deriveProviderInstanceConfigMap: typeof deriveProviderInstanceConfigMap; readonly serverSettings: ServerSettings.ServerSettingsService["Service"]; readonly path: Path.Path; readonly rawProviderInstanceId: string; @@ -1448,7 +1701,7 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( const settings = yield* input.serverSettings.getSettings.pipe( Effect.mapError((cause) => new TerminalProviderEnvironmentError({ providerInstanceId, cause })), ); - const instance = deriveProviderInstanceConfigMap(settings)[providerInstanceId]; + const instance = input.deriveProviderInstanceConfigMap(settings)[providerInstanceId]; if (instance === undefined) { return yield* new TerminalProviderInstanceNotFoundError({ providerInstanceId }); } @@ -1478,7 +1731,9 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( }); /** @public */ -export const make = Effect.fn("TerminalManager.make")(function* () { +export const make = Effect.fn("TerminalManager.make")(function* ( + deriveConfigMap: typeof deriveProviderInstanceConfigMap, +) { const { terminalLogsDir, providerStatusCacheDir, baseDir } = yield* ServerConfig.ServerConfig; const ptyAdapter = yield* PtyAdapter.PtyAdapter; const portDiscovery = yield* PortScanner.PortDiscovery; @@ -1489,6 +1744,7 @@ export const make = Effect.fn("TerminalManager.make")(function* () { "terminal.resolveProviderInstanceEnvironment", )((rawProviderInstanceId: string, env: Record | undefined) => resolveProviderInstanceTerminalEnvironment({ + deriveProviderInstanceConfigMap: deriveConfigMap, serverSettings, path, rawProviderInstanceId, @@ -1591,6 +1847,30 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func snapshotSucceeded: Result.isSuccess(fallback.snapshot), })), ); + const foregroundProcessGroup = + options.foregroundProcessGroup ?? + ((terminalPid: number) => + platform === "linux" + ? fileSystem.readFileString(`/proc/${terminalPid}/stat`).pipe( + Effect.map(parseProcStatForegroundProcessGroup), + Effect.orElseSucceed(() => null), + ) + : processRunner + .run({ + command: posixPsCommand ?? "ps", + args: ["-o", "tpgid=", "-p", String(terminalPid)], + timeout: CLOSE_IDLE_QUERY_TIMEOUT.posix, + timeoutBehavior: "timedOutResult", + }) + .pipe( + Effect.map((result) => { + const tpgid = Number(result.stdout.trim()); + return result.code === 0 && !result.timedOut && Number.isInteger(tpgid) && tpgid > 0 + ? tpgid + : null; + }), + Effect.orElseSucceed(() => null), + )); const customSubprocessInspector = options.subprocessInspector; const acquireSubprocessInspector = ( fallbackTimeout: Duration.Input, @@ -1611,8 +1891,20 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func inspector: Result.map( snapshot, (table): TerminalSubprocessInspector => - (terminalPid) => - Effect.succeed(deriveSubprocessInspectResult(table, terminalPid, platform)), + (terminalPid, shell) => { + const result = deriveSubprocessInspectResult(table, terminalPid, shell, platform); + // Only shell-named childless children are ambiguous; read the foreground group for those alone. + if ( + result.hasRunningSubprocess || + platform === "win32" || + (table.childrenByParent.get(terminalPid)?.length ?? 0) === 0 + ) { + return Effect.succeed(result); + } + return Effect.map(foregroundProcessGroup(terminalPid), (group) => + deriveSubprocessInspectResult(table, terminalPid, shell, platform, group), + ); + }, ), snapshotSucceeded, queryElapsedMs, @@ -1668,14 +1960,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); }; - const legacyHistoryPath = (threadId: string) => - path.join(logsDir, `${legacySafeThreadId(threadId)}.log`); + const legacyHistoryName = (threadId: string) => `${legacySafeThreadId(threadId)}.log`; + // Legacy names in the current "terminal_" namespace would alias another thread's history, + // case-insensitively on some filesystems. + const hasLegacyHistoryName = (threadId: string) => + !legacySafeThreadId(threadId).toLowerCase().startsWith("terminal_"); const historyPaths = (threadId: string, terminalId: string) => [ ...new Set([ historyPath(threadId, terminalId), encodedHistoryPath(threadId, terminalId), - ...(terminalId === DEFAULT_TERMINAL_ID ? [legacyHistoryPath(threadId)] : []), + ...(terminalId === DEFAULT_TERMINAL_ID && hasLegacyHistoryName(threadId) + ? [path.join(logsDir, legacyHistoryName(threadId))] + : []), ]), ]; @@ -1714,7 +2011,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func // After a viewer's first size, resizes own it; attach retries resend the original size. viewer.grid ??= grid; } else { - viewers.set(viewerId, { streams: 1, grid }); + viewers.set(viewerId, { streams: 1, grid, answersQueries: false }); } }; @@ -1730,6 +2027,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return true; }; + // The first attached viewer to answer a query keeps answering until it detaches. + const acceptsQueryReply = (sessionKey: string, viewerId: string | undefined) => { + const viewers = terminalViewers.get(sessionKey); + const viewer = viewerId === undefined ? undefined : viewers?.get(viewerId); + if (viewerId !== undefined && !viewer) return false; + if (viewer?.answersQueries) return true; + for (const other of viewers?.values() ?? []) { + if (other.answersQueries) return false; + } + if (viewer) viewer.answersQueries = true; + return true; + }; + // The smallest attached viewer bounds each axis, so every viewer can draw the whole grid. const sharedViewerGrid = (sessionKey: string): TerminalGrid | null => { let shared: TerminalGrid | null = null; @@ -1922,6 +2232,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* registerKillFiber(process, fiber); }); + const persistedHistory = new WeakMap(); const persistWorker = yield* makeKeyedCoalescingWorker< string, PersistHistoryRequest, @@ -1942,9 +2253,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return; } + const update = request.history.persistenceUpdate( + request.immediate ? undefined : persistedHistory.get(request.history), + ); + if (update.append && update.data.length === 0) return; + // An append may partially succeed before failing. Retry from a full snapshot, + // never from an uncertain file offset. + persistedHistory.delete(request.history); yield* fileSystem - .writeFileString(historyPath(threadId, terminalId), request.history.value()) + .writeFileString(historyPath(threadId, terminalId), update.data, { + flag: update.append ? "a" : "w", + }) .pipe( + Effect.tap(() => Effect.sync(() => persistedHistory.set(request.history, update.cursor))), Effect.catch((error) => Effect.logWarning("failed to persist terminal history", { threadId, @@ -1991,6 +2312,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const info = yield* file.stat; const limit = BigInt(historyByteLimit); const offset = info.size > limit ? info.size - limit : 0n; + // The tail can start inside a control sequence; only the bytes before it say which. + const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); + let sequenceState = TERMINAL_SEQUENCE_GROUND; + const skipped = new Uint8Array(Math.min(Number(offset), 64 * 1024)); + for (let remaining = Number(offset); remaining > 0;) { + const read = Number(yield* file.read(skipped.subarray(0, remaining))); + if (read === 0) break; + remaining -= read; + sequenceState = terminalSequenceStateAfter( + sequenceState, + decoder.decode(skipped.subarray(0, read), { stream: true }), + ); + } yield* file.seek(offset, "start"); const bytes = new Uint8Array(Number(info.size - offset)); let length = 0; @@ -2004,8 +2338,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func // A tail read can start inside a UTF-8 code point. Skip its remaining bytes. while (start < length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start += 1; } + sequenceState = terminalSequenceStateAfter( + sequenceState, + decoder.decode(bytes.subarray(0, start)), + ); + const history = new TextDecoder("utf-8", { ignoreBOM: true }).decode( + bytes.subarray(start, length), + ); return { - history: new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(start, length)), + history: history.slice(terminalSequenceEnd(sequenceState, history)), truncated: offset > 0n, }; }); @@ -2035,17 +2376,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit); const capped = history.value(); if (migrating || truncated || capped !== raw) { - const write = migrating - ? Effect.gen(function* () { - const temporaryPath = yield* fileSystem.makeTempFileScoped({ - directory: logsDir, - prefix: ".history-", - }); - yield* fileSystem.writeFileString(temporaryPath, capped); - yield* fileSystem.rename(temporaryPath, nextPath); - }).pipe(Effect.scoped) - : fileSystem.writeFileString(nextPath, capped); - yield* write.pipe( + const write = Effect.gen(function* () { + const temporaryPath = yield* fileSystem.makeTempFileScoped({ + directory: logsDir, + prefix: ".history-", + }); + yield* fileSystem.writeFileString(temporaryPath, capped); + yield* fileSystem.rename(temporaryPath, nextPath); + }).pipe( + Effect.scoped, Effect.mapError( (cause) => new TerminalHistoryError({ @@ -2056,6 +2395,17 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }), ), ); + yield* migrating + ? write + : write.pipe( + Effect.catch((error) => + Effect.logWarning("failed to compact terminal history", { + threadId, + terminalId, + error, + }), + ), + ); } if (migrating) { yield* fileSystem.remove(sourcePath, { force: true }).pipe( @@ -2107,7 +2457,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* Effect.forEach( entries.filter( (name) => - name === `${legacySafeThreadId(threadId)}.log` || + (hasLegacyHistoryName(threadId) && name === legacyHistoryName(threadId)) || threadParts.some((part) => name === `${part}.log` || name.startsWith(`${part}_`)), ), (name) => @@ -2124,7 +2474,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }); const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) { - const stats = yield* fileSystem.stat(cwd).pipe( + const stat = fileSystem.stat(cwd).pipe( Effect.catchTags({ PlatformError: (cause) => cause.reason._tag === "NotFound" @@ -2132,6 +2482,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func : new TerminalCwdStatError({ cwd, cause }), }), ); + const stats = yield* stat.pipe( + Effect.catchTags({ + TerminalCwdNotFoundError: (error) => + Effect.flatMap(TerminalCwdRecovery, (recover) => + recover(error).pipe(Effect.andThen(stat)), + ), + }), + ); if (stats.type !== "Directory") { return yield* new TerminalCwdNotDirectoryError({ cwd }); } @@ -2420,6 +2778,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const startingAt = yield* nowIso; yield* modifyManagerState((state) => { session.status = "starting"; + session.startupError = null; session.shell = null; session.cwd = input.cwd; session.worktreePath = input.worktreePath ?? null; @@ -2443,7 +2802,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func increment(terminalSessionsTotal, { lifecycle: eventType }).pipe( Effect.andThen( Effect.gen(function* () { - const shellCandidates = resolveShellCandidates(shellResolver, platform, baseEnv); + const shellCandidates = yield* resolveShellCandidates( + shellResolver, + platform, + baseEnv, + ).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem)); const terminalEnv = createTerminalSpawnEnv( baseEnv, session.runtimeEnv, @@ -2536,6 +2899,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func { const error = startResult.failure; + const message = error.message; if (ptyProcess) { yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId); } @@ -2543,6 +2907,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* modifyManagerState((state) => { cleanupProcessHandles(session); session.status = "error"; + session.startupError = message; session.pid = null; session.process = null; session.hasRunningSubprocess = false; @@ -2560,7 +2925,6 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* evictInactiveSessionsIfNeeded(); - const message = error.message; yield* publishEvent({ type: "error", threadId: session.threadId, @@ -2678,7 +3042,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func let mark = candidate.mark; const previous = quietSessions.get(session); quietSessions.delete(session); - const inspectResult = yield* subprocessInspector(terminalPid).pipe( + const inspectResult = yield* subprocessInspector(terminalPid, session.shell).pipe( Effect.asSome, Effect.catch((reason) => Effect.logWarning("failed to check terminal subprocess activity", { @@ -2802,10 +3166,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* Effect.addFinalizer(() => Effect.gen(function* () { - const sessions = yield* modifyManagerState( + const [sessions, pendingKills] = yield* modifyManagerState( (state) => [ - [...state.sessions.values()], + [[...state.sessions.values()], [...state.killFibers.values()]], { ...state, sessions: new Map(), @@ -2822,10 +3186,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* runKillEscalation(session.process, session.threadId, session.terminalId); }); - yield* Effect.forEach(sessions, cleanupSession, { - concurrency: "unbounded", - discard: true, - }); + // Closing workerScope next would interrupt escalations of already stopped terminals. + yield* Effect.all( + [ + Effect.forEach(sessions, cleanupSession, { concurrency: "unbounded", discard: true }), + Fiber.awaitAll(pendingKills), + ], + { concurrency: "unbounded", discard: true }, + ); }).pipe(Effect.ignoreCause({ log: true })), ); @@ -2879,6 +3247,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func childCommandLabel: null, runtimeEnv: normalizedRuntimeEnv(input.env), stopOnSettle: input.stopOnSettle ?? false, + startupError: null, }; const createdSession = session; @@ -3224,20 +3593,41 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func registerCleanup, ); - const attachOutputStream: TerminalManager["Service"]["attachOutputStream"] = (input, viewerId) => - Stream.unwrap( + const attachOutputStream: TerminalManager["Service"]["attachOutputStream"] = ( + input, + viewerId, + ) => { + const { maxHistoryBytes } = input; + const retained = (listener: (event: TerminalAttachStreamEvent) => Effect.Effect) => + maxHistoryBytes === undefined + ? listener + : (event: TerminalAttachStreamEvent) => + listener( + "snapshot" in event + ? { + ...event, + snapshot: { + ...event.snapshot, + history: retainedTerminalHistory(event.snapshot.history, maxHistoryBytes), + }, + } + : event, + ); + return Stream.unwrap( Effect.acquireRelease( Effect.sync(() => retainViewerOnce(input, viewerId, null)), (release) => Effect.sync(release), ).pipe( Effect.as( terminalOutputStream( - (listener, registerCleanup) => attachStream(input, listener, registerCleanup, viewerId), - (listener, registerCleanup) => resyncStream(input, listener, registerCleanup), + (listener, registerCleanup) => + attachStream(input, retained(listener), registerCleanup, viewerId), + (listener, registerCleanup) => resyncStream(input, retained(listener), registerCleanup), ), ), ), ); + }; const metadataEventFromTerminalEvent = ( event: TerminalEvent, @@ -3321,29 +3711,34 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); }; - const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")(function* (input) { - const terminalId = input.terminalId; - const session = yield* requireSession(input.threadId, terminalId); - const process = session.process; - if (!process || session.status !== "running") { - if (session.status === "exited") return; - return yield* new TerminalNotRunningError({ - threadId: input.threadId, - terminalId, - }); - } - session.inputCount += 1; - yield* Effect.try({ - try: () => process.write(input.data), - catch: (cause) => - new TerminalWriteError({ + const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")( + function* (input, viewerId) { + const terminalId = input.terminalId; + const session = yield* requireSession(input.threadId, terminalId); + const process = session.process; + if (!process || session.status !== "running") { + if (session.status === "exited") return; + return yield* new TerminalNotRunningError({ threadId: input.threadId, terminalId, - terminalPid: process.pid, - cause, - }), - }); - }); + }); + } + if (input.reply && !acceptsQueryReply(toSessionKey(input.threadId, terminalId), viewerId)) { + return; + } + session.inputCount += 1; + yield* Effect.try({ + try: () => process.write(PtyAdapter.ptyInput(input.data, input.binary)), + catch: (cause) => + new TerminalWriteError({ + threadId: input.threadId, + terminalId, + terminalPid: process.pid, + cause, + }), + }); + }, + ); const resizeLocked = Effect.fn("terminal.resize")(function* ( input: TerminalResizeInput, @@ -3388,7 +3783,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func session.pendingProcessEventIndex = 0; session.processEventDrainRunning = false; const eventStamp = advanceEventSequence(session); - yield* persistHistory(input.threadId, terminalId, session.history); + // A drain waits for the key to go idle, which never happens while the shell keeps + // printing; every reader of the file flushes it first. + yield* persistWorker.enqueue(toSessionKey(input.threadId, terminalId), { + history: session.history, + immediate: true, + }); yield* publishEvent({ type: "cleared", threadId: input.threadId, @@ -3442,7 +3842,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* Effect.forEach( running, (session) => - inspector(session.pid).pipe( + inspector(session.pid, session.shell).pipe( Effect.flatMap((result) => result.hasRunningSubprocess || terminalActivityMark(session) !== marks.get(session.terminalId) @@ -3497,4 +3897,5 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }); }); -export const layer = Layer.effect(TerminalManager, make()).pipe(Layer.provide(ProcessRunner.layer)); +export const layer = (deriveConfigMap: typeof deriveProviderInstanceConfigMap) => + Layer.effect(TerminalManager, make(deriveConfigMap)).pipe(Layer.provide(ProcessRunner.layer)); diff --git a/apps/server/src/terminal/NodePtyAdapter.ts b/apps/server/src/terminal/NodePtyAdapter.ts index cc7ae638f7..4035e23f2b 100644 --- a/apps/server/src/terminal/NodePtyAdapter.ts +++ b/apps/server/src/terminal/NodePtyAdapter.ts @@ -190,7 +190,7 @@ class NodePtyProcess implements PtyAdapter.PtyProcess { return this.process.pid; } - write(data: string): void { + write(data: string | Buffer): void { this.process.write(data); } diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.ts index 9750f41815..7ae536605e 100644 --- a/apps/server/src/terminal/OutputProtocol.test.ts +++ b/apps/server/src/terminal/OutputProtocol.test.ts @@ -9,80 +9,99 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Queue from "effect/Queue"; -import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc"; import { terminalOutputStream, withOutputWindow } from "./OutputProtocol.ts"; +const eventWith = ( + field: "data" | "message" | "threadId", + text: string, +): TerminalAttachStreamEvent => + field === "message" + ? { threadId: "thread-1", terminalId: "default", type: "error", message: text } + : { + threadId: field === "threadId" ? text : "thread-1", + terminalId: "default", + type: "output", + data: field === "data" ? text : "x", + }; + describe("terminal output window", () => { it.effect.each([ - { tag: WS_METHODS.terminalAttach, size: 1, limit: 8 }, - { tag: WS_METHODS.terminalObserve, size: 1, limit: 8 }, - { tag: WS_METHODS.terminalAttach, size: 64 * 1024, limit: 1 }, - { tag: WS_METHODS.terminalObserve, size: 64 * 1024, limit: 1 }, - { tag: WS_METHODS.subscribeServerConfig, size: 1, limit: 8 }, - { tag: ORCHESTRATION_V2_WS_METHODS.subscribeShell, size: 1, limit: 8 }, - { tag: ORCHESTRATION_V2_WS_METHODS.subscribeThread, size: 64 * 1024, limit: 8 }, - { tag: WS_METHODS.subscribeTerminalMetadata, size: 1, limit: 1 }, - ])("limits $tag with $size-byte values to $limit pending chunks", ({ tag, size, limit }) => - Effect.gen(function* () { - const group = RpcGroup.make(Rpc.make(tag, { success: Schema.String, stream: true })); - const output = yield* Queue.unbounded(); - const responses = yield* Queue.unbounded(); - const receive = yield* Deferred.make[0]>(); - const protocol = yield* RpcServer.Protocol.make((write) => - Effect.gen(function* () { - yield* Deferred.succeed(receive, write); - const serialization = yield* RpcSerialization.RpcSerialization; - return { - disconnects: yield* Queue.unbounded(), - send: (_clientId, response) => Queue.offer(responses, response), - end: () => Effect.void, - clientIds: Effect.succeed(new Set([0])), - initialMessage: Effect.succeedNone, - supportsAck: true, - supportsTransferables: false, - supportsSpanPropagation: false, - supportsNotifications: true, - codecFor: serialization.codecFor, - }; - }), - ); - yield* RpcServer.make(group).pipe( - Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))), - Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol)), - Effect.forkScoped, - ); - const write = yield* Deferred.await(receive); - yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] }); + { tag: WS_METHODS.terminalAttach, field: "data", size: 1, limit: 8 }, + { tag: WS_METHODS.terminalObserve, field: "data", size: 1, limit: 8 }, + { tag: WS_METHODS.terminalAttach, field: "data", size: 64 * 1024, limit: 1 }, + { tag: WS_METHODS.terminalObserve, field: "data", size: 64 * 1024, limit: 1 }, + { tag: WS_METHODS.terminalAttach, field: "message", size: 64 * 1024, limit: 1 }, + { tag: WS_METHODS.terminalAttach, field: "threadId", size: 64 * 1024, limit: 1 }, + { tag: WS_METHODS.subscribeServerConfig, field: "data", size: 1, limit: 8 }, + { tag: ORCHESTRATION_V2_WS_METHODS.subscribeShell, field: "data", size: 1, limit: 8 }, + { tag: ORCHESTRATION_V2_WS_METHODS.subscribeThread, field: "data", size: 64 * 1024, limit: 8 }, + { tag: WS_METHODS.subscribeTerminalMetadata, field: "data", size: 1, limit: 1 }, + ] as const)( + "limits $tag with $size-byte $field values to $limit pending chunks", + ({ tag, field, size, limit }) => + Effect.gen(function* () { + const group = RpcGroup.make( + Rpc.make(tag, { success: TerminalAttachStreamEventSchema, stream: true }), + ); + const output = yield* Queue.unbounded(); + const responses = yield* Queue.unbounded(); + const receive = yield* Deferred.make[0]>(); + const protocol = yield* RpcServer.Protocol.make((write) => + Effect.gen(function* () { + yield* Deferred.succeed(receive, write); + const serialization = yield* RpcSerialization.RpcSerialization; + return { + disconnects: yield* Queue.unbounded(), + send: (_clientId, response) => Queue.offer(responses, response), + end: () => Effect.void, + clientIds: Effect.succeed(new Set([0])), + initialMessage: Effect.succeedNone, + supportsAck: true, + supportsTransferables: false, + supportsSpanPropagation: false, + supportsNotifications: true, + codecFor: serialization.codecFor, + }; + }), + ); + yield* RpcServer.make(group).pipe( + Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))), + Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol)), + Effect.forkScoped, + ); + const write = yield* Deferred.await(receive); + yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] }); - for (let index = 0; index < limit; index++) { - const value = String(index).repeat(size); - yield* Queue.offer(output, value); + for (let index = 0; index < limit; index++) { + const value = eventWith(field, String(index).repeat(size)); + yield* Queue.offer(output, value); + yield* TestClock.adjust(0); + assert.equal(yield* Queue.size(responses), 1); + assert.deepEqual(yield* Queue.take(responses), { + _tag: "Chunk", + requestId: "1", + values: [value], + }); + } + const resumedValue = eventWith(field, "i".repeat(size)); + yield* Queue.offer(output, resumedValue); yield* TestClock.adjust(0); - assert.equal(yield* Queue.size(responses), 1); - assert.deepEqual(yield* Queue.take(responses), { - _tag: "Chunk", - requestId: "1", - values: [value], - }); - } - yield* Queue.offer(output, "i".repeat(size)); - yield* TestClock.adjust(0); - assert.equal(yield* Queue.size(responses), 0); - yield* write(0, { _tag: "Ack", requestId: "1" }); - const resumed = yield* Queue.take(responses); - assert.equal(resumed._tag, "Chunk"); - if (resumed._tag === "Chunk") assert.deepEqual(resumed.values, ["i".repeat(size)]); + assert.equal(yield* Queue.size(responses), 0); + yield* write(0, { _tag: "Ack", requestId: "1" }); + const resumed = yield* Queue.take(responses); + assert.equal(resumed._tag, "Chunk"); + if (resumed._tag === "Chunk") assert.deepEqual(resumed.values, [resumedValue]); - yield* Queue.offer(output, "j"); - yield* TestClock.adjust(0); - assert.equal(yield* Queue.size(responses), 0); - yield* write(0, { _tag: "Interrupt", requestId: "1" }); - assert.equal((yield* Queue.take(responses))._tag, "Exit"); - }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), + yield* Queue.offer(output, eventWith(field, "j")); + yield* TestClock.adjust(0); + assert.equal(yield* Queue.size(responses), 0); + yield* write(0, { _tag: "Interrupt", requestId: "1" }); + assert.equal((yield* Queue.take(responses))._tag, "Exit"); + }).pipe(Effect.provide(RpcSerialization.layerJson)), ); }); @@ -199,6 +218,9 @@ describe("terminal output stream", () => { Effect.forkScoped, ); const write = yield* Deferred.await(receive); + // Each event arrives after the batching window, so it is sent on its own. + const publish = (event: TerminalAttachStreamEvent) => + TestClock.adjust("2 millis").pipe(Effect.andThen(publisher.publish(event))); const takeChunk = Effect.fnUntraced(function* (queue: typeof stalled) { const response = yield* Queue.take(queue); assert.equal(response._tag, "Chunk"); @@ -215,7 +237,7 @@ describe("terminal output stream", () => { // Eight unacknowledged chunks fill only client 0's output window. for (let index = 0; index < 7; index++) { const event = output("before-stall-" + index); - yield* publisher.publish(event); + yield* publish(event); assert.deepEqual(yield* takeChunk(stalled), [event]); assert.deepEqual(yield* takeChunk(healthy), [event]); yield* write(1, { _tag: "Ack", requestId: "2" }); @@ -223,7 +245,7 @@ describe("terminal output stream", () => { assert.equal(publisher.listeners.size, 2); for (let index = 0; index < 100; index++) { const event = output(index + ":" + "界".repeat(1365)); - yield* publisher.publish(event); + yield* publish(event); assert.deepEqual(yield* takeChunk(healthy), [event]); yield* write(1, { _tag: "Ack", requestId: "2" }); if (index === 31) assert.equal(publisher.listeners.size, 2); @@ -238,11 +260,11 @@ describe("terminal output stream", () => { yield* write(0, { _tag: "Ack", requestId: "1" }); } const after = output("unique output after recovery"); - yield* publisher.publish(after); + yield* publish(after); assert.deepEqual(yield* takeChunk(healthy), [after]); assert.deepEqual(yield* takeChunk(stalled), [after]); assert.equal(yield* Queue.size(stalled), 0); - }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), + }).pipe(Effect.provide(RpcSerialization.layerJson)), ); it.effect("interrupts recovery while its subscription is still waiting", () => @@ -271,7 +293,7 @@ describe("terminal output stream", () => { yield* Fiber.interrupt(recovery); yield* Deferred.await(interrupted); assert.equal(publisher.listeners.size, 0); - }).pipe(Effect.scoped), + }), ); it.effect("cleans listeners when cancelled during a successful acquisition handoff", () => @@ -305,10 +327,51 @@ describe("terminal output stream", () => { yield* Fiber.join(cancellation); assert.equal(publisher.listeners.size, 0); } + }), + ); + + it.effect("emits idle output immediately and batches a burst until a fixed deadline", () => + Effect.gen(function* () { + const publisher = makePublisher(); + const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, ""))); + assert.deepEqual(yield* pull, [snapshot("")]); + + yield* TestClock.adjust("10 millis"); + yield* publisher.publish(output("a")); + assert.deepEqual(yield* pull, [output("a")]); + + yield* publisher.publish(output("b")); + const burst = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("1 millis"); + assert.isUndefined(burst.pollUnsafe()); + // Arrivals inside the window never push the deadline back. + yield* publisher.publish(output("c")); + yield* publisher.publish(output("d")); + yield* TestClock.adjust("1 millis"); + assert.deepEqual(yield* Fiber.join(burst), [output("b"), output("c"), output("d")]); }).pipe(Effect.scoped), ); - it.effect("caps each delivered batch at the output window in UTF-8 bytes", () => + it.effect("flushes pending output early, in order, when a lifecycle event arrives", () => + Effect.gen(function* () { + const publisher = makePublisher(); + const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, ""))); + assert.deepEqual(yield* pull, [snapshot("")]); + + yield* publisher.publish(output("last words")); + const waiting = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + assert.isUndefined(waiting.pollUnsafe()); + const closed: TerminalAttachStreamEvent = { + type: "closed", + threadId: "thread-1", + terminalId: "default", + }; + yield* publisher.publish(closed); + assert.deepEqual(yield* Fiber.join(waiting), [output("last words"), closed]); + }).pipe(Effect.scoped), + ); + + it.effect("flushes full batches early and caps each at the output window in UTF-8 bytes", () => Effect.gen(function* () { const publisher = makePublisher(); const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, ""))); @@ -317,8 +380,9 @@ describe("terminal output stream", () => { const data = "界".repeat(1024); for (let index = 0; index < 1024; index++) yield* publisher.publish(output(data)); + // Twenty 3 KiB events fill a 64 KiB batch, so full batches skip the deadline. let delivered = 0; - while (delivered < 1024) { + while (delivered < 1020) { const batch = yield* pull; assert.isAtMost( batch.reduce( @@ -329,8 +393,12 @@ describe("terminal output stream", () => { ); delivered += batch.length; } - assert.equal(delivered, 1024); - }).pipe(Effect.scoped), + assert.equal(delivered, 1020); + const tail = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + assert.isUndefined(tail.pollUnsafe()); + yield* TestClock.adjust("2 millis"); + assert.lengthOf(yield* Fiber.join(tail), 4); + }), ); it.effect("charges snapshot history but never overflows on one snapshot", () => @@ -348,6 +416,6 @@ describe("terminal output stream", () => { assert.equal(publisher.listeners.size, 1); yield* publisher.publish(snapshot(history)); assert.equal(publisher.listeners.size, 0); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.ts index 11339fc2bf..84f6e40923 100644 --- a/apps/server/src/terminal/OutputProtocol.ts +++ b/apps/server/src/terminal/OutputProtocol.ts @@ -6,6 +6,8 @@ import { } from "@t3tools/contracts"; import type * as Arr from "effect/Array"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Latch from "effect/Latch"; import * as Stream from "effect/Stream"; @@ -13,6 +15,8 @@ import type { RpcServer } from "effect/rpc"; const MAX_PENDING_CHUNKS = 8; const MAX_PENDING_BYTES = 64 * 1024; +// Charge an envelope so tiny events cannot bypass the byte budget. +const EVENT_OVERHEAD = 128; const isFull = (sizes: number[]) => sizes.length >= MAX_PENDING_CHUNKS || sizes.reduce((total, size) => total + size, 0) >= MAX_PENDING_BYTES; @@ -29,6 +33,36 @@ const COUNT_WINDOWED_STREAMS: ReadonlySet = new Set([ ORCHESTRATION_V2_WS_METHODS.subscribeThread, ]); +const byteLengthOf = (value: unknown) => (typeof value === "string" ? Buffer.byteLength(value) : 0); + +// Charges every variable-size field a terminal event can carry, so the byte +// budgets below cannot be bypassed by a large payload in an uncharged field. +const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) => + EVENT_OVERHEAD + + ("threadId" in event ? byteLengthOf(event.threadId) + byteLengthOf(event.terminalId) : 0) + + (event.type === "output" + ? byteLengthOf(event.data) + : event.type === "error" + ? byteLengthOf(event.message) + : event.type === "activity" + ? byteLengthOf(event.label) + : "snapshot" in event + ? byteLengthOf(event.snapshot.threadId) + + byteLengthOf(event.snapshot.terminalId) + + byteLengthOf(event.snapshot.history) + + byteLengthOf(event.snapshot.cwd) + + byteLengthOf(event.snapshot.worktreePath) + + byteLengthOf(event.snapshot.label) + : 0); + +// Byte-windowed streams carry TerminalAttachStreamEvent, whose encoded form is the +// event itself, so charge it like the output queue does instead of serializing twice. +const chunkSize = (values: ReadonlyArray) => + values.reduce( + (total, value) => total + queuedSize(value as TerminalAttachStreamEvent), + EVENT_OVERHEAD, + ); + interface Window { readonly bytes: boolean; readonly sizes: number[]; @@ -86,10 +120,7 @@ export function withOutputWindow( } else if (response._tag === "Chunk") { const window = windowFor(clientId, String(response.requestId)); if (window) { - window.sizes.push( - // @effect-diagnostics-next-line globalJsonInEffect:off - window.bytes ? Buffer.byteLength(JSON.stringify(response)) : 0, - ); + window.sizes.push(window.bytes ? chunkSize(response.values) : 0); if (!isFull(window.sizes)) { return send.pipe( Effect.andThen(() => @@ -108,8 +139,9 @@ export function withOutputWindow( } const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024; -// Charge an envelope so tiny events cannot bypass the byte budget. -const EVENT_OVERHEAD = 128; +// Output that follows an emission this closely waits and rides along in one batch, +// so a PTY that delivers one line per callback (ConPTY) is not sent one frame per line. +const OUTPUT_WINDOW_NANOS = 2_000_000n; type Listener = (event: A) => Effect.Effect; // Acquisition must register cleanup synchronously with installing the listener. @@ -118,14 +150,6 @@ type Subscribe = ( registerCleanup: (stop: () => void) => void, ) => Effect.Effect<() => void, E>; -const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) => - EVENT_OVERHEAD + - (event.type === "output" - ? Buffer.byteLength(event.data) - : "snapshot" in event - ? Buffer.byteLength(event.snapshot.history) - : 0); - export function terminalOutputStream( subscribe: Subscribe, resync?: Subscribe, @@ -133,11 +157,15 @@ export function terminalOutputStream { return Stream.unwrap( Effect.gen(function* () { + const clock = yield* Clock.Clock; const ready = yield* Latch.make(); let pending: Array = []; let sizes: number[] = []; let head = 0; let queued = 0; + // Pending events other than output; any of them flushes the window early. + let lifecycle = 0; + let deadline = 0n; let overflowed = false; let subscription = 0; let unsubscribe: (() => void) | null = null; @@ -149,7 +177,9 @@ export function terminalOutputStream lifecycle > 0 || queued >= MAX_PENDING_BYTES; yield* Effect.addFinalizer(() => Effect.sync(release)); const listen = (from: Subscribe) => @@ -159,16 +189,19 @@ export function terminalOutputStream Effect.sync(() => { if (id !== subscription) return; + const wasEmpty = head === pending.length; const size = queuedSize(event); pending.push(event); sizes.push(size); queued += size; + if (event.type !== "output") lifecycle += 1; // A single snapshot must fit even when history fills the budget. if (queued - sizes[head]! > maxQueued) { release(); overflowed = true; } - ready.openUnsafe(); + // The current or next pull handles the pending output deadline. + if (wasEmpty || overflowed || urgent()) ready.openUnsafe(); }), (stop) => { // Overflow or cancellation may invalidate acquisition before registration. @@ -185,6 +218,7 @@ export function terminalOutputStream => { @@ -209,9 +243,16 @@ export function terminalOutputStream= deadline || urgent()) { + deadline = now + OUTPUT_WINDOW_NANOS; + return Effect.succeed(takeBatch()); + } + return Effect.raceFirst(ready.await, Effect.sleep(Duration.nanos(deadline - now))).pipe( + Effect.andThen(pull), + ); }, ); diff --git a/apps/server/src/terminal/nodePtyFlushDataAndCleanUp.test.ts b/apps/server/src/terminal/nodePtyFlushDataAndCleanUp.test.ts new file mode 100644 index 0000000000..7dc0861c7f --- /dev/null +++ b/apps/server/src/terminal/nodePtyFlushDataAndCleanUp.test.ts @@ -0,0 +1,131 @@ +import * as NodeModule from "node:module"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +const requireCjs = NodeModule.createRequire(import.meta.url); +const { + WindowsPtyAgent, +}: { + WindowsPtyAgent: { + prototype: { + _flushDataAndCleanUp(this: FakeAgent): void; + _cleanUpProcess(this: FakeAgent): void; + }; + }; +} = requireCjs("node-pty/lib/windowsPtyAgent.js"); + +interface FakeAgent { + _useConptyDll: boolean; + _closeTimeout?: unknown; + _inSocket: { readable: boolean }; + _outSocket: { readable: boolean; destroy: () => void }; + _cleanUpProcess: () => void; +} + +// The sockets are stand-ins; the timer logic and _cleanUpProcess are node-pty's own (as patched by T3). +const makeAgent = (): FakeAgent => { + const agent: FakeAgent = { + _useConptyDll: false, + _inSocket: { readable: true }, + _outSocket: { readable: true, destroy: vi.fn() }, + _cleanUpProcess: () => WindowsPtyAgent.prototype._cleanUpProcess.call(agent), + }; + return agent; +}; + +const flush = (agent: FakeAgent) => WindowsPtyAgent.prototype._flushDataAndCleanUp.call(agent); + +// A minimal event loop that mirrors Node's phases: expired timers run first, then immediates (the check phase). +// node-pty calls the global timer functions at call time, so replacing them lets the test place a "poll phase" +// (delivery of already-buffered pipe data) exactly between the two. +interface Timer { + readonly id: number; + readonly dueAt: number; + readonly run: () => void; +} +let now = 0; +let nextId = 0; +let timers: Timer[] = []; +let immediates: Array<() => void> = []; + +const runExpiredTimers = () => { + for (const timer of timers.filter((t) => t.dueAt <= now).toSorted((a, b) => a.dueAt - b.dueAt)) { + timers = timers.filter((t) => t.id !== timer.id); + timer.run(); + } +}; +const runImmediates = () => { + const batch = immediates; + immediates = []; + for (const run of batch) run(); +}; +/** One loop iteration after `ms` of wall time; `poll` runs between the timers and check phases. */ +const loopIteration = (ms: number, poll?: () => void) => { + now += ms; + runExpiredTimers(); + poll?.(); + runImmediates(); +}; + +// ConPTY never closes the output pipe after the shell exits, so node-pty ends the session on a timer. +// T3 shortens it (patches/node-pty@1.2.0-beta.15.patch) so the terminal reports "exited" about 0.9 s sooner. +describe("node-pty Windows exit flush", () => { + beforeEach(() => { + now = 0; + nextId = 0; + timers = []; + immediates = []; + vi.stubGlobal("setTimeout", (run: () => void, ms: number) => { + const id = ++nextId; + timers.push({ id, dueAt: now + ms, run }); + return id; + }); + vi.stubGlobal("clearTimeout", (id: number) => { + timers = timers.filter((t) => t.id !== id); + }); + vi.stubGlobal("setImmediate", (run: () => void) => { + immediates.push(run); + return ++nextId; + }); + }); + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("closes the output socket 100 ms after the exit, not a second later", () => { + const agent = makeAgent(); + flush(agent); + + loopIteration(99); + expect(agent._outSocket.destroy).not.toHaveBeenCalled(); + + loopIteration(1); + expect(agent._outSocket.destroy).toHaveBeenCalledTimes(1); + expect(agent._outSocket.readable).toBe(false); + expect(agent._inSocket.readable).toBe(false); + }); + + // Timers run before the poll phase. After a main-thread stall longer than the window, output that is already + // buffered in the pipe is read only after the timer has expired, so the cleanup has to wait one loop turn for it. + it("keeps the socket open when buffered output is read right after a stalled timer expires", () => { + const agent = makeAgent(); + flush(agent); + + loopIteration(150, () => flush(agent)); + expect(agent._outSocket.destroy).not.toHaveBeenCalled(); + + loopIteration(99); + expect(agent._outSocket.destroy).not.toHaveBeenCalled(); + + loopIteration(1); + expect(agent._outSocket.destroy).toHaveBeenCalledTimes(1); + }); + + it("closes after a stall when no output was buffered", () => { + const agent = makeAgent(); + flush(agent); + + loopIteration(150); + expect(agent._outSocket.destroy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/server/src/testUtils/fakeWsl.ts b/apps/server/src/testUtils/fakeWsl.ts new file mode 100644 index 0000000000..d8f88fcde8 --- /dev/null +++ b/apps/server/src/testUtils/fakeWsl.ts @@ -0,0 +1,37 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +// `wslpath` honours the distro's configurable automount root, so the fake maps drives under a temp dir. +export const makeFakeWslHost = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const mountRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-wsl-mnt-" }); + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-wsl-bin-" }); + const wslpath = path.join(binDir, "wslpath"); + yield* fileSystem + .writeFileString( + wslpath, + [ + "#!/bin/sh", + '[ "$1" = "-u" ] || exit 1', + "p=$(printf '%s' \"$2\" | tr '\\\\' '/')", + "drive=$(printf '%s' \"$p\" | cut -c1 | tr 'A-Z' 'a-z')", + `printf '%s/%s%s\\n' '${mountRoot}' "$drive" "\${p#?:}"`, + "", + ].join("\n"), + ) + .pipe(Effect.orDie); + yield* fileSystem.chmod(wslpath, 0o755).pipe(Effect.orDie); + const environment = { + ...HostProcess.Environment.defaultValue(), + PATH: `${binDir}:${HostProcess.Environment.defaultValue().PATH ?? ""}`, + }; + const underWsl = (effect: Effect.Effect) => + effect.pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Environment, environment), + ); + return { mountRoot, underWsl }; +}); diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts index 5cb6a1f8d4..5a410dbf34 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts @@ -343,7 +343,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { { type: "text", text: expect.stringContaining("+handleRemoteCallback()") }, ]); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each(["tool_call", "tool_call_update"] as const)( @@ -362,7 +362,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toContain("tool work"); expect(fixture.state.cancellations).toBe(1); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("rejects native permission and choice requests instead of answering them", () => @@ -387,7 +387,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(reply).toEqual({ outcome: { outcome: "cancelled" } }); expect(error.detail).toContain("permission or user input"); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each(["file", "terminal", "extension"] as const)( @@ -416,7 +416,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { const error = yield* Fiber.join(child).pipe(Effect.flip); expect(error.detail).toContain("tool or user input"); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -432,7 +432,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { .pipe(Effect.flip); expect(error.detail).toContain(detail); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("does not return partial JSON after native cancellation", () => @@ -449,7 +449,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { .pipe(Effect.flip); expect(error.detail).toContain("cancelled"); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -470,7 +470,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toBe(detail); expect(error.detail).not.toContain("Raw provider failure text."); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -517,7 +517,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toContain("wrote files"); if (target !== undefined) expect(yield* fs.exists(target)).toBe(true); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("uses the native default without sending T3's default selection as a model ID", () => @@ -530,7 +530,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(result).toEqual({ title: "Repair login" }); expect(fixture.state.selectedModels).toEqual([]); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -549,6 +549,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { { name: "hooks.json", value: "{}", available: true }, { name: "hooks.json", value: '{"hooks":{}}', available: true }, { name: "mcp_config.json", value: '{"mcpServers":{}}', available: true }, + { name: "mcp_config.json", value: "", available: true }, ])("checks $name before starting a helper, available=$available", ({ name, value, available }) => Effect.gen(function* () { const fixture = yield* makeFixture(); @@ -562,7 +563,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(Exit.isSuccess(result)).toBe(available); expect(fixture.state.workspaces.length).toBe(available ? 1 : 0); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("does not launch during sign-out or before sign-in", () => @@ -575,7 +576,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toBe("Sign in before starting Antigravity."); expect(fixture.state.workspaces).toEqual([]); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each(["caller", "sign-out"] as const)( @@ -596,7 +597,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { } expect(fixture.state.cancellations).toBe(1); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("refuses unsafe native session IDs without deleting other files", () => @@ -609,7 +610,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(fixture.state.prompts).toEqual([]); expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.db`)).toBe("helper session"); expect(fixture.state.closed).toEqual(fixture.state.workspaces); - }).pipe(Effect.scoped), + }), ); it.effect("keeps native sessions whose metadata belongs to a different workspace", () => @@ -627,7 +628,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { "keep this session", ); expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.meta`)).toBe(metadata); - }).pipe(Effect.scoped), + }), ); }); @@ -640,5 +641,5 @@ it.effect("retains filesystem services supplied only during construction", () => title: "Repair login", }); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.ts index b7e7cfaeb4..b67bad85fa 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.ts @@ -79,14 +79,20 @@ export const isAntigravityTextGenerationAvailable = Effect.fn( if (info.type !== "File" || info.size > 64_000n) { return false; } + // CLI 1.5.8 writes a 0-byte mcp_config.json before any server exists. const empty = yield* fs.readFileString(configurationPath).pipe( - Effect.flatMap(decodeConfiguration), - Effect.flatMap((configuration) => - decodeConfigurationObject( - configuration[name === "hooks.json" ? "hooks" : "mcpServers"] ?? configuration, - ), + Effect.flatMap((text) => + text.trim().length === 0 + ? Effect.succeed(true) + : decodeConfiguration(text).pipe( + Effect.flatMap((configuration) => + decodeConfigurationObject( + configuration[name === "hooks.json" ? "hooks" : "mcpServers"] ?? configuration, + ), + ), + Effect.map((configuration) => Object.keys(configuration).length === 0), + ), ), - Effect.map((configuration) => Object.keys(configuration).length === 0), Effect.orElseSucceed(() => false), ); if (!empty) return false; diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index a7041d5d24..84b7a9151e 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -188,7 +188,7 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { withFakeClaudeEnv( { output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }), - stdinMustContain: "Additional instructions:\nUse two to four words.", + stdinMustContain: "Title instructions from the user:\nUse two to four words.", }, (textGeneration) => textGeneration.generateThreadTitle({ @@ -234,6 +234,35 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { }), ); + it.effect("passes --settings from the instance launch args to Claude text generation", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: "Use instance settings", + }, + }), + argsMustContain: `"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}`, + claudeConfig: { + launchArgs: `--settings '{"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}}'`, + }, + }, + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "thread title", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: SYNTHETIC_CLAUDE_STANDARD_MODEL, + }, + }); + + expect(generated.title).toBe(sanitizeThreadTitle("Use instance settings")); + }), + ), + ); + it.effect("retries without --no-session-persistence when the Claude CLI rejects it", () => withFakeClaudeEnv( { diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 34e7415b3c..a523a3873a 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -1,7 +1,9 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -32,6 +34,7 @@ import { hasClaudeManagedMcpConfig, makeClaudeEnvironment, } from "../provider/Drivers/ClaudeHome.ts"; +import { readClaudeLaunchArgSettings } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; const CLAUDE_TIMEOUT_MS = 180_000; /** `--tools` takes bare names; patterns go in the allow list. */ @@ -97,9 +100,14 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu claudeSettings: ClaudeSettings, environment?: NodeJS.ProcessEnv, modelCatalog: Effect.Effect = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG), + routeModelCatalog: ( + catalog: ClaudeModelCatalog, + cwd: string, + ) => Effect.Effect = Effect.succeed, ) { const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); const scopedModelCatalog = modelCatalog.pipe( Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)), @@ -146,9 +154,19 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu }: TextGenerationOperations.Request): Effect.fn.Return< S["Type"], TextGenerationError, - S["DecodingServices"] + S["DecodingServices"] | Scope.Scope > { - const catalog = yield* scopedModelCatalog; + const workingDirectory = + operation === "generateThreadTitle" + ? yield* fileSystem + .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" }) + .pipe( + Effect.mapError((cause) => + normalizeCliError("claude", operation, cause, "Failed to create title directory"), + ), + ) + : cwd; + const catalog = yield* routeModelCatalog(yield* scopedModelCatalog, workingDirectory); const resolvedModelSelection = { ...modelSelection, model: resolveClaudeModelSlug(catalog, modelSelection.model), @@ -185,7 +203,18 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu : undefined; const fastMode = fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined; + const launchArgSettings = yield* readClaudeLaunchArgSettings({ + settings: claudeSettings, + cwd, + fileSystem, + path, + }).pipe( + Effect.mapError( + (cause) => new TextGenerationError({ operation, detail: cause.message, cause }), + ), + ); const settings = { + ...launchArgSettings, disableAllHooks: true, ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), ...(fastMode ? { fastMode: true } : {}), @@ -200,16 +229,6 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* ( noSessionPersistence: boolean, ) { - const workingDirectory = - operation === "generateThreadTitle" - ? yield* fileSystem - .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" }) - .pipe( - Effect.mapError((cause) => - normalizeCliError("claude", operation, cause, "Failed to create title directory"), - ), - ) - : cwd; const managedMcpConfig = yield* hasClaudeManagedMcpConfig(); const spawnCommand = yield* resolveSpawnCommand( claudeSettings.binaryPath || "claude", @@ -344,5 +363,9 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu ); }); - return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson); + return TextGenerationOperations.fromRunner( + "ClaudeTextGeneration", + (request: TextGenerationOperations.Request) => + Effect.scoped(runClaudeJson(request)), + ); }); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 86c6cb9a8c..1a1a5c43b0 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -1,11 +1,11 @@ import { - DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, ProjectId, ProviderDriverKind, type ModelSelection, type ServerProvider, } from "@t3tools/contracts"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; +import * as ProviderInstallationGate from "../provider/ProviderInstallationGate.ts"; import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; @@ -58,6 +58,7 @@ interface FakeCodexInput { mcpServers?: ReadonlyArray<{ name: string; enabled: boolean }> | number; requiredCwd?: string; requireInstructions?: string; + requireMcpServersOff?: ReadonlyArray; } function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { @@ -73,6 +74,7 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { mcpServers: input.mcpServers ?? [], requiredCwd: input.requiredCwd ?? null, requireInstructions: input.requireInstructions ?? null, + requireMcpServersOff: input.requireMcpServersOff ?? [], stderr: input.stderr ?? null, output: input.output, exitCode: input.exitCode ?? 0, @@ -129,6 +131,33 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { ' process.stderr.write(message + "\\n");', " process.exit(code);", "}", + "// Like Codex: a later mcp_servers={...} override replaces servers earlier -c flags defined.", + "const servers = new Map();", + "const offServers = new Set();", + "for (let index = 0; index < args.length; index += 1) {", + ' if (args[index] !== "-c" && args[index] !== "--config") continue;', + ' const value = args[index + 1] ?? "";', + ' if (value.startsWith("mcp_servers={")) {', + ' const named = [...value.matchAll(/"([^"]+)"=\\{enabled=false\\}/g)].map((match) => match[1]);', + " for (const name of named) offServers.add(name);", + " for (const name of [...servers.keys()]) {", + " if (named.includes(name)) servers.set(name, false);", + " else servers.delete(name);", + " }", + ' } else if (value.startsWith("mcp_servers.")) {', + ' const [name, key] = value.slice("mcp_servers.".length).split(/[.=]/);', + " if (value === `mcp_servers.${name}.enabled=false`) offServers.add(name);", + " // An enabled flag alone toggles a server another layer (config.toml) defines.", + ' if (key === "enabled" && !servers.has(name)) continue;', + ' servers.set(name, servers.get(name) === true || key === "url" || key === "command");', + " }", + "}", + "for (const [name, hasTransport] of servers) {", + ' if (!hasTransport) fail("Error loading config.toml: invalid transport in `mcp_servers." + name + "`", 12);', + "}", + "for (const name of check.requireMcpServersOff) {", + ' if (!offServers.has(name)) fail("MCP server left on: " + name, 13);', + "}", 'if (check.requiredCwd !== null && process.cwd() !== check.requiredCwd) fail("cannot inspect checkout", 10);', 'if (check.requireInstructions !== null && !instructions.includes(check.requireInstructions)) fail("missing writer task", 11);', "if (check.requireArg !== null && !originalArgs.includes(` ${check.requireArg} `)) {", @@ -365,7 +394,7 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { { name: "already-off", enabled: false }, ], requireArg: - '--config features.plugins=false --config features.apps=false --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}}', + 'exec --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}} --config developer_instructions="Use', }, (textGeneration) => Effect.gen(function* () { @@ -384,6 +413,52 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); + it.effect("turns off an MCP server that launch args define without dropping its transport", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Remove default shapes" }), + launchArgs: `-c 'mcp_servers.t3-code.url="http://127.0.0.1:1/mcp"' -c 'mcp_servers.t3-code.enabled=true'`, + mcpServers: [{ name: "t3-code", enabled: true }], + requireMcpServersOff: ["t3-code"], + requireArg: + "--config features.apps=false --config mcp_servers.t3-code.enabled=false --ephemeral", + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Remove default shapes from characters", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Remove default shapes"); + }), + ), + ); + + it.effect("keeps MCP servers off when launch args set their own mcp_servers table", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Remove default shapes" }), + launchArgs: `-c 'mcp_servers={"my.server"={command="echo",enabled=true}}'`, + mcpServers: [ + { name: "my.server", enabled: true }, + { name: "my server", enabled: true }, + ], + requireArg: + '--config features.apps=false --config mcp_servers={"my.server"={enabled=false},"my server"={enabled=false}} --config mcp_servers.my server.enabled=false --ephemeral', + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Remove default shapes from characters", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Remove default shapes"); + }), + ), + ); + it.effect("still generates when Codex cannot list its MCP servers", () => withFakeCodexEnv( { @@ -424,6 +499,26 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); + it.effect("keeps user hooks off over launch args that turn them on", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Hookless title" }), + launchArgs: "--config features.hooks=true --enable hooks", + requireArg: "--config features.codex_hooks=false --config features.hooks=false", + forbidArg: "--enable", + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Describe this change", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Hookless title"); + }), + ), + ); + it.effect("passes exec-safe launch args into codex exec", () => withFakeCodexEnv( { @@ -431,8 +526,8 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { subject: "Add important change", body: "", }), - launchArgs: "--strict-config --listen off", - requireArg: "--strict-config", + launchArgs: "--strict-config --oss --local-provider ollama --listen off", + requireArg: "--strict-config --oss --local-provider ollama", forbidArg: "--listen", }, (textGeneration) => @@ -546,6 +641,8 @@ const PREFLIGHT_PRIMARY_STATES = [ "not installed, fallback disabled for project", "signed out", "signed out, fallback failed", + "cannot generate text", + "model cannot generate text", ] as const; it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (primaryState) => @@ -558,6 +655,11 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima model: "chat-model", options: [{ id: "effort", value: "high" }], }; + const threadDefault = { + instanceId: fallback, + model: "z-ai/glm-5.3-flash", + options: [{ id: "thinking", value: false }], + }; const calls: ModelSelection[] = []; const instances: ProviderInstance[] = [primary, fallback].map((instanceId) => { const driver = ProviderDriverKind.make(instanceId === primary ? "codex" : "claudeAgent"); @@ -585,6 +687,22 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima ...(primaryState === "signed out, fallback failed" && instanceId === fallback ? { status: "error", auth: { status: "unknown" } } : {}), + ...(primaryState === "cannot generate text" && instanceId === primary + ? { supportsTextGeneration: false } + : {}), + ...(primaryState === "model cannot generate text" && instanceId === primary + ? { + models: [ + { + slug: selection.model, + name: selection.model, + isCustom: false, + supportsTextGeneration: false, + capabilities: null, + }, + ], + } + : {}), ...(primaryState === "exhausted" && instanceId === primary ? { usageLimits: { @@ -626,8 +744,12 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima }), ServerSettings.layerTest({ providerInstances: { - [fallback]: { driver: ProviderDriverKind.make("claudeAgent"), config: {} }, + [fallback]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { customModels: [threadDefault.model] }, + }, }, + defaultModelSelection: threadDefault, ...(primaryState === "not installed, fallback disabled for project" ? { projectSettingsOverrides: { @@ -640,6 +762,7 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ resolveLink: () => Effect.die("unused"), }), + ProviderInstallationGate.layer, ), ), ); @@ -658,11 +781,7 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima primaryState === "not installed, fallback disabled for project" || primaryState === "signed out, fallback failed" ? selection - : { - instanceId: fallback, - model: - DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[ProviderDriverKind.make("claudeAgent")], - }, + : threadDefault, ]); }), ); @@ -730,6 +849,7 @@ it.effect( Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ resolveLink: () => Effect.die("unused"), }), + ProviderInstallationGate.layer, ), ), ); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index cbf095b303..fc741aaaeb 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -18,7 +18,11 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { resolveAttachmentPath } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; -import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/codexLaunchArgs.ts"; +import { + codexExecLaunchArgs, + codexMcpListLaunchArgs, + resolveCodexLaunchArgs, +} from "../provider/codexLaunchArgs.ts"; import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations"; import { normalizeCliError, @@ -51,6 +55,11 @@ const codexMcpServersOff = (names: ReadonlyArray): string | null => names.length === 0 ? null : `mcp_servers={${names.map((name) => `${JSON.stringify(name)}={enabled=false}`).join(",")}}`; +// Codex splits -c keys at the first "=" and on every dot, so only those names take a dotted flag. +const codexMcpServerOffFlags = (names: ReadonlyArray) => + names + .filter((name) => !name.includes(".") && !name.includes("=")) + .flatMap((name) => ["--config", `mcp_servers.${name}.enabled=false`]); const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* ( codexConfig: CodexSettings, @@ -287,22 +296,28 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func } : {}), }; - const execLaunchArgs = codexExecLaunchArgs(launchArgs); - const mcpServersOff = yield* listEnabledMcpServers({ + const enabledMcpServers = yield* listEnabledMcpServers({ binary, cwd, env, - // `codex mcp` rejects --strict-config; the overrides still apply. - launchArgs: execLaunchArgs.filter((arg) => arg !== "--strict-config"), - }).pipe(Effect.map(codexMcpServersOff)); + launchArgs: codexMcpListLaunchArgs(launchArgs), + }); + const mcpServersOff = codexMcpServersOff(enabledMcpServers); + const execLaunchArgs = codexExecLaunchArgs(launchArgs); + // A launch-arg mcp_servers={...} table replaces ours and can re-enable dotted names. + const launchArgsSetMcpTable = execLaunchArgs.some((arg) => /\bmcp_servers\s*=/.test(arg)); const spawnCommand = yield* resolveSpawnCommand( binary, [ "exec", + // Before launch args: a later table would replace servers their -c flags define. + ...(mcpServersOff ? ["--config", mcpServersOff] : []), ...execLaunchArgs, // A user's MCP server could act on the text-generation prompt. ...CODEX_NO_PLUGIN_ARGS, - ...(mcpServersOff ? ["--config", mcpServersOff] : []), + ...(mcpServersOff && launchArgsSetMcpTable ? ["--config", mcpServersOff] : []), + // After launch args, so a launch arg's enabled=true cannot turn a server back on. + ...codexMcpServerOffFlags(enabledMcpServers), "--ephemeral", "--skip-git-repo-check", "-s", @@ -311,6 +326,11 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func model, "--config", `model_reasoning_effort="${reasoningEffort}"`, + // Current Codex gives hooks precedence over the historical codex_hooks alias. + "--config", + "features.codex_hooks=false", + "--config", + "features.hooks=false", ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []), "--output-schema", schemaPath, diff --git a/apps/server/src/textGeneration/GrokTextGeneration.test.ts b/apps/server/src/textGeneration/GrokTextGeneration.test.ts index 26ab9e79c7..adb911623f 100644 --- a/apps/server/src/textGeneration/GrokTextGeneration.test.ts +++ b/apps/server/src/textGeneration/GrokTextGeneration.test.ts @@ -35,7 +35,7 @@ function makeAcpGrokWrapper(dir: string, env: Record): string { env, source: execScriptSource({ scriptPath: mockAgentPath, - expectedArgs: ["agent", "stdio"], + expectedArgs: ["--permission-mode", "default", "agent", "stdio"], }), }); } @@ -58,14 +58,19 @@ function withFakeAcpGrok( }).pipe(Effect.scoped); } -function readJsonRpcRequests( - filePath: string, -): ReadonlyArray<{ readonly method?: string; readonly params?: Record }> { +function readJsonRpcRequests(filePath: string): ReadonlyArray<{ + readonly id?: unknown; + readonly method?: string; + readonly params?: Record; +}> { return NodeFS.readFileSync(filePath, "utf8") .trim() .split("\n") .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as { method?: string; params?: Record }); + .map( + (line) => + JSON.parse(line) as { id?: unknown; method?: string; params?: Record }, + ); } it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => { @@ -78,6 +83,7 @@ it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => { return withFakeAcpGrok( { T3_ACP_REQUEST_LOG_PATH: requestLogPath, + T3_ACP_REQUEST_PERMISSION: "1", T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ subject: "Add Grok provider", body: "Wire up the ACP runtime and headless text generation path.", @@ -110,6 +116,9 @@ it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => { request.params?.modelId === "grok-mock-alt", ), ).toBe(true); + expect(requests.find((request) => request.id === 9001)).toMatchObject({ + result: { outcome: { outcome: "cancelled" } }, + }); }), ); }); diff --git a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts index 869cd1b4fb..6cb1bfad71 100644 --- a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts +++ b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts @@ -70,7 +70,7 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { files: [{ uri: NodeURL.pathToFileURL(screenshotPath).href, name: "screen.png" }], }); } - }).pipe(Effect.scoped), + }), ); it.effect("keeps a provider's own error message out of the caller-visible detail", () => @@ -153,7 +153,7 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { .pipe(Effect.flip); assert.equal(failure.detail, "OpenCode could not generate the text."); assert.deepEqual(failure.cause, refusal); - }).pipe(Effect.scoped), + }), ); it.effect("times out when the prompt request and its interrupt never answer", () => @@ -219,6 +219,6 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { yield* TestClock.adjust("5 seconds"); const failure = yield* Fiber.join(generation); assert.equal(failure.detail, "OpenCode did not finish generating in time."); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index 612d473071..818afb4fae 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -9,14 +9,12 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { exhaustedUsageWindow } from "@t3tools/shared/usageLimits"; -import { - defaultTextGenerationModel, - fallbackTextGenerationModelSelection, -} from "@t3tools/shared/serverSettings"; +import { fallbackTextGenerationModelSelection } from "@t3tools/shared/serverSettings"; import * as ServerSettings from "../serverSettings.ts"; import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; import { TextGenerationError } from "@t3tools/contracts"; +import * as ProviderInstallationGate from "../provider/ProviderInstallationGate.ts"; import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; @@ -77,6 +75,7 @@ export const make = Effect.gen(function* () { const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; const sourceControl = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; const serverSettings = yield* ServerSettings.ServerSettingsService; + const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate; const textGenerators = yield* TextGenerators.TextGenerators; const generate = Effect.fn("TextGeneration.generate")(function* ( operation: TextGenerationOp, @@ -109,8 +108,11 @@ export const make = Effect.gen(function* () { const unusable = textGeneratorCannotRun || (selected?.enabled === true && - selected.status === "error" && - (!selected.installed || selected.auth.status === "unauthenticated")); + (!isProviderTextGenerationCapable(selected) || + selected.models.find((model) => model.slug === selection.model) + ?.supportsTextGeneration === false || + (selected.status === "error" && + (!selected.installed || selected.auth.status === "unauthenticated")))); if (unusable || exhaustedUsageWindow(selected, now, selection.model)) { const settings = yield* serverSettings.getSettings.pipe( Effect.mapError( @@ -125,7 +127,7 @@ export const make = Effect.gen(function* () { selection = fallbackTextGenerationModelSelection( settings.providerInstances, - (instanceId, driver) => { + (instanceId, driver, model) => { const provider = snapshots.find((candidate) => candidate.instanceId === instanceId); return ( instanceId !== selection.instanceId && @@ -137,10 +139,10 @@ export const make = Effect.gen(function* () { isProviderAvailable(provider) && isProviderTextGenerationCapable(provider) && (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) && - !exhaustedUsageWindow(provider, now, defaultTextGenerationModel(driver)) + !exhaustedUsageWindow(provider, now, model) ); }, - { includeConfiguredInstances: true }, + { defaultModelSelection: settings.defaultModelSelection }, ) ?? selection; } if (textGeneratorCannotRun && selection.instanceId === textGeneratorId) { @@ -150,8 +152,11 @@ export const make = Effect.gen(function* () { "Review guides need a coding agent that can read the checkout. None is ready. Pick Codex or Claude as the review guide model in Settings → Source control.", }); } - return yield* resolveInstance(registry, operation, selection.instanceId).pipe( - Effect.flatMap((service) => invoke(service, selection)), + return yield* installationGate.execute( + selection.instanceId, + resolveInstance(registry, operation, selection.instanceId).pipe( + Effect.flatMap((service) => invoke(service, selection)), + ), ); }); return TextGeneration.of({ diff --git a/apps/server/src/textGeneration/TextGenerationPresets.ts b/apps/server/src/textGeneration/TextGenerationPresets.ts index b53ecc5435..2dd3b95321 100644 --- a/apps/server/src/textGeneration/TextGenerationPresets.ts +++ b/apps/server/src/textGeneration/TextGenerationPresets.ts @@ -3,7 +3,7 @@ import type { TextGenerationPolicy } from "@t3tools/provider-core/server/textGen export const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = { kind: "conventional_commits", commitInstructions: - "Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff.", + "Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff. Start the description after the colon with a lowercase word, never a proper noun or acronym, because commitlint rejects a capitalized description.", changeRequestInstructions: "Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.", inferRepositoryConventions: false, diff --git a/apps/server/src/usage/UsageLimitSources.test.ts b/apps/server/src/usage/UsageLimitSources.test.ts index 274e63b46c..fc8a93f9e1 100644 --- a/apps/server/src/usage/UsageLimitSources.test.ts +++ b/apps/server/src/usage/UsageLimitSources.test.ts @@ -1,11 +1,21 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { expect, it } from "@effect/vitest"; -import { SecretProviderId, ServerConfigStreamEvent, UsageLimitSourceId } from "@t3tools/contracts"; +import { + ProviderDriverKind, + SecretProviderId, + ServerConfigStreamEvent, + UsageLimitSourceId, + type ServerProviderUsageWindow, + type UsageLimitSourceSnapshot, +} from "@t3tools/contracts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; @@ -26,6 +36,15 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () => "hub.test:8317", "Usage limit source", ]); + // Only an http(s) hub URL names an endpoint an agent can be sent to. + expect(snapshots.map((source) => source.origin)).toEqual([ + undefined, + undefined, + undefined, + "https://hub.test:8317", + undefined, + ]); + expect(snapshots[3]?.endpoint).toBe("https://hub.test:8317/team-a"); expect(() => encodeConfigEvent({ version: 1, @@ -66,7 +85,7 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () => }, [UsageLimitSourceId.make("valid-hub")]: { kind: "cliproxy", - url: "https://hub.test:8317", + url: "https://hub.test:8317/team-a/management.html", managementKey: "", enabled: true, }, @@ -87,7 +106,6 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () => ), NodeCrypto.layer, ]), - Effect.scoped, ), ); @@ -154,6 +172,137 @@ it.effect("reads a management key from its secret provider", () => { ), NodeCrypto.layer, ]), - Effect.scoped, ); }); + +const NOW = Date.parse("2026-11-13T12:00:00.000Z"); +const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000)); +const spent = (id: string, hours: number): ServerProviderUsageWindow => ({ + id, + kind: "weekly", + label: id, + usedPercent: 100, + resetsAt: at(hours), +}); +const hub = ( + accounts: ReadonlyArray<{ + driver?: string; + windows?: ReadonlyArray; + unavailable?: true; + }>, +): UsageLimitSourceSnapshot => ({ + id: UsageLimitSourceId.make("hub"), + kind: "cliproxy", + label: "hub", + checkedAt: at(0), + accounts: accounts.map((account, index) => ({ + id: `account-${index}`, + driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"), + usageLimits: { + checkedAt: at(0), + windows: account.windows ?? [], + ...(account.unavailable ? { unavailable: { reason: "probeFailed" as const } } : {}), + }, + })), +}); + +it.each([ + { + name: "earliest refill when every account is spent, each at its latest spent window", + accounts: [ + { windows: [spent("five_hour", 1), spent("seven_day", 3)] }, + { windows: [spent("five_hour", 2)] }, + { driver: "codex", windows: [] }, + ], + model: "claude-haiku-5-5", + expected: at(2), + }, + { + name: "unknown while an account still has room", + accounts: [{ windows: [spent("five_hour", 1)] }, { windows: [] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "unknown while an account could not be read", + accounts: [{ windows: [spent("five_hour", 1)] }, { unavailable: true as const }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "unknown when a spent window has no reset or already reset", + accounts: [{ windows: [{ ...spent("five_hour", 1), resetsAt: undefined }] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "a model-scoped weekly window blocks only its own model", + accounts: [{ windows: [spent("seven_day_fable", 5)] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "a model-scoped weekly window blocks its own model", + accounts: [{ windows: [spent("seven_day_fable", 5)] }], + model: "claude-fable-5-2", + expected: at(5), + }, + { + name: "no account of the driver", + accounts: [{ driver: "codex", windows: [spent("five_hour", 1)] }], + model: "claude-haiku-5-5", + expected: null, + }, +])("hub pool reset: $name", ({ accounts, model, expected }) => { + expect( + UsageLimitSources.hubPoolResetAt( + [hub(accounts)], + ProviderDriverKind.make("claudeAgent"), + model, + NOW, + ), + ).toBe(expected); +}); + +it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold the failure", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const roomLeft = { ...hub([{ windows: [spent("five_hour", 2)] }]), origin: "http://hub.test" }; + const cached = { + ...roomLeft, + accounts: roomLeft.accounts.map((account) => ({ + ...account, + usageLimits: { + ...account.usageLimits, + windows: account.usageLimits.windows.map((window) => ({ ...window, usedPercent: 99 })), + }, + })), + }; + let current: ReadonlyArray = [cached]; + let refresh: Effect.Effect = Effect.sync(() => { + current = [roomLeft]; + }); + const lookup = UsageLimitSources.UsageLimitResetFallback.pipe( + Effect.flatMap((fallback) => + fallback.resetAt(ProviderDriverKind.make("claudeAgent"), "http://hub.test", null), + ), + Effect.provide( + UsageLimitSources.layerResetFallback.pipe( + Layer.provide( + Layer.mock(UsageLimitSources.UsageLimitSources)({ + current: Effect.sync(() => current), + refresh: Effect.suspend(() => refresh), + }), + ), + ), + ), + ); + // The last poll saw room; the account was spent after it. + expect(yield* lookup).toBe(at(2)); + current = [cached]; + refresh = Effect.never; + const stalled = yield* Effect.forkChild(lookup); + yield* TestClock.adjust("5 seconds"); + expect(yield* Fiber.join(stalled)).toBeNull(); + }), +); diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index 7d40b0fb9e..d6f867d621 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -3,6 +3,7 @@ import { UsageLimitSourceError, type UsageLimitSourceConsumeResetCreditInput, type ProviderConsumeResetCreditResult, + type ProviderDriverKind, type ServerSettings, UsageLimitSourceConfig, settingsSecretLiteral, @@ -26,6 +27,7 @@ import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretReso import * as SecretResolverLayer from "../secrets/SecretResolver.ts"; import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts"; import * as Settings from "../serverSettings.ts"; +import { windowLimitsModel } from "../provider/claudeUsageLimits.ts"; import { makeCliproxyApi } from "./cliproxyApi.ts"; export class UsageLimitSources extends Context.Service< @@ -79,7 +81,19 @@ export const make = Effect.gen(function* () { config: UsageLimitSourceConfig, ) { const checkedAt = DateTime.formatIso(yield* DateTime.now); - const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const; + const url = URL.parse(config.url); + const base = { + id, + kind: config.kind, + label: sourceLabel(id, config), + ...(url && /^https?:$/.test(url.protocol) + ? { + origin: url.origin, + endpoint: `${url.origin}${url.pathname.replace(/(\/management\.html)?\/*$/i, "")}`, + } + : {}), + checkedAt, + } as const; const managementKey = yield* readManagementKey(config); if (managementKey.length === 0) { return { ...base, accounts: [], error: missingManagementKey(config) }; @@ -198,3 +212,64 @@ export const make = Effect.gen(function* () { export const layer = Layer.effect(UsageLimitSources, make).pipe( Layer.provide(SecretResolverLayer.layer), ); + +/** A hub answers with a usage limit only when every account it routes the driver to is spent. */ +export function hubPoolResetAt( + sources: ReadonlyArray, + driver: ProviderDriverKind, + model: string | null, + now: number, +): string | null { + let earliest: number | null = null; + for (const source of sources) { + for (const account of source.accounts) { + if (account.driver !== driver) continue; + // An unread account may be the one still blocked, so its refill is unknown. + if (account.usageLimits.unavailable) return null; + const spent = account.usageLimits.windows.filter( + (window) => window.usedPercent >= 100 && windowLimitsModel(window, model), + ); + if (spent.length === 0) return null; + const resets = spent.map((window) => Date.parse(window.resetsAt ?? "")); + if (resets.some((reset) => !Number.isFinite(reset))) return null; + const recoversAt = Math.max(...resets); + if (recoversAt <= now) return null; + earliest = earliest === null ? recoversAt : Math.min(earliest, recoversAt); + } + } + return earliest === null ? null : DateTime.formatIso(DateTime.makeUnsafe(earliest)); +} + +export class UsageLimitResetFallback extends Context.Reference<{ + readonly resetAt: ( + driver: ProviderDriverKind, + endpoint: string, + model: string | null, + ) => Effect.Effect; +}>("t3/usage/UsageLimitResetFallback", { + defaultValue: () => ({ resetAt: () => Effect.succeed(null) }), +}) {} + +export const layerResetFallback = Layer.effect( + UsageLimitResetFallback, + Effect.gen(function* () { + const sources = yield* UsageLimitSources; + return { + resetAt: Effect.fn("UsageLimitResetFallback.resetAt")(function* (driver, endpoint, model) { + // Only the hub at the instance's endpoint serves its turns. + const atEndpoint = Effect.map(sources.current, (current) => + current.filter((source) => source.origin === endpoint), + ); + if ((yield* atEndpoint).length === 0) return null; + // The pool usually ran out after the last poll, so the cached accounts still show room. + yield* sources.refresh.pipe(Effect.timeout("5 seconds"), Effect.ignore); + return hubPoolResetAt( + yield* atEndpoint, + driver, + model, + DateTime.toEpochMillis(yield* DateTime.now), + ); + }), + }; + }), +); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index c338b574c6..8335c7fe00 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -12,6 +12,7 @@ import { vi } from "vite-plus/test"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import { mergeUsage } from "@t3tools/shared/usageMerge"; import { EnvironmentId, @@ -50,6 +51,7 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts"; import * as ProviderHostLive from "../provider/ProviderHostLive.ts"; import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage"; import * as UsageService from "./UsageService.ts"; +import { DESKTOP_HOST_SCOPE_ENV, physicalSourceIdOf } from "./usageTranscriptReader.ts"; import * as MuseSdk from "../../../../packages/provider-muse/src/server/sdk.ts"; import { MuseUsageHome } from "@t3tools/provider-muse/server"; import { makeScanCacheWriter, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts"; @@ -93,6 +95,42 @@ function claudeLine( })}\n`; } +/** One content-block line of message `msg_1`; Claude Code writes several per message. */ +function claudeCopy(usage: Readonly>): string { + return `${JSON.stringify({ + type: "assistant", + timestamp: "2026-08-01T10:00:00Z", + requestId: "req_1", + sessionId: "session-1", + message: { id: "msg_1", model: "claude-fable-5", usage }, + })}\n`; +} + +// A subagent message: its stream-start copy, then its final copy. +const PARTIAL_USAGE = { + input_tokens: 2, + cache_creation_input_tokens: 1097, + cache_read_input_tokens: 67934, + output_tokens: 3, +}; +const COMPLETE_USAGE = { ...PARTIAL_USAGE, output_tokens: 264 }; +const COPY_RATES = { + "claude-fable-5": { + input_cost_per_token: 1e-5, + output_cost_per_token: 5e-5, + cache_read_input_token_cost: 1e-6, + cache_creation_input_token_cost: 1.25e-5, + }, +}; +const COMPLETE_COST_USD = 2 * 1e-5 + 67934 * 1e-6 + 1097 * 1.25e-5 + 264 * 5e-5; +const COMPLETE_TOTALS = { + uncachedInputTokens: 2, + cachedInputTokens: 67934, + cacheCreationTokens: 1097, + outputTokens: 264, + reasoningTokens: 0, +}; + const WINDOW: UsageSummaryInput = { timeZone: "UTC", sinceDay: UsageDay.make("2026-07-31"), @@ -176,6 +214,7 @@ const layerService = (input: { Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(Layer.succeed(HostProcess.Platform, input.platform ?? "linux")), Layer.provideMerge(Layer.succeed(HostProcess.Hostname, input.hostname ?? "usage-test-host")), + Layer.provideMerge(Layer.succeed(HostProcess.HomeDirectory, input.home)), Layer.provideMerge(ServerSettings.layerTest(input.settings)), Layer.provideMerge( Layer.succeed( @@ -212,6 +251,7 @@ const layerService = (input: { ); const BEFORE_NARROW_WINDOW = Date.parse("2026-08-01T10:00:00Z") / 1000; +const NARROW_WINDOW_MTIME = Date.parse("2026-09-01T10:00:00Z") / 1000; const NARROW_WINDOW: UsageSummaryInput = { timeZone: "UTC", sinceDay: UsageDay.make("2026-09-01"), @@ -483,7 +523,74 @@ describe("Codex usage history", () => { }); describe("UsageService", () => { - it.live("counts compressed Codex rollouts across refresh, rewrites, and cache restarts", () => + it.effect("keeps pricing metadata paired with the rates used during a concurrent refresh", () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const sessions = NodePath.join(home, "codex", "sessions"); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(sessions, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(sessions, "session.jsonl"), + [ + { type: "session_meta", payload: { id: "session", model_provider: "openai" } }, + { type: "turn_context", payload: { model: "gpt-6-astra", turn_id: "turn" } }, + { + type: "event_msg", + timestamp: "2026-08-01T10:00:00Z", + payload: { + type: "token_count", + info: { last_token_usage: { input_tokens: 0, output_tokens: 1 } }, + }, + }, + ] + .map((record) => encodeUnknownJsonString(record)) + .join("\n") + "\n", + ); + }); + let rate = 0; + yield* Effect.gen(function* () { + const resolving = yield* Deferred.make(); + const release = yield* Deferred.make(); + const service = yield* UsageService.make.pipe( + Effect.provideService(CodexUsageHistory.CodexUsageHistory, { + resolve: () => + Deferred.succeed(resolving, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as(new Map()), + ), + }), + ); + const initialPricing = yield* service.refreshRates; + yield* TestClock.adjust(61_000); + const pending = yield* service.readSummary(WINDOW).pipe(Effect.forkChild); + yield* Deferred.await(resolving); + yield* service.refreshRates; + yield* Deferred.succeed(release, undefined); + const original = yield* Fiber.join(pending); + assert.strictEqual(original.buckets[0]?.costUsd, 1); + assert.strictEqual(original.pricing.fetchedAt, initialPricing.fetchedAt); + const updated = yield* service.readSummary(WINDOW); + assert.strictEqual(updated.buckets[0]?.costUsd, 2); + assert.notStrictEqual(updated.pricing.fetchedAt, initialPricing.fetchedAt); + }).pipe( + Effect.provide( + layerService({ + prefix: "concurrent-rates", + home, + settings, + ratesResponse: () => + Effect.succeed( + Response.json({ + "gpt-6-astra": { input_cost_per_token: 0, output_cost_per_token: ++rate }, + }), + ), + }), + ), + ); + }).pipe(Effect.scoped), + ); + + it.effect("counts compressed Codex rollouts across refresh, rewrites, and cache restarts", () => Effect.gen(function* () { const { home, settings } = yield* setup; const sessions = NodePath.join(home, "codex", "sessions"); @@ -540,17 +647,63 @@ describe("UsageService", () => { assert.strictEqual(totalOutputTokens(rewritten), 71); assert.deepStrictEqual((yield* service.readSummary(WINDOW)).buckets, rewritten.buckets); yield* service.awaitPersisted; + const { stateDir } = yield* ServerConfig.ServerConfig; + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME); + const originalPath = (yield* Effect.promise(() => NodeFSP.realpath(compressedPath))).slice( + 0, + -4, + ); + yield* Effect.promise(async () => { + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record< + string, + { cs: Record; r: unknown[]; t: unknown[]; mr: number } + >; + }; + const archived = document.files[await NodeFSP.realpath(compressedPath)]; + assert.ok(archived); + document.files[originalPath] = { + ...archived, + r: [], + t: [], + mr: 1, + cs: { ...archived.cs, malformedRecords: 1 }, + }; + await NodeFSP.writeFile(cachePath, encodeUnknownJsonString(document)); + }); const restarted = yield* UsageService.make; - assert.deepStrictEqual((yield* restarted.readSummary(WINDOW)).buckets, rewritten.buckets); + const restored = yield* restarted.readSummary(WINDOW); + assert.deepStrictEqual(restored.buckets, rewritten.buckets); + assert.strictEqual( + restored.sources.find((source) => source.fingerprint.provider === "codex") + ?.malformedRecords, + 0, + ); yield* restarted.awaitPersisted; + yield* Effect.promise(async () => { + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record; + }; + assert.strictEqual(document.files[originalPath], undefined); + await NodeFSP.rm(compressedPath); + }); + const removed = yield* UsageService.make; + const retained = yield* removed.readSummary(WINDOW); + assert.deepStrictEqual(retained.buckets, rewritten.buckets); + assert.strictEqual( + retained.sources.find((source) => source.fingerprint.provider === "codex") + ?.malformedRecords, + 0, + ); + yield* removed.awaitPersisted; }).pipe( Effect.scoped, Effect.provide(layerService({ prefix: "usage-compressed-codex", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live("keeps the first host identity across recreation and explicit override removal", () => + it.effect("keeps the first host identity across recreation and explicit override removal", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); @@ -578,10 +731,10 @@ describe("UsageService", () => { const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); assert.strictEqual(source?.fingerprint.hostId, expected); } - }).pipe(Effect.scoped), + }), ); - it.live("concurrent initialization keeps one host identity across service recreation", () => + it.effect("concurrent initialization keeps one host identity across service recreation", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); @@ -634,10 +787,10 @@ describe("UsageService", () => { const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); assert.strictEqual(source?.fingerprint.hostId, hostId); } - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "repairs initial Codex prices after unchanged-file retries, persists evidence and corrections, and honors later native tiers", () => Effect.gen(function* () { @@ -786,10 +939,106 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( + "keeps resolved Codex tiers when a grown pre-v15 cache entry re-parses without history", + () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const sessions = NodePath.join(home, "codex", "sessions"); + const rolloutPath = NodePath.join(sessions, "tier.jsonl"); + const context = (turn_id: string) => ({ + type: "turn_context", + payload: { model: "gpt-6-astra", turn_id }, + }); + const usage = (output_tokens: number, total_output_tokens: number) => ({ + type: "event_msg", + timestamp: "2026-08-01T10:00:00Z", + payload: { + type: "token_count", + info: { + last_token_usage: { input_tokens: 0, output_tokens }, + total_token_usage: { input_tokens: 0, output_tokens: total_output_tokens }, + }, + }, + }); + const lines = (records: readonly unknown[]) => + records.map((record) => encodeUnknownJsonString(record)).join("\n") + "\n"; + const verify = (summary: UsageSummary, output: number, cost: number) => { + assert.strictEqual(totalOutputTokens(summary), output); + assert.strictEqual( + summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0), + cost, + ); + }; + yield* Effect.promise(async () => { + await NodeFSP.mkdir(sessions, { recursive: true }); + await NodeFSP.writeFile( + rolloutPath, + lines([ + { type: "session_meta", payload: { id: "tier-session", model_provider: "openai" } }, + context("ultra-turn"), + usage(1, 1), + // An equal request at the same time, from a turn priced at the standard tier. + context("standard-turn"), + usage(1, 2), + ]), + ); + }); + yield* Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + yield* seedCodexHistory({ + id: "ultra-turn", + sessionId: "tier-session", + options: [{ id: "serviceTier", value: "ultrafast" }], + }); + yield* seedCodexHistory({ id: "standard-turn", sessionId: "tier-session", options: [] }); + const first = yield* UsageService.make; + verify(yield* first.readSummary(WINDOW), 2, 7); + yield* first.awaitPersisted; + + // Downgrade the saved cache to v14, whose clean Codex entries cannot resume. + yield* Effect.promise(async () => { + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME); + const document = JSON.parse(await NodeFSP.readFile(cachePath, "utf8")); + await NodeFSP.rm(cachePath); + await NodeFSP.writeFile( + NodePath.join(stateDir, "usage-scan-cache-v14.json"), + encodeUnknownJsonString({ ...document, version: 14 }), + ); + await NodeFSP.appendFile(rolloutPath, lines([context("later-turn"), usage(2, 4)])); + }); + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE orchestration_events RENAME TO unavailable_events`; + const upgraded = yield* UsageService.make; + verify(yield* upgraded.readSummary(WINDOW), 4, 9); + yield* upgraded.awaitPersisted; + const restarted = yield* UsageService.make; + verify(yield* restarted.readSummary(WINDOW), 4, 9); + yield* sql`ALTER TABLE unavailable_events RENAME TO orchestration_events`; + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-reparse-tier", + home, + settings, + ratesDocument: { + "gpt-6-astra": { + input_cost_per_token: 0, + output_cost_per_token: 1, + input_cost_per_token_ultrafast: 0, + output_cost_per_token_ultrafast: 6, + }, + }, + }), + ), + ); + }), + ); + + it.effect( "reads Pi per-model usage and auxiliary costs once across forks and repeated entries", () => Effect.gen(function* () { @@ -975,10 +1224,80 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), + ); + + it.effect("prices Pi usage mapped onto a Pi model at that model's rate", () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const dir = NodePath.join(home, "pi", "sessions", "project"); + const message = (id: string, model: string) => ({ + type: "message", + id, + timestamp: "2026-08-01T10:00:00Z", + message: { + role: "assistant", + provider: "anthropic", + model, + usage: { input: 10, output: 5 }, + }, + }); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(dir, "session.jsonl"), + [ + { type: "session", id: "session" }, + message("released", "actual-model"), + message("preview", "actual-model-preview"), + ] + .map((line) => encodeUnknownJsonString(line)) + .join("\n") + "\n", + ); + }); + const summary = yield* Effect.gen(function* () { + const service = yield* UsageService.make; + return yield* service.readSummary(WINDOW); + }).pipe( + Effect.scoped, + Effect.provide( + layerService({ + prefix: "usage-pi-model-alias", + home, + ratesDocument: { + "actual-model": { input_cost_per_token: 1, output_cost_per_token: 4 }, + }, + settings: { + ...settings, + usageModelAliases: { "anthropic/actual-model-preview": "anthropic/actual-model" }, + }, + }), + ), + ); + assert.deepStrictEqual( + summary.buckets + .filter((bucket) => bucket.provider === "pi") + .map(({ model, records, unpricedRecords, costUsd, costSource }) => ({ + model, + records, + unpricedRecords, + costUsd, + costSource, + })), + [ + { + model: "anthropic/actual-model", + records: 2, + unpricedRecords: 0, + costUsd: 60, + costSource: "modelPriced", + }, + ], + ); + }), ); - it.live( + it.effect( "reads Muse inference history once, persists appended usage, and reprices unknown models", () => Effect.gen(function* () { @@ -1084,7 +1403,7 @@ describe("UsageService", () => { }; const muse = (summary: UsageSummary) => summary.buckets.filter((bucket) => bucket.provider === "muse"); - const first = yield* service.readSummary(window); + const first = yield* service.readSummary({ ...window, awaitRefresh: true }); const buckets = muse(first); assert.strictEqual( buckets.reduce((sum, b) => sum + b.records, 0), @@ -1166,6 +1485,7 @@ describe("UsageService", () => { assert.closeTo(repriced?.costUsd ?? NaN, 0.000486, 1e-12); }).pipe( Effect.scoped, + Effect.provideService(SpawnExecutableResolution, (command: string) => command), Effect.provide( layerService({ prefix: "usage-muse", @@ -1196,73 +1516,168 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), + ); + + it.effect("returns other providers' usage while Muse home discovery is still pending", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); + const museStarted = yield* Deferred.make(); + const museReady = yield* Deferred.make(); + const museHome = NodePath.join(home, "muse"); + yield* Effect.promise(() => + NodeFSP.mkdir(NodePath.join(museHome, "sessions"), { recursive: true }), + ); + using _create = vi + .spyOn(MuseSdk, "createMuseSdkHostEffect") + .mockImplementation(() => + Deferred.succeed(museStarted, undefined).pipe(Effect.andThen(Deferred.await(museReady))), + ); + const museSources = (summary: UsageSummary) => + summary.sources + .filter((source) => source.fingerprint.provider === "muse") + .map((source) => [source.fingerprint.resolvedHomePath, source.status, source.refreshing]); + const [pending, refreshed] = yield* Effect.gen(function* () { + const service = yield* UsageService.make; + const read = yield* Effect.forkChild(service.readSummary(WINDOW)); + yield* Deferred.await(museStarted); + const pending = yield* Fiber.join(read); + const refresh = yield* Effect.forkChild( + service.readSummary({ ...WINDOW, awaitRefresh: true }), + ); + yield* Deferred.succeed(museReady, { + initializeResult: { grantedCapabilities: [], museHome }, + close: async () => {}, + } as unknown as MuseSdk.MuseSdkHost); + return [pending, yield* Fiber.join(refresh)] as const; + }).pipe( + Effect.scoped, + Effect.provideService(SpawnExecutableResolution, (command: string) => command), + Effect.provide( + layerService({ + prefix: "usage-muse-pending", + home, + settings: { + ...settings, + providerInstances: { + ...settings.providerInstances, + [ProviderInstanceId.make("muse")]: { + driver: ProviderDriverKind.make("muse"), + enabled: false, + }, + }, + }, + }), + ), + ); + assert.strictEqual(totalOutputTokens(pending), 5); + assert.deepStrictEqual(museSources(pending), [["muse", "ok", true]]); + assert.deepStrictEqual(museSources(refreshed), [ + [NodePath.join(museHome, "sessions"), "ok", undefined], + ]); + }), ); - it.live("reports missing Pi history and skips malformed records without losing valid usage", () => + it.effect("identifies a transcript directory created after the server first read usage", () => Effect.gen(function* () { const { home, settings } = yield* setup; + const scope = "0123456789abcdef0123456789abcdef"; + const dir = NodePath.join(home, "pi", "sessions"); yield* Effect.gen(function* () { const service = yield* UsageService.make; - const missing = yield* service.readSummary(WINDOW); + const piFingerprint = (summary: UsageSummary) => + summary.sources.find((source) => source.fingerprint.provider === "pi")?.fingerprint; + const missing = piFingerprint(yield* service.readSummary(WINDOW)); + assert.strictEqual(missing?.resolvedHomePath, dir); + assert.isUndefined(missing?.physicalSourceId); + yield* Effect.promise(() => NodeFSP.mkdir(dir, { recursive: true })); assert.strictEqual( - missing.sources.find((source) => source.fingerprint.provider === "pi")?.status, - "missing", + piFingerprint(yield* service.readSummary(WINDOW))?.physicalSourceId, + physicalSourceIdOf(scope, yield* Effect.promise(() => NodeFSP.realpath(dir))), ); - const dir = NodePath.join(home, "pi", "sessions"); - yield* Effect.promise(async () => { - await NodeFSP.mkdir(dir, { recursive: true }); - await NodeFSP.writeFile( - NodePath.join(dir, "session.jsonl"), - [ - "{broken", - "null", - encodeUnknownJsonString({ type: "session", id: "valid" }), - encodeUnknownJsonString({ - type: "message", - id: "bad", - timestamp: "invalid", - message: { - role: "assistant", - provider: "openai", - model: "model", - usage: { input: 100 }, - }, - }), - encodeUnknownJsonString({ - type: "message", - id: "valid", - timestamp: "2026-08-01T10:00:00Z", - message: { - role: "assistant", - provider: "openai", - model: "model", - usage: { - input: -1, - cacheRead: "100", - output: 7, - reasoning: 50, - cost: { total: -1 }, - }, - }, - }), - ].join("\n") + "\n", - ); - }); - const summary = yield* service.readSummary(WINDOW); - const pi = summary.buckets.filter((bucket) => bucket.provider === "pi"); - assert.strictEqual(pi.length, 1); - assert.strictEqual(pi[0] && totalTokens(pi[0].totals), 7); - assert.strictEqual(pi[0]?.totals.reasoningTokens, 7); - assert.strictEqual(pi[0]?.costSource, "unpriced"); }).pipe( Effect.scoped, - Effect.provide(layerService({ prefix: "usage-pi-malformed", home, settings })), + Effect.provide( + layerService({ + prefix: "usage-physical-source-created", + home, + settings, + // The native Windows server reads identity from realpath alone. + platform: "win32", + environment: { [DESKTOP_HOST_SCOPE_ENV]: scope }, + }), + ), ); - }).pipe(Effect.scoped), + }), + ); + + it.effect( + "reports missing Pi history and skips malformed records without losing valid usage", + () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + const missing = yield* service.readSummary(WINDOW); + assert.strictEqual( + missing.sources.find((source) => source.fingerprint.provider === "pi")?.status, + "missing", + ); + const dir = NodePath.join(home, "pi", "sessions"); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(dir, "session.jsonl"), + [ + "{broken", + "null", + encodeUnknownJsonString({ type: "session", id: "valid" }), + encodeUnknownJsonString({ + type: "message", + id: "bad", + timestamp: "invalid", + message: { + role: "assistant", + provider: "openai", + model: "model", + usage: { input: 100 }, + }, + }), + encodeUnknownJsonString({ + type: "message", + id: "valid", + timestamp: "2026-08-01T10:00:00Z", + message: { + role: "assistant", + provider: "openai", + model: "model", + usage: { + input: -1, + cacheRead: "100", + output: 7, + reasoning: 50, + cost: { total: -1 }, + }, + }, + }), + ].join("\n") + "\n", + ); + }); + const summary = yield* service.readSummary(WINDOW); + const pi = summary.buckets.filter((bucket) => bucket.provider === "pi"); + assert.strictEqual(pi.length, 1); + assert.strictEqual(pi[0] && totalTokens(pi[0].totals), 7); + assert.strictEqual(pi[0]?.totals.reasoningTokens, 7); + assert.strictEqual(pi[0]?.costSource, "unpriced"); + }).pipe( + Effect.scoped, + Effect.provide(layerService({ prefix: "usage-pi-malformed", home, settings })), + ); + }), ); - it.live("discovers Pi history in its default home and directory overrides", () => + it.effect("discovers Pi history in its default home and directory overrides", () => Effect.gen(function* () { const { home, settings } = yield* setup; for (const [agentDir, sessionDir, relativeDir, launchArgs, instanceHome, platform] of [ @@ -1286,6 +1701,15 @@ describe("UsageService", () => { "windows-profile", "win32", ], + [undefined, undefined, "pi-home/.pi/agent/sessions", undefined, "pi-home"], + ["~/custom-pi", undefined, "pi-agent-home/custom-pi/sessions", undefined, "pi-agent-home"], + [ + "~/ignored-pi", + "~/custom-sessions", + "pi-session-home/custom-sessions", + undefined, + "pi-session-home", + ], ] as const) { const dir = NodePath.join(home, relativeDir); yield* Effect.promise(async () => { @@ -1325,7 +1749,7 @@ describe("UsageService", () => { prefix: "usage-pi-" + relativeDir.replaceAll("/", "-"), home, settings: - launchArgs === undefined + launchArgs === undefined && instanceHome === undefined ? settings : { ...settings, @@ -1333,7 +1757,7 @@ describe("UsageService", () => { ...settings.providerInstances, [ProviderInstanceId.make("pi")]: { driver: ProviderDriverKind.make("pi"), - config: { launchArgs }, + config: launchArgs === undefined ? {} : { launchArgs }, environment: instanceHome === undefined ? [] @@ -1357,10 +1781,10 @@ describe("UsageService", () => { Effect.provideService(HostProcess.HomeDirectory, home), ); } - }).pipe(Effect.scoped), + }), ); - it.live("reads shared managed default and disabled extra account history once", () => + it.effect("reads shared managed default and disabled extra account history once", () => Effect.gen(function* () { const { home, settings } = yield* setup; const summary = yield* Effect.gen(function* () { @@ -1437,10 +1861,10 @@ describe("UsageService", () => { ).length, 1, ); - }).pipe(Effect.scoped), + }), ); - it.live("restores the Cursor account cache after a restart", () => + it.effect("restores the Cursor account cache after a restart", () => Effect.gen(function* () { const { settings, home } = yield* setup; yield* TestClock.setTime(CURSOR_NOW); @@ -1479,10 +1903,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () => + it.effect("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () => Effect.gen(function* () { const { settings, home } = yield* setup; const signIn = new TextEncoder().encode( @@ -1531,10 +1955,10 @@ describe("UsageService", () => { ]); assert.strictEqual(cursorSource(summary)?.status, "ok"); } - }).pipe(Effect.scoped), + }), ); - it.live("does not show a previous Cursor account's history after the API key changes", () => + it.effect("does not show a previous Cursor account's history after the API key changes", () => Effect.gen(function* () { const { settings, home } = yield* setup; yield* TestClock.setTime(CURSOR_NOW); @@ -1573,10 +1997,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live("keeps a new Cursor key's refresh visible beside a failing key", () => + it.effect("keeps a new Cursor key's refresh visible beside a failing key", () => Effect.gen(function* () { const { settings, home } = yield* setup; const cursor = makeFakeCursor(); @@ -1658,10 +2082,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("reports one Cursor source when two API keys belong to the same account", () => + it.effect("reports one Cursor source when two API keys belong to the same account", () => Effect.gen(function* () { const { settings, home } = yield* setup; yield* TestClock.setTime(CURSOR_NOW); @@ -1720,10 +2144,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live( + it.effect( "includes OpenCode history but does not substitute desktop usage for an unavailable Cursor account", () => Effect.gen(function* () { @@ -1777,10 +2201,47 @@ describe("UsageService", () => { ?.distinctSessions, 1, ); - }).pipe(Effect.scoped), + }), ); - it.live("includes host and merged OpenCode instance histories once across list aliases", () => + it.effect("counts unpriced tokens from the unpriced records of a mixed model", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + const message = (id: string, cost: number, input: number, output: number, minute: number) => + encodeUnknownJson({ + id, + sessionID: "session-1", + role: "assistant", + modelID: "acme-coder-1", + providerID: "acme", + time: { created: Date.parse(`2026-08-01T10:0${minute}:00Z`) }, + cost, + tokens: { input, output, reasoning: 0, cache: { read: 0, write: 0 } }, + }); + const priced = yield* message("msg_priced", 1, 60, 40, 0); + const unpriced = yield* message("msg_unpriced", 0, 9_000, 900, 1); + yield* Effect.promise(async () => { + const directory = NodePath.join(home, "opencode", "storage", "message", "session-1"); + await NodeFSP.mkdir(directory, { recursive: true }); + await NodeFSP.writeFile(NodePath.join(directory, "msg_priced.json"), priced); + await NodeFSP.writeFile(NodePath.join(directory, "msg_unpriced.json"), unpriced); + }); + const service = yield* UsageService.make.pipe( + Effect.provide(layerService({ prefix: "usage-service-unpriced-tokens", home, settings })), + ); + const summary = yield* service.readSummary(WINDOW); + const model = mergeUsage( + [{ environmentId: EnvironmentId.make("local"), label: "local", summary }], + summary.contractVersion, + ).models.find((entry) => entry.model === "acme-coder-1"); + + assert.strictEqual(model?.costUsd, 1); + assert.strictEqual(model?.totalTokens, 10_000); + assert.strictEqual(model?.unpricedTokens, 9_900); + }), + ); + + it.effect("includes host and merged OpenCode instance histories once across list aliases", () => Effect.gen(function* () { const { settings, home } = yield* setup; const hostRoot = NodePath.join(home, "opencode"); @@ -1856,10 +2317,10 @@ describe("UsageService", () => { .sort((a, b) => a - b), [5, 7, 11], ); - }).pipe(Effect.scoped), + }), ); - it.live("counts aliased OpenCode and Antigravity directories once", () => + it.effect("counts aliased OpenCode and Antigravity directories once", () => Effect.gen(function* () { const { settings, home } = yield* setup; const opencode = NodePath.join(home, "opencode-store"); @@ -1910,10 +2371,10 @@ describe("UsageService", () => { sourcesFor("antigravity")[0]?.fingerprint.resolvedHomePath, yield* Effect.promise(() => NodeFSP.realpath(conversations)), ); - }).pipe(Effect.scoped), + }), ); - it.live("reads Antigravity history from each instance's data directory", () => + it.effect("reads Antigravity history from each instance's data directory", () => Effect.gen(function* () { const { settings, home } = yield* setup; const first = NodePath.join(home, "antigravity-first"); @@ -1981,10 +2442,10 @@ describe("UsageService", () => { outputTokens, ); } - }).pipe(Effect.scoped), + }), ); - it.live("reads configured and disabled accounts once across shared and aliased homes", () => + it.effect("reads configured and disabled accounts once across shared and aliased homes", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; const codexHome = NodePath.join(home, "codex-account"); @@ -2050,6 +2511,7 @@ describe("UsageService", () => { }, [ProviderInstanceId.make("codex-work")]: { driver: ProviderDriverKind.make("codex"), + config: { shadowHomePath: NodePath.join(home, "work-shadow") }, environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }], }, [ProviderInstanceId.make("codex-alias")]: { @@ -2099,10 +2561,38 @@ describe("UsageService", () => { sources.filter((source) => source.fingerprint.provider === "codex").length, 1, ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect("keeps default-home history after the default account moves to a custom home", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const defaultHome = NodePath.join(home, "default-claude"); + const defaultProjects = NodePath.join(defaultHome, "projects", "proj"); + yield* Effect.promise(async () => { + await NodeFSP.writeFile(transcript, claudeLine(1, 5)); + await NodeFSP.mkdir(defaultProjects, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(defaultProjects, "earlier.jsonl"), + claudeLine(2, 7, "claude-fable-5", "earlier-session"), + ); + }); + const summary = yield* UsageService.make.pipe( + Effect.flatMap((service) => service.readSummary(WINDOW)), + Effect.provide( + layerService({ + prefix: "usage-service-default-home-test", + home, + environment: { CLAUDE_CONFIG_DIR: defaultHome }, + settings, + }), + ), + ); + assert.strictEqual(totalOutputTokens(summary), 12); + }), + ); + + it.effect( "uses explicit account settings before environment and default homes, then refreshes them", () => Effect.gen(function* () { @@ -2182,10 +2672,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "uses inherited home variables when explicit default accounts have no home settings", () => Effect.gen(function* () { @@ -2228,10 +2718,10 @@ describe("UsageService", () => { .resolvedHomePath, NodePath.join(home, "grok", "sessions"), ); - }).pipe(Effect.scoped), + }), ); - it.live.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)( + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)( "reports unreadable transcripts as partial and recovers once they can be read", () => Effect.gen(function* () { @@ -2256,10 +2746,79 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-unreadable", home, settings })), ); - }).pipe(Effect.scoped), + }), + ); + + it.effect( + "answers a provisional read from the last scan, then the exact read adds what changed", + () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); + const provisional = { ...WINDOW, provisional: true }; + const claude = (summary: UsageSummary) => + summary.sources.find((source) => source.fingerprint.provider === "claude"); + yield* Effect.gen(function* () { + // With nothing persisted, the first answer is a full scan. + const service = yield* UsageService.make; + const loop = NodePath.join(NodePath.dirname(transcript), "loop.jsonl"); + yield* Effect.promise(() => NodeFSP.symlink(loop, loop, "junction")); + assert.strictEqual(claude(yield* service.readSummary(provisional))?.status, "partial"); + yield* Effect.promise(() => NodeFSP.rm(loop)); + // A scan that missed a path covers nothing, so this is a full scan too. + assert.isUndefined(claude(yield* service.readSummary(provisional))?.refreshing); + yield* service.awaitPersisted; + + yield* Effect.promise(() => NodeFSP.appendFile(transcript, claudeLine(2, 7))); + const restarted = yield* UsageService.make; + const saved = yield* restarted.readSummary(provisional); + assert.strictEqual(totalOutputTokens(saved), 5); + assert.isTrue(claude(saved)?.refreshing); + // A window that starts before the saved scan could only show part of its usage. + const wider = yield* restarted.readSummary({ + ...provisional, + sinceDay: UsageDay.make("2026-07-01"), + }); + assert.strictEqual(totalOutputTokens(wider), 12); + assert.isUndefined(claude(wider)?.refreshing); + const refreshed = yield* restarted.readSummary({ ...WINDOW, awaitRefresh: true }); + assert.strictEqual(totalOutputTokens(refreshed), 12); + assert.isUndefined(claude(refreshed)?.refreshing); + // Saved usage with nothing to show marks nothing refreshing, so it must not be the answer. + yield* Effect.promise(() => + NodeFSP.appendFile(transcript, claudeLine(3, 11, "claude-other")), + ); + const unseen = yield* restarted.readSummary({ + ...provisional, + modelFilter: { include: [{ model: "claude-other" }] }, + }); + assert.strictEqual(totalOutputTokens(unseen), 11); + yield* restarted.awaitPersisted; + + // A saved scan with an entry this server cannot read covers nothing. + const { stateDir } = yield* ServerConfig.ServerConfig; + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME); + yield* Effect.promise(async () => { + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record>; + }; + const [entry] = Object.values(document.files); + document.files[NodePath.join(NodePath.dirname(transcript), "broken.jsonl")] = { + ...entry, + r: "broken", + }; + await NodeFSP.writeFile(cachePath, JSON.stringify(document)); + }); + const reloaded = yield* UsageService.make; + assert.isUndefined(claude(yield* reloaded.readSummary(provisional))?.refreshing); + }).pipe( + Effect.scoped, + Effect.provide(layerService({ prefix: "usage-service-provisional", home, settings })), + ); + }), ); - it.live("filters original model IDs before aliases, pricing, buckets and session counts", () => + it.effect("filters original model IDs before aliases, pricing, buckets and session counts", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => @@ -2361,10 +2920,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("reprices unchanged transcripts when custom prices are added, edited, or removed", () => + it.effect("reprices unchanged transcripts when custom prices are added, edited, or removed", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model"))); @@ -2405,10 +2964,10 @@ describe("UsageService", () => { layerService({ prefix: "usage-service-price-overrides-test", home, settings }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "retains Codex reconciliation and partial coverage through persisted restart, append and repair", () => Effect.gen(function* () { @@ -2528,10 +3087,69 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( + "merges partial Claude copies through tail replacement, newline completion and restart", + () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const partial = claudeCopy(PARTIAL_USAGE); + const complete = claudeCopy(COMPLETE_USAGE); + yield* Effect.promise(() => NodeFSP.writeFile(transcript, partial)); + yield* Effect.gen(function* () { + const first = yield* UsageService.make; + assert.strictEqual(totalOutputTokens(yield* first.readSummary(WINDOW)), 3); + yield* first.awaitPersisted; + + yield* Effect.promise(() => NodeFSP.appendFile(transcript, complete.trimEnd())); + const resumed = yield* UsageService.make; + const tail = yield* resumed.readSummary(WINDOW); + assert.deepStrictEqual(tail.buckets[0]?.totals, COMPLETE_TOTALS); + assert.strictEqual(tail.buckets[0]?.records, 1); + assert.closeTo(tail.buckets[0]?.costUsd ?? 0, COMPLETE_COST_USD, 1e-12); + yield* resumed.awaitPersisted; + const restarted = yield* UsageService.make; + assert.deepStrictEqual((yield* restarted.readSummary(WINDOW)).buckets, tail.buckets); + + // Grow the file without changing its settled prefix: the old tail must be discarded. + yield* Effect.promise(() => + NodeFSP.writeFile(transcript, partial + claudeLine(2, 7) + claudeLine(3, 5)), + ); + const replaced = yield* restarted.readSummary(WINDOW); + assert.strictEqual(totalOutputTokens(replaced), 3 + 7 + 5); + assert.strictEqual(replaced.buckets[0]?.records, 3); + + yield* Effect.promise(() => NodeFSP.appendFile(transcript, complete.trimEnd())); + const grown = yield* restarted.readSummary(WINDOW); + assert.deepStrictEqual(grown.buckets[0]?.totals, { + ...COMPLETE_TOTALS, + uncachedInputTokens: 22, + outputTokens: 264 + 7 + 5, + }); + assert.strictEqual(grown.buckets[0]?.records, 3); + yield* Effect.promise(() => NodeFSP.appendFile(transcript, "\n")); + assert.deepStrictEqual((yield* restarted.readSummary(WINDOW)).buckets, grown.buckets); + yield* restarted.awaitPersisted; + assert.deepStrictEqual( + (yield* (yield* UsageService.make).readSummary(WINDOW)).buckets, + grown.buckets, + ); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-service-copy-lifecycle-test", + home, + settings, + ratesDocument: COPY_RATES, + }), + ), + ); + }), + ); + + it.effect( "keeps large-record totals and costs exact through append, dedupe, restart and cleanup", () => Effect.gen(function* () { @@ -2583,13 +3201,14 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live.each([4, 5, 6, 7, 8, 10])( + it.effect.each([4, 5, 6, 7, 8, 10, 11, 12, 13, 14])( "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts, removes the old file", (version) => Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-02T12:00:00Z")); const { home, settings } = yield* setup; const sessions = NodePath.join(home, "codex", "sessions"); const rollout = (sessionId: string, outputTokens: number) => @@ -2687,7 +3306,7 @@ describe("UsageService", () => { 60 + 20 * (version === 4 ? 1 : 2), ); yield* upgraded.awaitPersisted; - assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v11.json"); + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v17.json"); assert.deepStrictEqual( (yield* Effect.promise(() => NodeFSP.readdir(stateDir))) .filter((name) => name.startsWith("usage-scan-cache")) @@ -2713,10 +3332,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("re-parses a clean v10 Codex rollout that grew after an interrupted request", () => + it.effect("re-parses a clean v10 Codex rollout that grew after an interrupted request", () => Effect.gen(function* () { const { home, settings } = yield* setup; const sessions = NodePath.join(home, "codex", "sessions"); @@ -2813,10 +3432,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("preserves saved tokens, costs and sessions after transcript cleanup and restart", () => + it.effect("preserves saved tokens, costs and sessions after transcript cleanup and restart", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; const alias = NodePath.join(home, "claude-alias"); @@ -2914,10 +3533,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("credits the same copy of a duplicate after its transcripts are deleted", () => + it.effect("credits the same copy of a duplicate after its transcripts are deleted", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; const dir = NodePath.dirname(transcript); @@ -2952,10 +3571,68 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-copy-order-test", home, settings })), ); - }).pipe(Effect.scoped), + }), + ); + + it.effect("credits the same copy of a duplicate from the last scan as an exact read does", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z")); + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + const [first = "", second = ""] = yield* Effect.promise(async () => { + await NodeFSP.writeFile(NodePath.join(dir, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(dir, "b.jsonl"), ""); + return (await NodeFSP.readdir(dir)).map((name) => NodePath.join(dir, name)); + }); + const forked = (line: string) => line.replace('"session-1"', '"session-2"'); + yield* Effect.promise(async () => { + await NodeFSP.writeFile(first, claudeLine(1, 5)); + await NodeFSP.utimes(first, BEFORE_NARROW_WINDOW, BEFORE_NARROW_WINDOW); + await NodeFSP.writeFile(second, forked(claudeLine(1, 5)) + forked(claudeLine(2, 7))); + }); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + // The narrow window saves the second copy before the wide one reads the first. + yield* service.readSummary(NARROW_WINDOW); + const exact = yield* service.readSummary(WINDOW); + yield* service.awaitPersisted; + const restarted = yield* UsageService.make; + const saved = yield* restarted.readSummary({ ...WINDOW, provisional: true }); + assert.isTrue(saved.sources.some((source) => source.refreshing === true)); + assert.deepStrictEqual(saved.buckets, exact.buckets); + }).pipe( + Effect.provide(layerService({ prefix: "usage-service-saved-order-test", home, settings })), + ); + + // A narrow scan that first saves the earlier copy still puts it before a later file it skipped. + yield* Effect.promise(async () => { + await NodeFSP.writeFile(first, forked(claudeLine(1, 5)) + forked(claudeLine(2, 7))); + await NodeFSP.utimes( + first, + Date.parse("2026-07-01T00:00:00Z") / 1000, + Date.parse("2026-07-01T00:00:00Z") / 1000, + ); + await NodeFSP.writeFile(second, claudeLine(1, 5)); + await NodeFSP.utimes(second, BEFORE_NARROW_WINDOW, BEFORE_NARROW_WINDOW); + }); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + yield* service.readSummary(WINDOW); + yield* Effect.promise(() => + NodeFSP.utimes(first, NARROW_WINDOW_MTIME, NARROW_WINDOW_MTIME), + ); + yield* service.readSummary(NARROW_WINDOW); + const saved = yield* service.readSummary({ ...WINDOW, provisional: true }); + assert.isTrue(saved.sources.some((source) => source.refreshing === true)); + const exact = yield* service.readSummary(WINDOW); + assert.deepStrictEqual(saved.buckets, exact.buckets); + }).pipe( + Effect.provide(layerService({ prefix: "usage-service-narrow-order-test", home, settings })), + ); + }), ); - it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "keeps a newer cached read when a slower scan of another window finishes later", () => Effect.gen(function* () { @@ -2982,53 +3659,56 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-stale-read-test", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live("keeps an absent directory missing when its cached files only contain diagnostics", () => - Effect.gen(function* () { - const { transcript, settings, home } = yield* setup; - yield* Effect.promise(() => - NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }), - ); - yield* Effect.gen(function* () { - const { stateDir } = yield* ServerConfig.ServerConfig; - const mtimeMs = yield* Clock.currentTimeMillis; - const cache = makeScanCacheWriter()( - new Map([ - [ - transcript, - { - size: 0, - mtimeMs, - provider: "claude" as const, - records: [], - tailRecords: [], - malformedRecords: 2, - position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, - }, - ], - ]), - {}, + it.effect( + "keeps an absent directory missing when its cached files only contain diagnostics", + () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-02T12:00:00Z")); + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(() => + NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }), ); - yield* Effect.promise(async () => { - await NodeFSP.mkdir(stateDir, { recursive: true }); - await NodeFSP.writeFile(NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), cache); - }); - const summary = yield* (yield* UsageService.make).readSummary(WINDOW); - const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); - assert.strictEqual(source?.status, "missing"); - assert.strictEqual(source?.scannedFiles, 0); - assert.strictEqual(source?.malformedRecords, 2); - }).pipe( - Effect.provide( - layerService({ prefix: "usage-service-missing-diagnostics", home, settings }), - ), - ); - }).pipe(Effect.scoped), + yield* Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + const mtimeMs = yield* Clock.currentTimeMillis; + const cache = makeScanCacheWriter()( + new Map([ + [ + transcript, + { + size: 0, + mtimeMs, + provider: "claude" as const, + records: [], + tailRecords: [], + malformedRecords: 2, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }, + ], + ]), + {}, + ); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(stateDir, { recursive: true }); + await NodeFSP.writeFile(NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), cache); + }); + const summary = yield* (yield* UsageService.make).readSummary(WINDOW); + const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); + assert.strictEqual(source?.status, "missing"); + assert.strictEqual(source?.scannedFiles, 0); + assert.strictEqual(source?.malformedRecords, 2); + }).pipe( + Effect.provide( + layerService({ prefix: "usage-service-missing-diagnostics", home, settings }), + ), + ); + }), ); - it.live("reports saved usage of a removed directory only for windows it reaches", () => + it.effect("reports saved usage of a removed directory only for windows it reaches", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse("2026-08-12T00:00:00Z")); const { transcript, settings, home } = yield* setup; @@ -3059,10 +3739,10 @@ describe("UsageService", () => { assert.deepStrictEqual(later.buckets, []); assert.strictEqual(later.sources[0]?.status, "missing"); assert.strictEqual(later.sources[0]?.scannedFiles, 0); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live("does not share an in-flight scan after custom prices change", () => + it.effect("does not share an in-flight scan after custom prices change", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model"))); @@ -3096,7 +3776,14 @@ describe("UsageService", () => { HttpClient.HttpClient, HttpClient.make((request) => Deferred.await(releaseRates).pipe( - Effect.as(HttpClientResponse.fromWeb(request, Response.json({}))), + Effect.as( + HttpClientResponse.fromWeb( + request, + Response.json({ + "example-model": { input_cost_per_token: 1e-6, output_cost_per_token: 1e-5 }, + }), + ), + ), ), ), ), @@ -3115,15 +3802,16 @@ describe("UsageService", () => { const original = yield* Fiber.join(first); const updated = yield* Fiber.join(second); - assert.strictEqual(original.buckets[0]?.costUsd, 0); + // Fetched rates price the first read, so scans must start while the fetch is pending. + assert.isAbove(original.buckets[0]?.costUsd ?? 0, 0); assert.closeTo(updated.buckets[0]?.costUsd ?? -1, 0.00006, 1e-12); }).pipe( Effect.provide(layerService({ prefix: "usage-service-price-race-test", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live.each(["network", "http", "invalidJson", "empty"] as const)( + it.effect.each(["network", "http", "invalidJson", "empty"] as const)( "recovers pricing through the GitHub API after a %s failure", (failure) => Effect.gen(function* () { @@ -3179,10 +3867,60 @@ describe("UsageService", () => { assert.strictEqual(cached.pricing.status, "cached"); assert.deepStrictEqual(cached.buckets, summary.buckets); assert.strictEqual(requests.length, 2); - }).pipe(Effect.scoped), + }), + ); + + it.effect("refetches cached rates early for a model they do not list", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-02T00:00:00Z")); + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(() => + NodeFSP.writeFile( + transcript, + claudeLine(1, 5, "claude-new-model") + claudeLine(2, 5, "claude-unknown-model"), + ), + ); + const requests: string[] = []; + let ratesDocument: Record = { + "claude-fable-5": { input_cost_per_token: 1e-5, output_cost_per_token: 5e-5 }, + }; + const serviceLayer = layerService({ + prefix: "usage-service-unlisted-model-test", + home, + settings, + onRatesFetch: (request) => requests.push(request.url), + ratesResponse: () => Effect.succeed(Response.json(ratesDocument)), + }); + const newModelCost = (summary: UsageSummary) => + summary.buckets.find((bucket) => bucket.model === "claude-new-model")?.costUsd; + + // Rates fetched for this scan are fresh: no second request for the models they lack. + const first = yield* (yield* UsageService.make.pipe( + Effect.provide(serviceLayer), + )).readSummary(WINDOW); + assert.strictEqual(newModelCost(first), 0); + assert.strictEqual(requests.length, 1); + + // An hour later LiteLLM lists the new model; a restarted server starts from the cached table. + ratesDocument = { + ...ratesDocument, + "claude-new-model": { input_cost_per_token: 2e-5, output_cost_per_token: 1e-4 }, + }; + yield* TestClock.adjust(Duration.hours(1)); + const service = yield* UsageService.make.pipe(Effect.provide(serviceLayer)); + const refreshed = yield* service.readSummary(WINDOW); + assert.strictEqual(refreshed.pricing.status, "fresh"); + assert.closeTo(newModelCost(refreshed) ?? -1, 10 * 2e-5 + 5 * 1e-4, 1e-12); + assert.strictEqual(requests.length, 2); + + // A model the fresh table still lacks does not refetch again before the TTL. + yield* TestClock.adjust(Duration.hours(1)); + yield* service.readSummary(WINDOW); + assert.strictEqual(requests.length, 2); + }), ); - it.live("does not orphan an in-flight scan when its first caller is interrupted", () => + it.effect("does not orphan an in-flight scan when its first caller is interrupted", () => Effect.gen(function* () { const { settings, home } = yield* setup; const service = yield* UsageService.make.pipe( @@ -3257,6 +3995,6 @@ describe("UsageService", () => { orphanedAt, `interruption left the next matching request pending at scheduler check ${orphanedAt}`, ); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index b834b07805..a59fbc66a0 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -40,10 +40,17 @@ import type { UsageRecord, } from "@t3tools/provider-core/server/usage"; import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; -import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts"; import { + createOverrideRateTable, + isUnlistedModel, + parseRateTable, + type RateTable, +} from "./usagePricing.ts"; +import { + DESKTOP_HOST_SCOPE_ENV, listTranscriptFiles, readDirectoryVolumeId, + readPhysicalSourceId, readTranscriptRecords, } from "./usageTranscriptReader.ts"; import { @@ -83,6 +90,12 @@ const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) => driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [], ); +const providerRateModels = new Map( + BUILT_IN_USAGE_DRIVERS.flatMap(({ usage }) => + usage?.rateModel === undefined ? [] : [[usage.provider, usage.rateModel] as const], + ), +); + const transcriptFormats = new Map( transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const), ); @@ -92,6 +105,7 @@ interface TranscriptSource { readonly format: TranscriptUsageFormat; readonly dir: string; readonly volumeId: string; + readonly physicalSourceId?: string; readonly fileName?: string; } @@ -137,7 +151,10 @@ function sharedSessions( return shared; } const decodeCachedSources = Schema.decodeUnknownOption( - Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }), + Schema.Struct({ + sources: Schema.Record(Schema.String, CachedSource), + coveredSince: Schema.optional(Schema.Record(Schema.String, Schema.Number)), + }), ); export class UsageService extends Context.Service< @@ -155,6 +172,24 @@ export const make = Effect.gen(function* () { const settingsService = yield* ServerSettings.ServerSettingsService; const httpClient = yield* HttpClient.HttpClient; const hostEnvironment = yield* HostProcess.Environment; + const hostPlatform = yield* HostProcess.Platform; + const hostScope = hostEnvironment[DESKTOP_HOST_SCOPE_ENV]?.trim(); + // A mount or a directory's on-disk name does not change under a running server. + // A miss is not cached: the directory may not exist yet. + const physicalSourceIds = new Map>(); + const physicalSourceId = (dir: string) => + Effect.promise(() => { + const cached = physicalSourceIds.get(dir); + if (cached !== undefined) return cached; + const id = readPhysicalSourceId(dir, hostScope, hostPlatform); + physicalSourceIds.set(dir, id); + void id.then((resolved) => { + if (resolved === undefined && physicalSourceIds.get(dir) === id) { + physicalSourceIds.delete(dir); + } + }); + return id; + }); const hostname = yield* HostProcess.Hostname; const readerContext = yield* Effect.context(); @@ -165,7 +200,15 @@ export const make = Effect.gen(function* () { const correctedBatch = (records: readonly UsageRecord[]) => records.some((record) => resolvedRecords.has(record)) ? records.map(correctedRecord) : records; const sourceCache = new Map(); + // Earliest window start a complete scan read each transcript directory from. + const coveredSince = new Map(); + const coverageKey = (source: TranscriptSource) => `${source.provider}\0${source.dir}`; let cacheDirty = false; + const cover = (source: TranscriptSource, windowStartMs: number) => { + if ((coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs) return; + coveredSince.set(coverageKey(source), windowStartMs); + cacheDirty = true; + }; const isWithinDirectory = (filePath: string, dir: string) => { const relative = path.relative(dir, filePath); return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative); @@ -235,27 +278,26 @@ export const make = Effect.gen(function* () { Effect.catchCause(() => Effect.succeed(null)), ); + // Outside ratesLock, which a slow fetch holds: a provisional answer prices with these. + const loadSavedRates = yield* Effect.cached( + fileSystem.readFileString(ratesCachePath).pipe( + Effect.flatMap((raw) => decodeRatesCache(raw)), + Effect.map((saved) => { + const parsed = parseRateTable(saved.document); + if (parsed.size === 0) return; + rates = parsed; + ratesFetchedAtMs = saved.fetchedAtMs; + ratesStatus = "cached"; + }), + Effect.ignoreCause, + ), + ); + const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) { const now = yield* Clock.currentTimeMillis; const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS; + yield* loadSavedRates; if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return; - - if (ratesFetchedAtMs === null) { - const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe( - Effect.flatMap((raw) => decodeRatesCache(raw)), - Effect.catchCause(() => Effect.succeed(null)), - ); - if (fromDisk !== null) { - const parsed = parseRateTable(fromDisk.document); - if (parsed.size > 0) { - rates = parsed; - ratesFetchedAtMs = fromDisk.fetchedAtMs; - ratesStatus = "cached"; - if (now - fromDisk.fetchedAtMs < maxAgeMs) return; - } - } - } - if (ratesLastFailedAtMs !== null && now - ratesLastFailedAtMs < RATES_REFRESH_FLOOR_MS) return; let fetched = yield* fetchRates(LITELLM_RATES_URL); @@ -281,6 +323,24 @@ export const make = Effect.gen(function* () { const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force)); + // Rates are kept for RATES_TTL_MS, so a model released after the table was fetched would stay unpriced + // that long. A scan that meets a model the table does not list refetches early: once per model against + // a fresh table, with loadRates keeping RATES_REFRESH_FLOOR_MS between attempts. + const checkedUnlistedModels = new Set(); + const refreshForUnlistedModels = Effect.fn("UsageService.refreshForUnlistedModels")(function* ( + models: ReadonlySet, + ) { + const unlisted = [...models].filter( + (model) => !checkedUnlistedModels.has(model) && isUnlistedModel(rates, model), + ); + if (unlisted.length === 0) return; + yield* ensureRates(true); + const now = yield* Clock.currentTimeMillis; + // A failed fetch leaves the models unchecked, so a later scan tries again. + if (ratesFetchedAtMs === null || now - ratesFetchedAtMs >= RATES_REFRESH_FLOOR_MS) return; + for (const model of unlisted) checkedUnlistedModels.add(model); + }); + const refreshRates = ensureRates(true).pipe( Effect.map(pricing), Effect.withSpan("UsageService.refreshRates"), @@ -306,9 +366,8 @@ export const make = Effect.gen(function* () { > = Object.entries(settings.providerInstances) .filter(([, instance]) => instance.driver === driver.driverKind) .map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const); - if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) { - entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]); - } + // History in the driver's default home stays counted after every instance moves elsewhere; readers dedupe shared directories. + entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]); const decodeConfig = Schema.decodeUnknownOption(driver.configSchema); return yield* Effect.forEach( entries, @@ -330,16 +389,25 @@ export const make = Effect.gen(function* () { const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* ( settings: ServerSettingsValue, retentionCutoffMs: number, + awaitRefresh: boolean, ) { const dirs: Array = []; + const pending: Array = []; const seen = new Set(); for (const { driver, reader } of transcriptReaders) { const { provider, format } = reader; const directories = yield* Effect.forEach( yield* usageInstances(driver, settings), - (instance) => reader.directories(instance), + (instance) => reader.directories(instance, { awaitRefresh }), ); - for (const { dir: directory, fileName } of directories.flat()) { + for (const { dir: directory, fileName, refreshing } of directories.flat()) { + if (refreshing) { + const key = `${provider}\0${directory}`; + if (seen.has(key)) continue; + seen.add(key); + pending.push({ provider, dir: directory, volumeId: "", files: [], refreshing }); + continue; + } const sourceKey = provider + "\0" + directory; const previous = sourceCache.get(sourceKey); const dir = yield* fileSystem @@ -366,16 +434,18 @@ export const make = Effect.gen(function* () { const key = `${provider}\0${dir}`; if (seen.has(key)) continue; seen.add(key); + const sourceId = yield* physicalSourceId(dir); dirs.push({ provider, format, dir, volumeId, + ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }), ...(fileName === undefined ? {} : { fileName }), }); } } - return dirs; + return { dirs, pending }; }); // Share first loads so concurrent readers cannot scan against a still-empty cache. @@ -387,19 +457,27 @@ export const make = Effect.gen(function* () { Effect.catchCause(() => Effect.succeed(null)), ); let document = yield* readDocument(scanCachePath); + const current = document !== null; for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) { if (document !== null) break; document = yield* readDocument(path.join(config.stateDir, fileName)); cacheDirty = document !== null; } if (document === null) return; - for (const [path, entry] of decodeScanCache(document, transcriptFormats)) { - fileCache.set(path, entry); - } + const decoded = decodeScanCache(document, transcriptFormats); + for (const [path, entry] of decoded) fileCache.set(path, entry); + const saved = (document as { readonly files?: unknown }).files; + const complete = + typeof saved === "object" && saved !== null && Object.keys(saved).length === decoded.size; const sources = decodeCachedSources(document); if (Option.isSome(sources)) { for (const [key, source] of Object.entries(sources.value.sources)) sourceCache.set(key, source); + // Coverage describes the saved files, so it needs every one, in this version's format. + if (current && complete && fileCache.size > 0) { + for (const [key, since] of Object.entries(sources.value.coveredSince ?? {})) + coveredSince.set(key, since); + } } }), ); @@ -439,7 +517,10 @@ export const make = Effect.gen(function* () { if (cacheDirty) { cacheDirty = false; yield* Effect.sync(() => - writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }), + writeScanCache(fileCache, { + sources: Object.fromEntries(sourceCache), + coveredSince: Object.fromEntries(coveredSince), + }), ).pipe( Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)), Effect.andThen( @@ -473,7 +554,7 @@ export const make = Effect.gen(function* () { /** * Reads run concurrently, and the caller stores updates in walk order rather * than completion order: saved records of deleted transcripts aggregate in - * cache order, where the first copy of a duplicate wins. Untraced: a scan + * cache order, where the first copy of a duplicate decides its bucket. Untraced: a scan * reads thousands of files, so scanTranscriptDir records the counts instead. */ const readFileRecords = Effect.fnUntraced(function* ( @@ -523,21 +604,44 @@ export const make = Effect.gen(function* () { failed: true, }; + const identity = (record: UsageRecord) => + encodeUsageRecordKey([ + record.provider, + record.sessionId, + record.timestampMs, + record.model, + record.rateModel, + record.totals, + record.reportedCostUsd, + record.dedupeKey, + ]); + if (!parsed.resumed && cached !== undefined && cached.provider === provider) { + // A whole-file re-parse re-emits saved requests unresolved. Keep their saved tier + // corrections, since the history that resolved them may no longer be available. + // Equal requests keep their own corrections by matching occurrences in order. + const saved = new Map(); + for (const previous of [...cached.records, ...cached.tailRecords]) { + const corrected = correctedRecord(previous); + const key = identity(corrected); + const occurrences = saved.get(key); + if (occurrences === undefined) saved.set(key, [corrected]); + else occurrences.push(corrected); + } + for (const record of [...parsed.records, ...parsed.tailRecords]) { + const corrected = saved.get(identity(record))?.shift(); + if ( + record.unresolvedServiceTierTurnId !== undefined && + corrected !== undefined && + corrected.unresolvedServiceTierTurnId === undefined + ) { + resolvedRecords.set(record, corrected); + } + } + } if (parsed.resumed && cached !== undefined && cached.tailRecords.length > 0) { // Completing a tentative line reparses it. Reuse its saved correction only when the // same usage is emitted again, without putting inferred tiers in the parser state. const reparsed = [...parsed.records, ...parsed.tailRecords]; - const identity = (record: UsageRecord) => - encodeUsageRecordKey([ - record.provider, - record.sessionId, - record.timestampMs, - record.model, - record.rateModel, - record.totals, - record.reportedCostUsd, - record.dedupeKey, - ]); for (const [index, previous] of cached.tailRecords.entries()) { const record = reparsed[index]; const corrected = correctedRecord(previous); @@ -551,9 +655,8 @@ export const make = Effect.gen(function* () { } } const base = parsed.resumed && cached !== undefined ? cached.records : []; - const seen = new Set(); - const records = dedupeWithinFile([...base, ...parsed.records], seen); - const tailRecords = dedupeWithinFile(parsed.tailRecords, seen); + const records = dedupeWithinFile([...base, ...parsed.records]); + const tailRecords = parsed.tailRecords; return { records: tailRecords.length === 0 ? records : [...records, ...tailRecords], @@ -577,6 +680,7 @@ export const make = Effect.gen(function* () { readonly provider: UsageProviderKind; readonly dir: string; readonly volumeId: string; + readonly physicalSourceId?: string; readonly hostId?: string; readonly status?: UsageSource["status"]; readonly message?: string; @@ -587,19 +691,33 @@ export const make = Effect.gen(function* () { readonly malformedRecords: number; }[] | null; + /** Every transcript path the walk listed, in walk order, whatever its mtime. */ + readonly walked?: readonly string[]; readonly refreshing?: true; } const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* ( source: TranscriptSource, windowStartMs: number, + fromMemory: boolean, ) { - const { provider, format, dir, volumeId, fileName } = source; + const { provider, format, dir, volumeId, physicalSourceId, fileName } = source; + const identity = { + provider, + dir, + volumeId, + ...(physicalSourceId === undefined ? {} : { physicalSourceId }), + }; const exists = yield* fileSystem .exists(dir) .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir; - const { files, failedPaths } = yield* Effect.promise(() => + if (!exists) { + cover(source, windowStartMs); + return { ...identity, files: null } satisfies ScannedDir; + } + // scanSummary aggregates the saved files, as it does for a deleted directory. + if (fromMemory) return { ...identity, files: [] } satisfies ScannedDir; + const { files, walked, failedPaths } = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }), ); const read = yield* Effect.forEach( @@ -630,16 +748,23 @@ export const make = Effect.gen(function* () { } return { path, records, malformedRecords }; }); + const livePaths = new Set(files.map((file) => file.path)); + for (const file of read) { + if (file.failed || !file.path.endsWith(".jsonl.zst")) continue; + const originalPath = file.path.slice(0, -4); + // A successfully read archive replaces the original's saved records and diagnostics. + if (!livePaths.has(originalPath) && fileCache.delete(originalPath)) cacheDirty = true; + } const unread = failedPaths + read.filter((file) => file.failed).length; + if (unread === 0) cover(source, windowStartMs); yield* Effect.annotateCurrentSpan({ "usage.files": files.length, "usage.files_parsed": read.filter((file) => file.update !== undefined).length, }); return { - provider, - dir, - volumeId, + ...identity, files: parsedFiles, + walked, ...(unread > 0 ? { status: "partial", @@ -650,15 +775,13 @@ export const make = Effect.gen(function* () { }); const collectDirs = Effect.fn("UsageService.collectDirs")(function* ( + { dirs, pending }: Effect.Success>, windowStartMs: number, settings: ServerSettingsValue, retentionCutoffMs: number, awaitRefresh: boolean, + fromMemory: boolean, ) { - const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe( - Effect.provideContext(readerContext), - ); - const scans = Effect.forEach( scanReaders, ({ driver, reader }) => @@ -669,14 +792,19 @@ export const make = Effect.gen(function* () { Effect.flatMap((sources) => Effect.forEach(sources, ({ volumeId, ...source }) => Effect.map( + // A reader's own volumeId names a remote account, not a local directory. volumeId === undefined - ? Effect.promise(() => readDirectoryVolumeId(source.dir)) - : Effect.succeed(volumeId), - (resolved): ScannedDir => ({ + ? Effect.all([ + Effect.promise(() => readDirectoryVolumeId(source.dir)), + physicalSourceId(source.dir), + ]) + : Effect.succeed<[string, string | undefined]>([volumeId, undefined]), + ([resolved, sourceId]): ScannedDir => ({ ...source, files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null, provider: reader.provider, volumeId: resolved, + ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }), }), ), ), @@ -686,18 +814,19 @@ export const make = Effect.gen(function* () { { concurrency: "unbounded" }, ); - // Scan independent sources together, directories sequentially to bound open files; preserve order for first-copy dedupe. + // Scan independent sources together, directories sequentially to bound open files; keep order, since the first copy decides a duplicate's bucket. const [transcripts, scanDirs] = yield* Effect.all( - [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)), scans], + [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs, fromMemory)), scans], { concurrency: "unbounded" }, ); - const scanned: readonly ScannedDir[] = [...transcripts, ...scanDirs.flat()]; + const scanned: readonly ScannedDir[] = [...transcripts, ...pending, ...scanDirs.flat()]; return scanned; }); const scanSummary = Effect.fn("UsageService.scanSummary")(function* ( input: UsageSummaryInput, settings: ServerSettingsValue, + provisional: boolean, ) { if (input.sinceDay > input.untilDay) { return yield* new UsageReadError({ @@ -745,55 +874,145 @@ export const make = Effect.gen(function* () { const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000; - const [, scannedDirs] = yield* Effect.all( - [ - ensureRates(false), - collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true), - ], + const awaitRefresh = input.awaitRefresh === true; + const collect = Effect.gen(function* () { + const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe( + Effect.provideContext(readerContext), + ); + // A window no complete scan has read would show partial totals, so every directory must cover it. + // Saved files are keyed by path, so two providers reading one directory keep only one parse. + const fromMemory = + provisional && + resolved.dirs.length > 0 && + new Set(resolved.dirs.map((source) => source.dir)).size === resolved.dirs.length && + resolved.dirs.every( + (source) => (coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs, + ); + const [, scanned] = yield* Effect.all( + [ + fromMemory ? loadSavedRates : provisional ? ensureRates(false) : Effect.void, + collectDirs( + resolved, + windowStartMs, + settings, + retentionCutoffMs, + awaitRefresh, + fromMemory, + ), + ], + { concurrency: 2 }, + ); + return { scannedDirs: scanned, fromMemory }; + }); + const [{ scannedDirs, fromMemory }] = yield* Effect.all( + [collect, provisional ? Effect.void : ensureRates(false)], { concurrency: 2 }, ); - const aggregator = new UsageAggregator({ - timeZone: input.timeZone, - sinceDay: input.sinceDay, - untilDay: input.untilDay, - resolution: input.resolution ?? "day", - ...hourlyWindow, - rates, - priceOverrides: createOverrideRateTable(settings.usagePriceOverrides), - modelAliases: resolveModelAliases(settings.usageModelAliases), - ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), - }); - + const priceOverrides = createOverrideRateTable(settings.usagePriceOverrides); + const modelAliases = resolveModelAliases(settings.usageModelAliases); const sources: UsageSource[] = []; // Deleted transcripts' saved usage still aggregates and deduplicates normally. const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs); + // Saved paths are files below a scanned root, so their folder decides; folders repeat thousands of times. + const withinDir = (dir: string) => { + const foldersWithin = new Map(); + return (filePath: string) => { + const folder = path.dirname(filePath); + let within = foldersWithin.get(folder); + if (within === undefined) { + within = isWithinDirectory(folder, dir); + foldersWithin.set(folder, within); + } + return within; + }; + }; const filesByDir = scannedDirs.map(({ provider, dir, files }) => { const retainedFiles = [...(files ?? [])]; const livePaths = new Set(retainedFiles.map((file) => file.path)); + const isRetained = withinDir(dir); for (const [filePath, entry] of fileCache) { if ( entry.provider !== provider || entry.mtimeMs < retainedSinceMs || livePaths.has(filePath) || - !isWithinDirectory(filePath, dir) + !isRetained(filePath) ) continue; retainedFiles.push({ path: filePath, - records: [...entry.records, ...entry.tailRecords], + records: + entry.tailRecords.length === 0 + ? entry.records + : [...entry.records, ...entry.tailRecords], malformedRecords: entry.malformedRecords, }); } return retainedFiles; }); + // Usage two transcripts share counts in the first one, so saved files take the order an exact + // scan reads them in: walked files in walk order, then the directory's deleted files. + for (const { provider, dir, walked } of fromMemory ? [] : scannedDirs) { + if (walked === undefined) continue; + const within = withinDir(dir); + const saved = [...fileCache.keys()]; + const members = new Set( + saved.filter( + (filePath) => fileCache.get(filePath)!.provider === provider && within(filePath), + ), + ); + if (members.size < 2) continue; + const listed = new Set(walked); + const target = [ + ...walked.filter((filePath) => members.has(filePath)), + ...saved.filter((filePath) => members.has(filePath) && !listed.has(filePath)), + ]; + let next = 0; + const ordered = saved.map((filePath) => (members.has(filePath) ? target[next++]! : filePath)); + if (ordered.every((filePath, index) => filePath === saved[index])) continue; + const entries = new Map(fileCache); + fileCache.clear(); + for (const filePath of ordered) fileCache.set(filePath, entries.get(filePath)!); + cacheDirty = true; + } + + // The models priced below, as UsageAggregator resolves them: an alias replaces rateModel. + const rateModels = new Set(); + for (const files of filesByDir) { + for (const file of files) { + for (const record of file.records) { + const alias = modelAliases.get(record.model); + const model = alias ?? record.model; + if (priceOverrides.has(model.trim())) continue; + rateModels.add(alias === undefined ? (record.rateModel ?? model) : model); + } + } + } + // A saved answer prices with saved rates and the full scan after it refetches. + if (!fromMemory) yield* refreshForUnlistedModels(rateModels); + + const summaryPricing = pricing(); + + const aggregator = new UsageAggregator({ + timeZone: input.timeZone, + sinceDay: input.sinceDay, + untilDay: input.untilDay, + resolution: input.resolution ?? "day", + ...hourlyWindow, + rates, + priceOverrides, + modelAliases, + rateModel: (provider, model) => providerRateModels.get(provider)?.(model), + ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), + }); + const windowEndMs = hourlyWindow?.untilTimeMs ?? Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; let resolvedAny = false; for (const { reader } of transcriptReaders) { - if (reader.resolveServiceTiers === undefined) continue; + if (reader.resolveServiceTiers === undefined || fromMemory) continue; const pending = new Set(); for (const [index, files] of filesByDir.entries()) { if (scannedDirs[index]?.provider !== reader.provider) continue; @@ -835,7 +1054,17 @@ export const make = Effect.gen(function* () { for (const [ index, - { provider, dir, volumeId, files, status, message, refreshing, hostId: sourceHostId }, + { + provider, + dir, + volumeId, + physicalSourceId, + files, + status, + message, + refreshing, + hostId: sourceHostId, + }, ] of scannedDirs.entries()) { let scannedFiles = 0; let skippedFiles = 0; @@ -843,6 +1072,7 @@ export const make = Effect.gen(function* () { // Distinct per directory. Buckets carry per-cell session counts, but a // session spans days and models, so clients total this figure instead. const sessionIds = new Set(); + let counted = false; for (const file of filesByDir[index] ?? []) { malformedRecords += file.malformedRecords; @@ -871,8 +1101,9 @@ export const make = Effect.gen(function* () { eventOccurrences.set(key, occurrence); usageRecord = { ...record, dedupeKey: key + ":" + occurrence }; } - if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) { - sessionIds.add(record.sessionId); + if (aggregator.add(usageRecord, dir)) { + counted = true; + if (record.sessionId.length > 0) sessionIds.add(record.sessionId); } } } @@ -880,7 +1111,13 @@ export const make = Effect.gen(function* () { const sourceMessage = message ?? (files === null ? "No transcript directory on this environment." : null); sources.push({ - fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId }, + fingerprint: { + hostId: sourceHostId ?? hostId, + provider, + resolvedHomePath: dir, + volumeId, + ...(physicalSourceId === undefined ? {} : { physicalSourceId }), + }, status: files === null && scannedFiles === 0 ? "missing" @@ -899,18 +1136,28 @@ export const make = Effect.gen(function* () { .filter(Boolean) .join(" ") : sourceMessage, - ...(refreshing ? { refreshing } : {}), + // A saved answer misses what changed since its scan, so the client must ask again. An + // empty source stays unmarked: it would only flash a loading row. + ...(refreshing || (fromMemory && counted && transcriptFormats.has(provider)) + ? { refreshing: true } + : {}), }); } const pruned = pruneScanCache(fileCache, retentionCutoffMs); - if (pruned > 0) cacheDirty = true; + if (pruned > 0) { + cacheDirty = true; + // Pruned files are no longer saved, so nothing before the cutoff stays covered. + for (const [key, since] of coveredSince) { + if (since < retentionCutoffMs) coveredSince.set(key, retentionCutoffMs); + } + } const aggregated = aggregator.finish(); const readAt = yield* DateTime.now; const finishedAtMs = yield* Clock.currentTimeMillis; - return { + const summary = { contractVersion: USAGE_CONTRACT_VERSION, readAt: DateTime.formatIso(readAt), timeZone: input.timeZone, @@ -918,15 +1165,32 @@ export const make = Effect.gen(function* () { untilDay: input.untilDay, buckets: aggregated.buckets, sources, - pricing: pricing(), + pricing: summaryPricing, scanDurationMs: Math.max(0, finishedAtMs - startedAtMs), ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), } satisfies UsageSummary; + return { summary, fromMemory }; + }); + + const readWindow = Effect.fn("UsageService.readWindow")(function* ( + input: UsageSummaryInput, + settings: ServerSettingsValue, + provisional: boolean, + ) { + const { summary, fromMemory } = yield* scanSummary(input, settings, provisional); + // With nothing marked refreshing the client would keep a saved answer as final. + return fromMemory && !summary.sources.some((source) => source.refreshing === true) + ? (yield* scanSummary(input, settings, false)).summary + : summary; }); const inflightScans = new Map>(); - const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string => + const scanKey = ( + input: UsageSummaryInput, + settings: ServerSettingsValue, + provisional: boolean, + ): string => JSON.stringify([ input.timeZone, input.sinceDay, @@ -936,6 +1200,7 @@ export const make = Effect.gen(function* () { input.untilTime ?? null, settings, input.awaitRefresh === true, + provisional, input.modelFilter ?? null, ]); @@ -946,7 +1211,8 @@ export const make = Effect.gen(function* () { const modelFilter = canonicalModelFilter(requestedFilter); const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter }; const settings = yield* readSettings; - const key = scanKey(input, settings); + const provisional = input.provisional === true && input.awaitRefresh !== true; + const key = scanKey(input, settings, provisional); const deferred = yield* Effect.uninterruptible( Effect.gen(function* () { const existing = inflightScans.get(key); @@ -957,7 +1223,7 @@ export const make = Effect.gen(function* () { inflightScans.set(key, created); // Detach so caller departure cannot cancel shared scans; finished scans warm the cache. // Register writes before releasing waiters, but start writing after delivering their summary. - yield* scanSummary(input, settings).pipe( + yield* readWindow(input, settings, provisional).pipe( Effect.onExit((exit) => Effect.sync(() => inflightScans.delete(key)).pipe( Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void), diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts index 431af7b597..5002d2223d 100644 --- a/apps/server/src/usage/cliproxyApi.test.ts +++ b/apps/server/src/usage/cliproxyApi.test.ts @@ -437,6 +437,26 @@ describe("CLIProxyAPI built-in management API", () => { }), ); + it.effect("keeps a Claude account whose window reports no utilization", () => + Effect.gen(function* () { + const test = fixture({ + accounts: [{ ...accounts[0]!, provider: "claude" }], + upstream: () => ({ + status: 200, + body: { + five_hour: { utilization: null, resets_at: null }, + seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" }, + }, + }), + }); + const result = yield* (yield* test.api).readAccounts(config); + expect(result[0]?.usageLimits.unavailable).toBeUndefined(); + expect( + result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]), + ).toEqual([["seven_day", 50]]); + }), + ); + const antigravitySummary = { buckets: [ { diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts index 030983f50e..537a2b436f 100644 --- a/apps/server/src/usage/cliproxyApi.ts +++ b/apps/server/src/usage/cliproxyApi.ts @@ -70,8 +70,9 @@ const CodexUsage = Schema.Struct({ }), ), }); +// The usage endpoint can report a window without a utilization, as the CLI's own schema allows. const ClaudeWindow = Schema.Struct({ - utilization: Schema.Number, + utilization: Schema.NullOr(Schema.Number), resets_at: Schema.NullOr(Schema.String), }); const ClaudeUsage = Schema.Struct({ diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts index 08b3f3ae1b..58953fbcfa 100644 --- a/apps/server/src/usage/usageAggregation.test.ts +++ b/apps/server/src/usage/usageAggregation.test.ts @@ -12,13 +12,16 @@ const rates: RateTable = new Map([ outputCostPerToken: 5e-5, cacheReadCostPerToken: 1e-6, cacheCreationCostPerToken: 1.25e-5, + cacheCreation1hCostPerToken: 2e-5, fast: { inputCostPerToken: 2e-5, outputCostPerToken: 1e-4, cacheReadCostPerToken: 2e-6, cacheCreationCostPerToken: 2.5e-5, + cacheCreation1hCostPerToken: 4e-5, }, ultrafast: null, + contextTiers: [], }, ], ]); @@ -85,17 +88,94 @@ describe("UsageAggregator", () => { expect(bucket).not.toHaveProperty("ultrafastCostUsd"); }); - it("keeps only the first record for a repeated dedupe key", () => { + it("merges partial copies of a key by channel maximum in the first copy's bucket", () => { + const zeroTotals = { + uncachedInputTokens: 0, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 0, + reasoningTokens: 0, + }; + const partial = record({ + dedupeKey: "msg_1:", + speed: "fast", + reportedCostUsd: 1, + totals: { ...record().totals, cachedInputTokens: 1200, outputTokens: 3, reasoningTokens: 5 }, + }); + const complete = record({ + dedupeKey: "msg_1:", + model: "claude-fable-5[1m]", + timestampMs: Date.parse("2026-08-08T12:00:00Z"), + sessionId: "session-fork", + reportedCostUsd: 2, + totals: { + uncachedInputTokens: 2, + cachedInputTokens: 1000, + cacheCreationTokens: 40, + outputTokens: 264, + reasoningTokens: 135, + }, + }); + const zero = { ...partial, totals: zeroTotals, reportedCostUsd: null }; + const merged = { + reportedCostUsd: 2, + totals: { ...complete.totals, uncachedInputTokens: 100, cachedInputTokens: 1200 }, + }; + + for (const copies of [ + [zero, partial, complete, complete], + [complete, partial, zero, zero], + ]) { + const aggregator = new UsageAggregator({ + timeZone: "UTC", + sinceDay: "2026-08-01", + untilDay: "2026-08-31", + rates, + }); + copies.forEach((copy, index) => aggregator.add(copy, `${index}.jsonl`)); + const result = aggregator.finish(); + const expected = aggregate([{ ...copies[0]!, ...merged }]).buckets[0]; + + expect(result.duplicatesDropped).toBe(3); + expect(result.buckets).toEqual([{ ...expected, sourcePath: "0.jsonl" }]); + } + }); + + it("keeps a live Grok turn over a saved pre-v17 maximum in either source order", () => { + const turn = (timestampMs: number, outputTokens: number) => + record({ + provider: "grok", + model: "grok-4.5", + timestampMs, + dedupeKey: `s:p:${timestampMs}:grok-4.5`, + reportedCostUsd: outputTokens / 10, + totals: { ...record().totals, uncachedInputTokens: 0, outputTokens }, + }); + const first = turn(Date.parse("2026-08-08T10:00:00Z"), 10); + const resumed = turn(Date.parse("2026-08-08T11:00:00Z"), 20); + const savedMaximum = { ...first, totals: resumed.totals, reportedCostUsd: 2 }; + + const expected = aggregate([first, resumed]).buckets; + + for (const order of [ + [first, resumed, savedMaximum], + [savedMaximum, first, resumed], + ]) { + const result = aggregate(order); + expect(result.duplicatesDropped).toBe(1); + expect(result.buckets).toEqual(expected); + } + }); + + it("does not count a key whose first copy fell outside the window", () => { const result = aggregate([ - record({ dedupeKey: "msg_1:" }), - record({ dedupeKey: "msg_1:" }), - record({ dedupeKey: "msg_1:" }), + record({ dedupeKey: "msg_1:", timestampMs: Date.parse("2026-07-01T12:00:00Z") }), + record({ dedupeKey: "msg_1:", totals: { ...record().totals, outputTokens: 500 } }), ]); - expect(result.duplicatesDropped).toBe(2); - expect(result.buckets).toHaveLength(1); - expect(result.buckets[0]?.records).toBe(1); - expect(result.buckets[0]?.totals.outputTokens).toBe(50); + expect(result.duplicatesDropped).toBe(1); + expect(result.outOfWindow).toBe(1); + expect(result.buckets).toHaveLength(0); }); it("buckets by the day in the requested time zone", () => { @@ -197,6 +277,7 @@ describe("UsageAggregator", () => { untilDay: "2026-08-31", rates, modelAliases: resolveModelAliases({ "example-preview": "claude-fable-5" }), + rateModel: () => "claude-fable", }); aggregator.add(record()); aggregator.add(record({ model: "example-preview", rateModel: "example-preview-high" })); @@ -212,20 +293,24 @@ describe("UsageAggregator", () => { describe("resolveModelAliases", () => { it("follows chains to the final model and drops chains that enter a loop", () => { - expect( - resolveModelAliases({ + expect([ + ...resolveModelAliases({ "preview[1m]": "preview", preview: "example-model", + shared: "preview", + intoLoop: "loop", loop: "back", back: "loop", - intoLoop: "loop", + laterIntoLoop: "back", + deepIntoLoop: "intoLoop", self: "self", + validAfterLoops: "shared", }), - ).toEqual( - new Map([ - ["preview[1m]", "example-model"], - ["preview", "example-model"], - ]), - ); + ]).toEqual([ + ["preview[1m]", "example-model"], + ["preview", "example-model"], + ["shared", "example-model"], + ["validAfterLoops", "example-model"], + ]); }); }); diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index 8f94c84a3c..f4c3975354 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -10,7 +10,7 @@ import type { } from "@t3tools/contracts"; import { EMPTY_TOTALS, type UsageRecord } from "@t3tools/provider-core/server/usage"; -import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts"; +import { cacheSavingsUsd, lookupRate, priceUsage, type RateTable } from "./usagePricing.ts"; // en-CA gives ISO-ordered parts in the requested zone; Date getters are host-local. function makeDayFormatter(timeZone: string): (timestampMs: number) => string { @@ -58,6 +58,7 @@ interface MutableBucket { speedPremiumUsd: number; records: number; unpricedRecords: number; + unpricedTokens: number; providerReportedRecords: number; sessions: Set; } @@ -69,6 +70,7 @@ export interface AggregateOptions { readonly rates: RateTable; readonly priceOverrides?: RateTable; readonly modelAliases?: ReadonlyMap; + readonly rateModel?: (provider: UsageRecord["provider"], model: string) => string | undefined; readonly modelFilter?: UsageModelFilter; readonly resolution?: UsageResolution; readonly sinceTimeMs?: number; @@ -78,15 +80,26 @@ export interface AggregateOptions { export function resolveModelAliases( aliases: Readonly>, ): ReadonlyMap { - const resolved = new Map(); - for (const model of Object.keys(aliases)) { - const seen = new Set([model]); - let target = aliases[model]!; - while (Object.hasOwn(aliases, target) && !seen.has(target)) { - seen.add(target); + const models = Object.keys(aliases); + const memo = new Map(); + for (const model of models) { + if (memo.has(model)) continue; + const path: string[] = []; + let target = model; + while (Object.hasOwn(aliases, target) && !memo.has(target)) { + path.push(target); + // Null marks both the active walk and paths that end in a cycle. + memo.set(target, null); target = aliases[target]!; } - if (!Object.hasOwn(aliases, target)) resolved.set(model, target); + const terminal = Object.hasOwn(aliases, target) ? (memo.get(target) ?? null) : target; + for (const alias of path) memo.set(alias, terminal); + } + + const resolved = new Map(); + for (const model of models) { + const target = memo.get(model); + if (target !== null && target !== undefined) resolved.set(model, target); } return resolved; } @@ -129,10 +142,80 @@ export interface AggregateResult { readonly outOfWindow: number; } +/** + * Partial copies share a billed message's key: keep each token channel's maximum and the larger + * reported cost, and the first copy's time, model, session and speed so it stays in its bucket. + */ +export function mergeUsageCopies(held: UsageRecord, copy: UsageRecord): UsageRecord { + const a = held.totals; + const b = copy.totals; + const reportedCostUsd = + held.reportedCostUsd === null || copy.reportedCostUsd === null + ? (held.reportedCostUsd ?? copy.reportedCostUsd) + : Math.max(held.reportedCostUsd, copy.reportedCostUsd); + if ( + b.uncachedInputTokens <= a.uncachedInputTokens && + b.cachedInputTokens <= a.cachedInputTokens && + b.cacheCreationTokens <= a.cacheCreationTokens && + b.outputTokens <= a.outputTokens && + b.reasoningTokens <= a.reasoningTokens && + (copy.cacheCreation1hTokens ?? 0) <= (held.cacheCreation1hTokens ?? 0) && + reportedCostUsd === held.reportedCostUsd + ) { + return held; + } + const cacheCreation1hTokens = Math.max( + held.cacheCreation1hTokens ?? 0, + copy.cacheCreation1hTokens ?? 0, + ); + return { + ...held, + ...(cacheCreation1hTokens > 0 ? { cacheCreation1hTokens } : {}), + totals: { + uncachedInputTokens: Math.max(a.uncachedInputTokens, b.uncachedInputTokens), + cachedInputTokens: Math.max(a.cachedInputTokens, b.cachedInputTokens), + cacheCreationTokens: Math.max(a.cacheCreationTokens, b.cacheCreationTokens), + outputTokens: Math.max(a.outputTokens, b.outputTokens), + reasoningTokens: Math.max(a.reasoningTokens, b.reasoningTokens), + }, + reportedCostUsd, + }; +} + +/** + * Grok reports each turn once, complete, so real copies are equal. A larger one is a deleted + * transcript's pre-v17 maximum over turns that shared a prompt id, whichever source it came from. + */ +function smallestGrokCopy(held: UsageRecord, copy: UsageRecord): UsageRecord { + const a = held.totals; + const b = copy.totals; + const reportedCostUsd = + held.reportedCostUsd === null || copy.reportedCostUsd === null + ? (held.reportedCostUsd ?? copy.reportedCostUsd) + : Math.min(held.reportedCostUsd, copy.reportedCostUsd); + return { + ...held, + totals: { + uncachedInputTokens: Math.min(a.uncachedInputTokens, b.uncachedInputTokens), + cachedInputTokens: Math.min(a.cachedInputTokens, b.cachedInputTokens), + cacheCreationTokens: Math.min(a.cacheCreationTokens, b.cacheCreationTokens), + outputTokens: Math.min(a.outputTokens, b.outputTokens), + reasoningTokens: Math.min(a.reasoningTokens, b.reasoningTokens), + }, + reportedCostUsd, + }; +} + +interface Contribution { + record: UsageRecord; + /** Null when the first copy fell outside the window. */ + readonly bucket: MutableBucket | null; +} + /** Deduplicates across the whole scan; Claude copies records into resumed/forked transcripts. */ export class UsageAggregator { readonly #buckets = new Map(); - readonly #seen = new Set(); + readonly #seen = new Map(); readonly #toDay: (timestampMs: number) => string; readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null; readonly #options: AggregateOptions; @@ -167,20 +250,38 @@ export class UsageAggregator { if (!keepsUsageRecord(this.#options.modelFilter, input)) return false; const record = this.#mapModel(input); if (record.dedupeKey !== null) { - if (this.#seen.has(record.dedupeKey)) { + const held = this.#seen.get(record.dedupeKey); + if (held !== undefined) { this.#duplicatesDropped += 1; + if (held.bucket !== null) { + held.record = + record.provider === "grok" + ? smallestGrokCopy(held.record, record) + : mergeUsageCopies(held.record, record); + } return false; } - this.#seen.add(record.dedupeKey); } + const bucket = this.#placeInWindow(record, sourcePath ?? ""); + if (record.dedupeKey !== null) this.#seen.set(record.dedupeKey, { record, bucket }); + if (bucket === null) { + this.#outOfWindow += 1; + return false; + } + // Keyed usage is counted in finish(), once all its copies are merged. + if (record.dedupeKey === null) this.#accumulate(bucket, record); + if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId); + return true; + } + + #placeInWindow(record: UsageRecord, source: string): MutableBucket | null { if ( this.#hourlyWindow !== null && (record.timestampMs < this.#hourlyWindow.sinceTimeMs || record.timestampMs >= this.#hourlyWindow.untilTimeMs) ) { - this.#outOfWindow += 1; - return false; + return null; } const day = this.#toDay(record.timestampMs); @@ -188,16 +289,17 @@ export class UsageAggregator { this.#hourlyWindow === null && (day < this.#options.sinceDay || day > this.#options.untilDay) ) { - this.#outOfWindow += 1; - return false; + return null; } const hourIndex = this.#hourlyWindow === null ? -1 : Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS); - const bucket = this.#bucketFor(day, hourIndex, record.provider, record.model, sourcePath ?? ""); + return this.#bucketFor(day, hourIndex, record.provider, record.model, source); + } + #accumulate(bucket: MutableBucket, record: UsageRecord): void { const priced = priceUsage(this.#options.rates, record, this.#options.priceOverrides); const totals = bucket.totals; @@ -229,18 +331,27 @@ export class UsageAggregator { this.#options.priceOverrides, ); bucket.records += 1; - if (priced.costSource === "unpriced") bucket.unpricedRecords += 1; + if (priced.costSource === "unpriced") { + bucket.unpricedRecords += 1; + bucket.unpricedTokens += + record.totals.uncachedInputTokens + + record.totals.cachedInputTokens + + record.totals.cacheCreationTokens + + record.totals.outputTokens; + } if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1; - if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId); - return true; } - // Aliases use the target's rate, replacing provider-specific rateModel. + // Aliases use the target's rate. Only an unpriced target goes through the provider's own rate naming. #mapModel(record: UsageRecord): UsageRecord { const model = this.#options.modelAliases?.get(record.model); if (model === undefined) return record; const { rateModel: _rateModel, ...rest } = record; - return { ...rest, model }; + const rateModel = + lookupRate(this.#options.rates, model) === null + ? this.#options.rateModel?.(record.provider, model) + : undefined; + return rateModel === undefined ? { ...rest, model } : { ...rest, model, rateModel }; } // Time-ordered records usually reuse the previous bucket; avoid rebuilding its key. @@ -278,6 +389,7 @@ export class UsageAggregator { speedPremiumUsd: 0, records: 0, unpricedRecords: 0, + unpricedTokens: 0, providerReportedRecords: 0, sessions: new Set(), }; @@ -288,6 +400,10 @@ export class UsageAggregator { } finish(): AggregateResult { + for (const { record, bucket } of this.#seen.values()) { + if (bucket !== null) this.#accumulate(bucket, record); + } + this.#seen.clear(); const buckets: UsageBucket[] = []; for (const [key, bucket] of this.#buckets) { const [day = "", hourStart = "", provider = "", model = "", sourcePath = ""] = @@ -321,6 +437,7 @@ export class UsageAggregator { costSource: resolveCostSource(bucket), records: bucket.records, unpricedRecords: bucket.unpricedRecords, + unpricedTokens: bucket.unpricedTokens, sessions: bucket.sessions.size, }); } diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index dc0f37cf13..9aff0eb194 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -75,6 +75,14 @@ describe("usage pricing", () => { }); }); + it("falls back to the display model when the rate model is unlisted", () => { + const table = parseRateTable({ "example-model": rate(1e-6, 0.1e-6) }); + const unlisted = { ...record("example-model"), rateModel: "reseller/example-model" }; + + expect(priceUsage(table, unlisted)).toEqual(priceUsage(table, record("example-model"))); + expect(cacheSavingsUsd(table, unlisted)).toBeCloseTo(0.9); + }); + it("prices unknown models offline and uses input prices for omitted cache rates", () => { const table = parseRateTable({}); const overrides = createOverrideRateTable({ @@ -195,6 +203,104 @@ describe("usage pricing", () => { expect(cost("gpt-6-sol", "ultrafast")).toBe(cost("gpt-6-sol", "standard")); }); + it("prices a request above the model's long-context threshold at its above-tier rates", () => { + const table = parseRateTable({ + "claude-haiku-5-5": { + input_cost_per_token: 1e-6, + output_cost_per_token: 5e-6, + cache_read_input_token_cost: 1e-7, + cache_creation_input_token_cost: 1.25e-6, + input_cost_per_token_above_100k_tokens: 2e-6, + output_cost_per_token_above_100k_tokens: 7.5e-6, + cache_read_input_token_cost_above_100k_tokens: 2e-7, + cache_creation_input_token_cost_above_100k_tokens: 2.5e-6, + }, + "gpt-6-sol": { + ...rate(2e-6, 2e-7), + input_cost_per_token_priority: 4e-6, + output_cost_per_token_priority: 2e-5, + cache_read_input_token_cost_priority: 4e-7, + input_cost_per_token_above_272k_tokens_priority: 8e-6, + output_cost_per_token_above_272k_tokens_priority: 3e-5, + cache_read_input_token_cost_above_272k_tokens_priority: 8e-7, + }, + }); + const longRequest = ( + model: string, + speed: UsageSpeed, + totals: { uncached: number; cacheRead: number; cacheWrite: number; output: number }, + ) => ({ + model, + speed, + reportedCostUsd: null, + totals: { + uncachedInputTokens: totals.uncached, + cachedInputTokens: totals.cacheRead, + cacheCreationTokens: totals.cacheWrite, + outputTokens: totals.output, + reasoningTokens: 0, + }, + }); + + // The Claude prompt is input + cache read + cache write: 120K, above the 100K tier. + expect + .soft( + priceUsage( + table, + longRequest("claude-haiku-5-5", "standard", { + uncached: 10_000, + cacheRead: 100_000, + cacheWrite: 10_000, + output: 1_000, + }), + ).costUsd, + ) + .toBeCloseTo(10_000 * 2e-6 + 100_000 * 2e-7 + 10_000 * 2.5e-6 + 1_000 * 7.5e-6, 12); + expect( + priceUsage( + table, + longRequest("gpt-6-sol", "fast", { + uncached: 20_000, + cacheRead: 280_000, + cacheWrite: 0, + output: 1_000, + }), + ).costUsd, + ).toBeCloseTo(20_000 * 8e-6 + 280_000 * 8e-7 + 1_000 * 3e-5, 12); + }); + + it("bills the long-context tier only above its threshold, filling missing tier fields from base", () => { + const table = parseRateTable({ + "gpt-6-sol": { + input_cost_per_token: 2e-6, + output_cost_per_token: 1e-5, + cache_read_input_token_cost: 2e-7, + input_cost_per_token_priority: 4e-6, + output_cost_per_token_priority: 2e-5, + input_cost_per_token_above_272k_tokens: 4e-6, + }, + }); + const cost = (prompt: number, speed: UsageSpeed = "standard") => + priceUsage(table, { + model: "gpt-6-sol", + speed, + reportedCostUsd: null, + totals: { + uncachedInputTokens: prompt - 200_000, + cachedInputTokens: 200_000, + cacheCreationTokens: 0, + outputTokens: 1_000, + reasoningTokens: 0, + }, + }).costUsd; + + expect(cost(272_000)).toBeCloseTo(72_000 * 2e-6 + 200_000 * 2e-7 + 1_000 * 1e-5, 12); + // Output keeps the base rate; cache reads keep the base discount relative to input. + expect(cost(272_001)).toBeCloseTo(72_001 * 4e-6 + 200_000 * 4e-7 + 1_000 * 1e-5, 12); + // Without a priority long-context rate, priority requests keep the priority rate. + expect(cost(272_001, "fast")).toBeCloseTo(72_001 * 4e-6 + 200_000 * 4e-7 + 1_000 * 2e-5, 12); + }); + it("keeps the canonical Fable rate separate from DeepInfra in either order", () => { const canonical = ["claude-fable-5", rate(1e-5, 1e-6)] as const; const deepInfra = ["deepinfra/anthropic/claude-fable-5", rate(1e-5)] as const; @@ -239,8 +345,12 @@ describe("usage pricing", () => { ...rate(1), input_cost_per_token_priority: 2, output_cost_per_token_priority: 10, + input_cost_per_token_above_272k_tokens: 2, + input_cost_per_token_above_272k_tokens_priority: 4, + output_cost_per_token_above_272k_tokens_priority: 20, }, - "provider-b/example-model": rate(1), + "provider-b/example-model": { ...rate(1), input_cost_per_token_above_272k_tokens: 2 }, + "provider-c/example-model": rate(1), }); expect(lookupRate(table, "example-model")).toEqual( diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 609a573f54..a9ffc69164 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -12,33 +12,51 @@ export interface TokenRates { readonly outputCostPerToken: number; readonly cacheReadCostPerToken: number; readonly cacheCreationCostPerToken: number; + /** Cache writes with a 1-hour TTL; the 5-minute rate when unpublished. */ + readonly cacheCreation1hCostPerToken: number; } -/** Omits LiteLLM's above_272k_tokens, flex and batches variants, which transcripts do not record. */ -export interface ModelRate extends TokenRates { +interface SpeedRates extends TokenRates { readonly fast: TokenRates | null; readonly ultrafast: TokenRates | null; } +/** A request whose prompt exceeds `thresholdTokens` bills every token at this tier. */ +interface ContextTier { + readonly thresholdTokens: number; + readonly rate: SpeedRates; +} + +/** Omits LiteLLM's flex and batches variants, which transcripts do not record. */ +export interface ModelRate extends SpeedRates { + /** Sorted by descending threshold. */ + readonly contextTiers: readonly ContextTier[]; +} + export type RateTable = ReadonlyMap; export function createOverrideRateTable( overrides: Readonly>, ): RateTable { return new Map( - Object.entries(overrides).map(([model, prices]) => [ - model.trim(), - { - inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000, - outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000, - cacheReadCostPerToken: - (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, - cacheCreationCostPerToken: - (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, - fast: null, - ultrafast: null, - }, - ]), + Object.entries(overrides).map(([model, prices]) => { + const cacheCreationCostPerToken = + (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000; + return [ + model.trim(), + { + inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000, + outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000, + cacheReadCostPerToken: + (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, + cacheCreationCostPerToken, + cacheCreation1hCostPerToken: cacheCreationCostPerToken, + fast: null, + ultrafast: null, + contextTiers: [], + }, + ]; + }), ); } @@ -48,27 +66,38 @@ function finiteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } -// Missing cache rates fall back to input pricing; Anthropic normally discounts reads and charges extra for writes. +// Missing cache rates fall back to input pricing, and a missing 1-hour write rate to the 5-minute one. function readTokenRates( entry: LiteLlmEntry, suffix: string, standard?: TokenRates, + outputFallback?: number, ): TokenRates | null { const input = finiteNumber(entry[`input_cost_per_token${suffix}`]); - const output = finiteNumber(entry[`output_cost_per_token${suffix}`]); + const output = finiteNumber(entry[`output_cost_per_token${suffix}`]) ?? outputFallback ?? null; if (input === null || output === null) return null; - const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") => + const cacheRate = ( + name: string, + field: "cacheReadCostPerToken" | "cacheCreationCostPerToken" | "cacheCreation1hCostPerToken", + fallback = input, + ) => finiteNumber(entry[`${name}${suffix}`]) ?? (standard !== undefined && standard.inputCostPerToken > 0 ? (standard[field] / standard.inputCostPerToken) * input - : input); + : fallback); + const cacheCreationCostPerToken = cacheRate( + "cache_creation_input_token_cost", + "cacheCreationCostPerToken", + ); return { inputCostPerToken: input, outputCostPerToken: output, cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"), - cacheCreationCostPerToken: cacheRate( - "cache_creation_input_token_cost", - "cacheCreationCostPerToken", + cacheCreationCostPerToken, + cacheCreation1hCostPerToken: cacheRate( + "cache_creation_input_token_cost_above_1hr", + "cacheCreation1hCostPerToken", + cacheCreationCostPerToken, ), }; } @@ -79,6 +108,7 @@ function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates { outputCostPerToken: rates.outputCostPerToken * multiple, cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple, cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple, + cacheCreation1hCostPerToken: rates.cacheCreation1hCostPerToken * multiple, }; } @@ -89,6 +119,40 @@ function fastMultiplier(entry: LiteLlmEntry): number | null { return fast !== null && fast > 0 ? fast : null; } +function readSpeedRates(entry: LiteLlmEntry, standard: TokenRates, suffix = ""): SpeedRates { + const multiple = fastMultiplier(entry); + return { + ...standard, + fast: + multiple === null + ? readTokenRates(entry, `${suffix}_priority`, standard) + : scaleTokenRates(standard, multiple), + ultrafast: readTokenRates(entry, `${suffix}_ultrafast`, standard), + }; +} + +const CONTEXT_TIER_INPUT_KEY = + /^input_cost_per_token_above_(\d{1,7})k_tokens(?:_priority|_ultrafast)?$/; + +// Fields a tier omits fall back to base rates, so a priority-only tier still prices standard requests at base. +function readContextTiers(entry: LiteLlmEntry, base: TokenRates): ContextTier[] { + const thresholds = new Set(); + for (const key of Object.keys(entry)) { + const match = CONTEXT_TIER_INPUT_KEY.exec(key); + if (match !== null) thresholds.add(match[1]!); + } + return [...thresholds] + .map((threshold) => { + const suffix = `_above_${threshold}k_tokens`; + const standard = readTokenRates(entry, suffix, base, base.outputCostPerToken) ?? base; + return { + thresholdTokens: Number(threshold) * 1_000, + rate: readSpeedRates(entry, standard, suffix), + }; + }) + .toSorted((a, b) => b.thresholdTokens - a.thresholdTokens); +} + // LiteLLM prefixes for the model makers' own APIs; their price beats a cloud's or reseller's for a bare name. const FIRST_PARTY_PROVIDERS = new Set([ "anthropic", @@ -113,14 +177,9 @@ export function parseRateTable(document: unknown): RateTable { const key = normalizeRateKey(name); if (key.length === 0) continue; - const multiple = fastMultiplier(entry); table.set(key, { - ...standard, - fast: - multiple === null - ? readTokenRates(entry, "_priority", standard) - : scaleTokenRates(standard, multiple), - ultrafast: readTokenRates(entry, "_ultrafast", standard), + ...readSpeedRates(entry, standard), + contextTiers: readContextTiers(entry, standard), }); } @@ -150,12 +209,13 @@ function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean { a.inputCostPerToken === b.inputCostPerToken && a.outputCostPerToken === b.outputCostPerToken && a.cacheReadCostPerToken === b.cacheReadCostPerToken && - a.cacheCreationCostPerToken === b.cacheCreationCostPerToken + a.cacheCreationCostPerToken === b.cacheCreationCostPerToken && + a.cacheCreation1hCostPerToken === b.cacheCreation1hCostPerToken ); } -// Resellers often omit speed tiers, so a missing tier fills from the other entry instead of conflicting. -function mergeAliasRate(a: ModelRate, b: ModelRate): ModelRate | null { +// Resellers often omit speed and context tiers, so a missing tier fills from the other entry instead of conflicting. +function mergeSpeedRates(a: SpeedRates, b: SpeedRates): SpeedRates | null { const fast = a.fast ?? b.fast; const ultrafast = a.ultrafast ?? b.ultrafast; if ( @@ -168,8 +228,39 @@ function mergeAliasRate(a: ModelRate, b: ModelRate): ModelRate | null { return { ...a, fast, ultrafast }; } -function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates { - return (speed === "standard" ? null : rate[speed]) ?? rate; +function mergeContextTiers( + a: readonly ContextTier[], + b: readonly ContextTier[], +): readonly ContextTier[] | null { + if (a.length === 0) return b; + if (b.length === 0) return a; + if (a.length !== b.length) return null; + const merged: ContextTier[] = []; + for (const [index, tier] of a.entries()) { + const other = b[index]!; + const rate = mergeSpeedRates(tier.rate, other.rate); + if (tier.thresholdTokens !== other.thresholdTokens || rate === null) return null; + merged.push({ thresholdTokens: tier.thresholdTokens, rate }); + } + return merged; +} + +function mergeAliasRate(a: ModelRate, b: ModelRate): ModelRate | null { + const speeds = mergeSpeedRates(a, b); + const contextTiers = mergeContextTiers(a.contextTiers, b.contextTiers); + return speeds === null || contextTiers === null ? null : { ...speeds, contextTiers }; +} + +function promptTokens(totals: UsageTokenTotals): number { + return totals.uncachedInputTokens + totals.cachedInputTokens + totals.cacheCreationTokens; +} + +// A tier without the requested speed keeps the base tier's rate for that speed. +function ratesAt(rate: ModelRate, speed: UsageSpeed, totals: UsageTokenTotals): TokenRates { + const prompt = promptTokens(totals); + const tier = rate.contextTiers.find((tier) => prompt > tier.thresholdTokens)?.rate; + if (speed === "standard") return tier ?? rate; + return tier?.[speed] ?? rate[speed] ?? tier ?? rate; } function normalizeRateKey(model: string): string { @@ -219,6 +310,14 @@ export function lookupRate(table: RateTable, model: string): ModelRate | null { return rate; } +/** A priceable model the table has no rate for; a newer table may list it. */ +export function isUnlistedModel(table: RateTable, model: string): boolean { + const bareName = bareModelName(stripVariantSuffix(normalizeRateKey(model))); + return ( + bareName.length > 0 && !UNPRICEABLE_MODELS.has(bareName) && lookupRate(table, model) === null + ); +} + function resolveRate(table: RateTable, model: string): ModelRate | null { const key = stripVariantSuffix(normalizeRateKey(model)); const bareName = bareModelName(key); @@ -228,9 +327,14 @@ function resolveRate(table: RateTable, model: string): ModelRate | null { export type PricedRecord = Pick< UsageRecord, - "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd" + "model" | "rateModel" | "totals" | "cacheCreation1hTokens" | "speed" | "reportedCostUsd" >; +function recordRate(table: RateTable, record: PricedRecord): ModelRate | null { + const rate = record.rateModel === undefined ? null : lookupRate(table, record.rateModel); + return rate ?? lookupRate(table, record.model); +} + export interface PricedUsage { readonly costUsd: number; readonly costSource: UsageCostSource; @@ -238,11 +342,15 @@ export interface PricedUsage { readonly speedPremiumUsd: number; } -function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost { +function costByCategory(record: PricedRecord, rates: TokenRates): UsageCategoryCost { + const { totals } = record; + const oneHour = Math.min(record.cacheCreation1hTokens ?? 0, totals.cacheCreationTokens); return { input: totals.uncachedInputTokens * rates.inputCostPerToken, cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken, - cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken, + cacheWrite: + (totals.cacheCreationTokens - oneHour) * rates.cacheCreationCostPerToken + + oneHour * rates.cacheCreation1hCostPerToken, output: totals.outputTokens * rates.outputCostPerToken, }; } @@ -269,16 +377,18 @@ export function priceUsage( categoryCostUsd: null, speedPremiumUsd: 0, }); - const rate = override ?? lookupRate(table, record.rateModel ?? model); + const rate = override ?? recordRate(table, record); if (rate === null) { return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported"); } - const listCost = costByCategory(totals, ratesAt(rate, record.speed)); + const listCost = costByCategory(record, ratesAt(rate, record.speed, totals)); const listCostUsd = sumCategories(listCost); if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported"); const premiumUsd = - record.speed === "standard" ? 0 : listCostUsd - sumCategories(costByCategory(totals, rate)); + record.speed === "standard" + ? 0 + : listCostUsd - sumCategories(costByCategory(record, ratesAt(rate, "standard", totals))); const scale = reported === null ? 1 : reported / listCostUsd; return { costUsd: reported ?? listCostUsd, @@ -298,9 +408,8 @@ export function cacheSavingsUsd( record: PricedRecord, overrides?: RateTable, ): number { - const rate = - overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model); + const rate = overrides?.get(record.model.trim()) ?? recordRate(table, record); if (rate === null) return 0; - const rates = ratesAt(rate, record.speed); + const rates = ratesAt(rate, record.speed, record.totals); return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken); } diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index d0e5eaceec..36864768eb 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -65,7 +65,15 @@ describe("scan cache round trip", () => { [ "/a.jsonl", 100, - [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", speed: "fast" })], + [ + record(), + record({ + dedupeKey: "msg_2:", + model: "claude-opus-5-5", + speed: "fast", + cacheCreation1hTokens: 8, + }), + ], ], [ "/b.jsonl", @@ -160,7 +168,7 @@ describe("scan cache round trip", () => { expect(restored).toEqual(original); }); - it.each([5, 6, 7, 8, 10])( + it.each([5, 6, 7, 8, 10, 11, 12, 13])( "retains v%s history and compatible positions but invalidates obsolete state", (version) => { const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]); @@ -218,7 +226,7 @@ describe("scan cache round trip", () => { const restored = decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP); expect(restored.get("/gone.jsonl")).toEqual( - version >= 10 + version >= 13 ? original.get("/gone.jsonl") : { ...original.get("/gone.jsonl"), @@ -233,7 +241,7 @@ describe("scan cache round trip", () => { }); expect(restored.get("/clean-codex.jsonl")).toEqual({ ...cleanCodex, - size: version >= 8 ? cleanCodex.size : -1, + size: -1, position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); expect(restored.get("/gone-pi.jsonl")).toEqual( @@ -248,11 +256,82 @@ describe("scan cache round trip", () => { }, ); - it("re-parses a Claude transcript cached before advisor usage was counted", () => { + it("re-parses a v14 Codex entry that skipped records and restarts a clean one when it grows", () => { + const codex = (malformedRecords: number): CachedFile => ({ + size: 10, + mtimeMs: 100, + provider: "codex", + records: [record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null })], + tailRecords: [], + malformedRecords, + position: position({ + state: { ...initialCodexScanState(), model: "gpt-6-astra", sessionId: "session-a" }, + }), + }); + const original: ScanCache = new Map([ + ["/skipped-codex.jsonl", codex(1)], + ["/clean-codex.jsonl", codex(0)], + ]); + const v14 = { ...parse(makeScanCacheWriter()(original, {})), version: 14 }; + + const restored = decodeScanCache(JSON.parse(JSON.stringify(v14)), TEST_FORMAT_MAP); + expect(restored.get("/skipped-codex.jsonl")).toEqual({ + ...codex(1), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); + // Served while unchanged, but its state predates the latest snapshot time, so it cannot resume. + expect(restored.get("/clean-codex.jsonl")).toEqual({ + ...codex(0), + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); + // The migrated entries persist without a state and load again under the current version. + expect(decodeScanCache(parse(makeScanCacheWriter()(restored, {})), TEST_FORMAT_MAP)).toEqual( + restored, + ); + }); + + it("restarts a grown v15 Codex entry, whose baseline time can be older than its totals", () => { + const request = { + input_tokens: 100, + cached_input_tokens: 0, + cache_write_input_tokens: 0, + output_tokens: 20, + reasoning_output_tokens: 0, + total_tokens: 120, + }; + const entry: CachedFile = { + size: 10, + mtimeMs: 100, + provider: "codex", + records: [record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null })], + tailRecords: [], + malformedRecords: 0, + position: position({ + state: { + ...initialCodexScanState(), + model: "gpt-6-astra", + lastCumulativeUsage: request, + latestCumulativeAtMs: 1_786_000_000_000, + }, + }), + }; + const current = parse(makeScanCacheWriter()(new Map([["/codex.jsonl", entry]]), {})); + + expect( + decodeScanCache({ ...current, version: 15 }, TEST_FORMAT_MAP).get("/codex.jsonl"), + ).toEqual({ + ...entry, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); + expect(decodeScanCache(current, TEST_FORMAT_MAP).get("/codex.jsonl")).toEqual(entry); + }); + + it("re-parses a Claude transcript cached before 1-hour cache writes were counted", () => { const original = cacheWith([["/claude.jsonl", 100, [record()]]]); - const v9 = { ...parse(makeScanCacheWriter()(original, {})), version: 9 }; + const v12 = { ...parse(makeScanCacheWriter()(original, {})), version: 12 }; - const restored = decodeScanCache(JSON.parse(JSON.stringify(v9)), TEST_FORMAT_MAP); + const restored = decodeScanCache(JSON.parse(JSON.stringify(v12)), TEST_FORMAT_MAP); expect(restored.get("/claude.jsonl")).toEqual({ ...original.get("/claude.jsonl"), size: -1, @@ -260,6 +339,29 @@ describe("scan cache round trip", () => { }); }); + it.each(["s:p:grok-4.5", "s:p:1786000000000:grok-4.5"])( + "re-parses v16 Grok transcripts with key %s", + (dedupeKey) => { + const original = cacheWith([ + ["/grok/updates.jsonl", 100, [record({ provider: "grok", model: "grok-4.5", dedupeKey })]], + ]); + original.set("/grok/updates.jsonl", { + ...original.get("/grok/updates.jsonl")!, + provider: "grok", + }); + const encoded = parse(makeScanCacheWriter()(original, {})); + const restored = decodeScanCache({ ...encoded, version: 16 }, TEST_FORMAT_MAP); + expect(restored.get("/grok/updates.jsonl")).toEqual({ + ...original.get("/grok/updates.jsonl"), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + records: [ + record({ provider: "grok", model: "grok-4.5", dedupeKey: "s:p:1786000000000:grok-4.5" }), + ], + }); + }, + ); + it("rewrites only changed entries and still restores the whole cache", () => { const write = makeScanCacheWriter(); const cache = cacheWith([ diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index c2cdc1cbf5..843b414b97 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -7,9 +7,10 @@ import type { import * as Schema from "effect/Schema"; import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts"; +import { mergeUsageCopies } from "./usageAggregation.ts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -const USAGE_SCAN_CACHE_VERSION = 11 as const; +const USAGE_SCAN_CACHE_VERSION = 17 as const; const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** @@ -17,8 +18,14 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; * replace it, dropping saved usage for deleted transcripts. Separate files keep * the newer one; older files are removed once it is saved. */ -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v11.json"; +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v17.json"; export const LEGACY_SCAN_CACHE_FILE_NAMES = [ + "usage-scan-cache-v16.json", + "usage-scan-cache-v15.json", + "usage-scan-cache-v14.json", + "usage-scan-cache-v13.json", + "usage-scan-cache-v12.json", + "usage-scan-cache-v11.json", "usage-scan-cache-v10.json", "usage-scan-cache-v9.json", "usage-scan-cache-v8.json", @@ -57,7 +64,8 @@ type SerializedRecord = readonly [ reportedCostUsd: number | null, speed: number, rateModelIndex?: number | null, - unresolvedServiceTierTurnId?: string, + unresolvedServiceTierTurnId?: string | null, + cacheCreation1hTokens?: number, ]; interface SerializedFile { @@ -116,9 +124,11 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile record.rateModel === undefined ? null : intern(tables.models, tables.modelIndex, record.rateModel), - ...(record.unresolvedServiceTierTurnId === undefined - ? ([] as const) - : ([record.unresolvedServiceTierTurnId] as const)), + ...(record.cacheCreation1hTokens !== undefined + ? ([record.unresolvedServiceTierTurnId ?? null, record.cacheCreation1hTokens] as const) + : record.unresolvedServiceTierTurnId !== undefined + ? ([record.unresolvedServiceTierTurnId] as const) + : ([] as const)), ]; return { s: entry.size, @@ -209,6 +219,7 @@ export function decodeScanCache( speedIndex, rateModelIndex, unresolvedServiceTierTurnId, + cacheCreation1h = 0, ] = row as SerializedRecord; const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined; @@ -218,8 +229,8 @@ export function decodeScanCache( typeof timestampMs !== "number" || !Number.isFinite(timestampMs) || model === undefined || - (unresolvedServiceTierTurnId !== undefined && - typeof unresolvedServiceTierTurnId !== "string") || + (unresolvedServiceTierTurnId != null && typeof unresolvedServiceTierTurnId !== "string") || + !Number.isFinite(cacheCreation1h) || (rateModelIndex != null && rateModel === undefined) || !Number.isFinite(uncached) || !Number.isFinite(cached) || @@ -248,12 +259,22 @@ export function decodeScanCache( outputTokens: output, reasoningTokens: reasoning, }, + ...(cacheCreation1h > 0 ? { cacheCreation1hTokens: cacheCreation1h } : {}), reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null, speed, - ...(version >= 7 && unresolvedServiceTierTurnId !== undefined + ...(version >= 7 && unresolvedServiceTierTurnId != null ? { unresolvedServiceTierTurnId } : {}), - dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null, + dedupeKey: + typeof dedupeKey !== "string" + ? null + : // Saved copies of moved transcripts must still match the re-parsed v17 key. + provider === "grok" && + version < 17 && + dedupeKey.endsWith(`:${model}`) && + !dedupeKey.endsWith(`:${timestampMs}:${model}`) + ? `${dedupeKey.slice(0, -model.length)}${timestampMs}:${model}` + : dedupeKey, }); } return records; @@ -288,19 +309,22 @@ export function decodeScanCache( continue; } // Keep history for deleted rollouts, but re-parse incompatible reducer state. - // v9 and v11 repair skipped Codex requests; clean v8+ entries stay served while unchanged. - // v10 adds Claude advisor calls, which no older Claude entry holds. + // v13 adds Claude 1-hour cache writes; v14 uses Codex request ledgers. + // v15 repairs skipped Codex requests whose counters rewound; clean v14 entries stay served. + // v17 keys Grok turns by time, restoring turns previously dropped as repeats. const legacy = - (entry.p === "claude" && version < 10) || + (entry.p === "claude" && version < 13) || + (entry.p === "grok" && version < 17) || (format.state !== undefined && (version < 6 || - (entry.p === "codex" && (version < 8 || (version < 11 && malformedRecords > 0))))); + (entry.p === "codex" && (version < 14 || (version < 15 && malformedRecords > 0))))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; - // Before v11 a clean scan could end past an interrupted request whose usage its state dropped, - // so a grown file re-parses whole instead of resuming. - const resumable = !legacy && !(entry.p === "codex" && version < 11); + // Before v16 a Codex baseline can lack the time of its latest move, or carry an older one, + // and that time keeps a re-emitted older snapshot from billing twice. A grown file re-parses + // whole instead of resuming. + const resumable = !legacy && !(entry.p === "codex" && version < 16); const provider = entry.p; const records = decodeRecords(entry.r, provider); @@ -353,16 +377,18 @@ export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): num return removed; } -/** Mutates seen; share it across incremental line/tail batches to deduplicate the whole file. */ -export function dedupeWithinFile( - records: readonly UsageRecord[], - seen: Set = new Set(), -): readonly UsageRecord[] { +/** Pass only newline-terminated records: an unterminated tail can still change, so the aggregator merges it per scan. */ +export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] { const kept: UsageRecord[] = []; + const firstIndex = new Map(); for (const record of records) { if (record.dedupeKey !== null) { - if (seen.has(record.dedupeKey)) continue; - seen.add(record.dedupeKey); + const index = firstIndex.get(record.dedupeKey); + if (index !== undefined) { + kept[index] = mergeUsageCopies(kept[index]!, record); + continue; + } + firstIndex.set(record.dedupeKey, kept.length); } kept.push(record); } diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index 105884d81c..ca994dd3ac 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -13,6 +13,8 @@ import * as Schema from "effect/Schema"; import { TEST_FORMATS } from "./usageTestFormats.ts"; import { listTranscriptFiles, + physicalSourceIdOf, + readPhysicalSourceId, readTranscriptRecords, transcriptLineGate, } from "./usageTranscriptReader.ts"; @@ -99,6 +101,30 @@ describe("compressed transcripts", () => { assert.isAbove(listed.files.find((file) => file.path === compressed)?.size ?? 0, 0); }); + it("lists files in directory order when more directories wait than it reads at once", async () => { + for (let index = 0; index < 40; index += 1) { + const nested = NodePath.join(dir, `project-${index}`, "sessions"); + await NodeFSP.mkdir(nested, { recursive: true }); + await NodeFSP.writeFile(NodePath.join(nested, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(nested, "..", "b.jsonl"), ""); + } + // Usage that two transcripts share counts in the first one listed, so the order is part of the result. + const inOrder = async (folder: string): Promise => { + const paths: string[] = []; + for (const entry of await NodeFSP.readdir(folder, { withFileTypes: true })) { + const child = NodePath.join(folder, entry.name); + if (entry.isDirectory()) paths.push(...(await inOrder(child))); + else paths.push(child); + } + return paths; + }; + const listed = await listTranscriptFiles(dir, 0); + assert.deepStrictEqual( + listed.files.map((file) => file.path), + await inOrder(dir), + ); + }); + it.each([ { parser: "native", streamingThresholdBytes: undefined }, { parser: "projected", streamingThresholdBytes: 1024 }, @@ -553,3 +579,49 @@ describe("transcriptLineGate", () => { } }); }); + +describe("readPhysicalSourceId", () => { + const scope = "0123456789abcdef0123456789abcdef"; + const windowsPath = "C:\\Users\\User\\.claude\\projects"; + + // One NTFS directory the Windows server reads natively and the WSL server + // through drvfs. The temp dir stands in for the drive's mount point. + async function drvfsFixture(extraMounts: (escapedMountPoint: string) => string = () => "") { + const mountPoint = NodePath.join(dir, "drive c"); + await NodeFSP.mkdir(NodePath.join(mountPoint, "Users", "User", ".claude", "projects"), { + recursive: true, + }); + const escaped = mountPoint.replaceAll(" ", "\\040"); + const mountInfoPath = NodePath.join(dir, "mountinfo"); + await NodeFSP.writeFile( + mountInfoPath, + [ + "24 1 8:32 / / rw,relatime shared:1 - ext4 /dev/sdc rw,discard", + `81 24 0:61 / ${escaped} rw,noatime shared:2 - 9p C:\\134 rw,dirsync,aname=drvfs;path=C:\\;uid=1000;gid=1000;symlinkroot=/mnt/,mmap,access=client,msize=65536,trans=fd`, + extraMounts(escaped), + ].join("\n"), + ); + return { mountPoint, mountInfoPath }; + } + + it("names a drvfs directory as the Windows server names it, whatever its typed case", async () => { + const { mountPoint, mountInfoPath } = await drvfsFixture(); + const wslId = await readPhysicalSourceId( + `${mountPoint}/users/user/.claude/projects`, + scope, + "linux", + mountInfoPath, + ); + assert.strictEqual(wslId, physicalSourceIdOf(scope, windowsPath)); + }); + + it("gives no identity to native or shadowing Linux mounts, or without a desktop scope", async () => { + const { mountPoint, mountInfoPath } = await drvfsFixture( + (escaped) => `90 81 8:48 / ${escaped}/Users rw,relatime - ext4 /dev/sdd rw`, + ); + const projects = `${mountPoint}/Users/User/.claude/projects`; + assert.isUndefined(await readPhysicalSourceId(projects, scope, "linux", mountInfoPath)); + assert.isUndefined(await readPhysicalSourceId(dir, scope, "linux", mountInfoPath)); + assert.isUndefined(await readPhysicalSourceId(projects, undefined, "linux", mountInfoPath)); + }); +}); diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index 38b80d36c8..5b92f48356 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -1,8 +1,11 @@ // @effect-diagnostics nodeBuiltinImport:off // Cold windows span ~1.4 GB/1,500 files; node:fs buffer streaming is ~10x cheaper than materializing files. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeStringDecoder from "node:string_decoder"; +import * as NodeUtil from "node:util"; import * as NodeZlib from "node:zlib"; import type { @@ -41,8 +44,12 @@ export interface TranscriptParseResult { export const GUARD_LENGTH = 64; const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024; +const READ_CHUNK_BYTES = 256 * 1024; const NEWLINE = 0x0a; const STAT_CONCURRENCY = 32; +const WALK_CONCURRENCY = 16; +// Measured about 3x faster than the promise API's stat across 20,000 transcripts. +const statFile = NodeUtil.promisify(NodeFS.stat); const CARRIAGE_RETURN = 0x0d; function selectUsageFields(fields: SelectedFields) { @@ -71,38 +78,54 @@ export async function listTranscriptFiles( root: string, sinceMs: number, options?: { readonly fileName?: string }, -): Promise<{ readonly files: readonly TranscriptFile[]; readonly failedPaths: number }> { +): Promise<{ + readonly files: readonly TranscriptFile[]; + readonly walked: readonly string[]; + readonly failedPaths: number; +}> { const fileName = options?.fileName; - const candidates: string[] = []; let failedPaths = 0; - const walk = async (dir: string): Promise => { + let reading = 0; + const waiting: Array<() => void> = []; + // Sibling directories read together; each returns its own list so the result keeps readdir order. + const walk = async (dir: string): Promise => { + if (reading < WALK_CONCURRENCY) reading += 1; + else await new Promise((resume) => waiting.push(resume)); let entries; try { entries = await NodeFSP.readdir(dir, { withFileTypes: true }); } catch { failedPaths += 1; - return; - } - for (const entry of entries) { - const child = NodePath.join(dir, entry.name); - if (entry.isDirectory()) await walk(child); - else if ( - fileName !== undefined - ? entry.name === fileName - : entry.name.endsWith(".jsonl") || entry.name.endsWith(".jsonl.zst") - ) { - candidates.push(child); - } + return []; + } finally { + // A waiting directory takes over this slot, so the count only drops when none waits. + const next = waiting.shift(); + if (next === undefined) reading -= 1; + else next(); } + const found = await Promise.all( + entries.map((entry) => { + const child = NodePath.join(dir, entry.name); + if (entry.isDirectory()) return walk(child); + return ( + fileName !== undefined + ? entry.name === fileName + : entry.name.endsWith(".jsonl") || entry.name.endsWith(".jsonl.zst") + ) + ? [child] + : []; + }), + ); + return found.flat(); }; - await walk(root); + const candidates = await walk(root); const found: Array = Array.from({ length: candidates.length }); const queue = candidates.entries(); const statQueued = async (): Promise => { for (const [index, path] of queue) { try { - const stats = await NodeFSP.stat(path); + const stats = await statFile(path); if (stats.mtimeMs >= sinceMs) { found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs }; } @@ -116,7 +139,7 @@ export async function listTranscriptFiles( await Promise.all( Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued), ); - return { files: found.filter((file) => file !== undefined), failedPaths }; + return { files: found.filter((file) => file !== undefined), walked: candidates, failedPaths }; } export async function readDirectoryVolumeId(path: string): Promise { @@ -128,6 +151,137 @@ export async function readDirectoryVolumeId(path: string): Promise { } } +/** + * Set by the desktop app, from a value it persists, on its Windows server and + * the WSL server it manages, so both can name one Windows directory alike + * without merging separate machines that share a hostname and path. + */ +export const DESKTOP_HOST_SCOPE_ENV = "T3CODE_DESKTOP_HOST_SCOPE"; + +const MOUNT_FIELD_ESCAPE = /\\([0-7]{3})/g; +const WINDOWS_ROOT = /^(?:[A-Za-z]:|\\\\[^\\]+\\[^\\]+)\\?$/; + +const unescapeMountField = (field: string) => + field.replace(MOUNT_FIELD_ESCAPE, (_, octal: string) => + String.fromCharCode(Number.parseInt(octal, 8)), + ); + +const normalizeWindowsPath = (path: string) => + (/^[a-z]:/.test(path) ? path[0]!.toUpperCase() + path.slice(1) : path).replace(/\\$/, ""); + +/** + * The Windows directory behind the deepest mount holding `dir`, read from + * `/proc/self/mountinfo` so a custom automount root resolves and an ext4 + * mount under `/mnt` never passes for a drive. + */ +function windowsMountFor( + mountInfo: string, + dir: string, +): { readonly mountPoint: string; readonly windowsRoot: string } | undefined { + let deepest: { mountPoint: string; windowsRoot: string | undefined } | undefined; + for (const line of mountInfo.split("\n")) { + const fields = line.split(" "); + const separator = fields.indexOf("-", 6); + if (separator === -1) continue; + const mountPoint = unescapeMountField(fields[4] ?? ""); + const contains = + mountPoint === "/" || + dir === mountPoint || + dir.startsWith(mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`); + if (!contains || (deepest !== undefined && deepest.mountPoint.length > mountPoint.length)) { + continue; + } + // WSL2 mounts drives over 9p with `aname=drvfs;path=C:\`; WSL1 as `drvfs`. + const options = (fields[separator + 3] ?? "").split(/[,;]/); + const source = options.includes("aname=drvfs") + ? options.find((option) => option.startsWith("path="))?.slice("path=".length) + : fields[separator + 1] === "drvfs" + ? unescapeMountField(fields[separator + 2] ?? "") + : undefined; + const root = unescapeMountField(fields[3] ?? "/") + .split("/") + .filter(Boolean); + deepest = { + mountPoint, + windowsRoot: + source !== undefined && WINDOWS_ROOT.test(source) + ? [normalizeWindowsPath(source), ...root].join("\\") + : undefined, + }; + } + return deepest?.windowsRoot === undefined + ? undefined + : { mountPoint: deepest.mountPoint, windowsRoot: deepest.windowsRoot }; +} + +/** + * drvfs keeps the casing a path was typed with, while Windows reports the + * on-disk names. Read those names rather than folding case, which would join + * distinct entries of a case-sensitive directory. + */ +async function onDiskNames( + mountPoint: string, + parts: readonly string[], +): Promise { + const names: string[] = []; + let current = mountPoint; + for (const part of parts) { + let entries: string[]; + try { + entries = await NodeFSP.readdir(current); + } catch { + return undefined; + } + const folded = part.toUpperCase(); + const [name, ...others] = entries.includes(part) + ? [part] + : entries.filter((entry) => entry.toUpperCase() === folded); + if (name === undefined || others.length > 0) return undefined; + names.push(name); + current = NodePath.posix.join(current, name); + } + return names; +} + +export function physicalSourceIdOf(scope: string, windowsPath: string): string { + return NodeCrypto.createHash("sha256") + .update(`${scope}\0${windowsPath}`) + .digest("hex") + .slice(0, 32); +} + +/** + * Identifies a Windows directory the same way from the Windows server and from + * a WSL server reading it through drvfs. Directories that are not Windows + * backed, and servers the desktop app did not start, get none. + */ +export async function readPhysicalSourceId( + dir: string, + scope: string | undefined, + platform: NodeJS.Platform, + mountInfoPath = "/proc/self/mountinfo", +): Promise { + if (scope === undefined || scope.length === 0) return undefined; + try { + if (platform === "win32") { + // The native realpath reports on-disk casing; the JS one keeps the input's. + return physicalSourceIdOf(scope, normalizeWindowsPath(await NodeFSP.realpath(dir))); + } + if (platform !== "linux") return undefined; + const mount = windowsMountFor(await NodeFSP.readFile(mountInfoPath, "utf8"), dir); + if (mount === undefined) return undefined; + const names = await onDiskNames( + mount.mountPoint, + dir.slice(mount.mountPoint.length).split("/").filter(Boolean), + ); + return names === undefined + ? undefined + : physicalSourceIdOf(scope, [mount.windowsRoot, ...names].join("\\")); + } catch { + return undefined; + } +} + async function guardMatches( handle: NodeFSP.FileHandle, position: TranscriptParsePosition, @@ -147,6 +301,29 @@ async function guardMatches( } } +/** Plain files reuse one buffer, so a chunk is only valid until the next one is requested. */ +async function* readChunks( + handle: NodeFSP.FileHandle, + start: number, + compressed: boolean, +): AsyncGenerator { + if (compressed) { + // Compressed snapshots cache a full parse; decoded byte offsets cannot + // resume the compressed input. + yield* handle + .createReadStream({ start, autoClose: true, highWaterMark: READ_CHUNK_BYTES }) + .compose(NodeZlib.createZstdDecompress()); + return; + } + const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES); + for (let position = start; ;) { + const { bytesRead } = await handle.read(buffer, 0, buffer.length, position); + if (bytesRead === 0) return; + position += bytesRead; + yield buffer.subarray(0, bytesRead); + } +} + // Match markers in one latin1 alternation; one character per byte preserves exact ASCII offsets. export function transcriptLineGate(markers: readonly [string, ...string[]]) { if (markers.length === 1) { @@ -223,7 +400,8 @@ export async function readTranscriptRecords( const append = (segment: Buffer) => { if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) { - if (segment.length > 0) pendingChunks.push(segment); + // Copy: the next read overwrites the chunk this segment points into. + if (segment.length > 0) pendingChunks.push(Buffer.from(segment)); pendingBytes += segment.length; return; } @@ -254,15 +432,7 @@ export async function readTranscriptRecords( streaming = undefined; decoder = undefined; }; - const input = handle.createReadStream({ - start, - autoClose: compressed, - highWaterMark: 256 * 1024, - }); - // Compressed snapshots cache a full parse; decoded byte offsets cannot - // resume the compressed input. - const stream = compressed ? input.compose(NodeZlib.createZstdDecompress()) : input; - for await (const chunk of stream) { + for await (const chunk of readChunks(handle, start, compressed)) { let lineStart = 0; while (lineStart < chunk.length) { const newlineIndex = chunk.indexOf(NEWLINE, lineStart); diff --git a/apps/server/src/usage/usageTranscriptStreaming.test.ts b/apps/server/src/usage/usageTranscriptStreaming.test.ts index 856ba2ac5b..635b5ae4e6 100644 --- a/apps/server/src/usage/usageTranscriptStreaming.test.ts +++ b/apps/server/src/usage/usageTranscriptStreaming.test.ts @@ -254,7 +254,7 @@ describe("large usage records", () => { outputTokens: 99, reasoningTokens: 10, }, - dedupeKey: "s1:p1:grok-4.5-build", + dedupeKey: "s1:p1:1785578400123:grok-4.5-build", reportedCostUsd: 0.25, }); }); diff --git a/apps/server/src/utils/subscribeBeforeSnapshot.test.ts b/apps/server/src/utils/subscribeBeforeSnapshot.test.ts index 70f0beda25..e37b969a12 100644 --- a/apps/server/src/utils/subscribeBeforeSnapshot.test.ts +++ b/apps/server/src/utils/subscribeBeforeSnapshot.test.ts @@ -15,70 +15,66 @@ import { describe("subscribeBeforeSnapshot", () => { it.effect("atomically reads the initial snapshot before receiving later changes", () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* PubSub.sliding(1); - const latest = yield* Ref.make(1); - const mutex = yield* Semaphore.make(1); - const snapshotStarted = yield* Deferred.make(); - const finishSnapshot = yield* Deferred.make(); - const subscriptionFiber = yield* subscribeBeforeSnapshot( - changes, - Deferred.succeed(snapshotStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishSnapshot)), - Effect.andThen(Ref.get(latest)), - ), - mutex, - ).pipe(Effect.forkChild); + Effect.gen(function* () { + const changes = yield* PubSub.sliding(1); + const latest = yield* Ref.make(1); + const mutex = yield* Semaphore.make(1); + const snapshotStarted = yield* Deferred.make(); + const finishSnapshot = yield* Deferred.make(); + const subscriptionFiber = yield* subscribeBeforeSnapshot( + changes, + Deferred.succeed(snapshotStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishSnapshot)), + Effect.andThen(Ref.get(latest)), + ), + mutex, + ).pipe(Effect.forkChild); - yield* Deferred.await(snapshotStarted); - const publishFiber = yield* mutex - .withPermits(1)(Ref.set(latest, 2).pipe(Effect.andThen(PubSub.publish(changes, 2)))) - .pipe(Effect.forkChild); - yield* Deferred.succeed(finishSnapshot, undefined); + yield* Deferred.await(snapshotStarted); + const publishFiber = yield* mutex + .withPermits(1)(Ref.set(latest, 2).pipe(Effect.andThen(PubSub.publish(changes, 2)))) + .pipe(Effect.forkChild); + yield* Deferred.succeed(finishSnapshot, undefined); - const subscription = yield* Fiber.join(subscriptionFiber); - yield* Fiber.join(publishFiber); - const firstChange = yield* subscription.changes.pipe( - Stream.runHead, - Effect.timeout("1 second"), - ); + const subscription = yield* Fiber.join(subscriptionFiber); + yield* Fiber.join(publishFiber); + const firstChange = yield* subscription.changes.pipe( + Stream.runHead, + Effect.timeout("1 second"), + ); - expect(subscription.latest).toBe(1); - expect(firstChange).toEqual(Option.some(2)); - }), - ), + expect(subscription.latest).toBe(1); + expect(firstChange).toEqual(Option.some(2)); + }), ); it.effect("subscribes before an uncoordinated snapshot can change", () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* PubSub.sliding(1); - const latest = yield* Ref.make(1); - const snapshotStarted = yield* Deferred.make(); - const finishSnapshot = yield* Deferred.make(); - const subscriptionFiber = yield* subscribeBeforeSnapshotWithoutMutex( - changes, - Deferred.succeed(snapshotStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishSnapshot)), - Effect.andThen(Ref.get(latest)), - ), - ).pipe(Effect.forkChild); + Effect.gen(function* () { + const changes = yield* PubSub.sliding(1); + const latest = yield* Ref.make(1); + const snapshotStarted = yield* Deferred.make(); + const finishSnapshot = yield* Deferred.make(); + const subscriptionFiber = yield* subscribeBeforeSnapshotWithoutMutex( + changes, + Deferred.succeed(snapshotStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishSnapshot)), + Effect.andThen(Ref.get(latest)), + ), + ).pipe(Effect.forkChild); - yield* Deferred.await(snapshotStarted); - yield* Ref.set(latest, 2); - yield* PubSub.publish(changes, 2); - yield* Deferred.succeed(finishSnapshot, undefined); + yield* Deferred.await(snapshotStarted); + yield* Ref.set(latest, 2); + yield* PubSub.publish(changes, 2); + yield* Deferred.succeed(finishSnapshot, undefined); - const subscription = yield* Fiber.join(subscriptionFiber); - const firstChange = yield* subscription.changes.pipe( - Stream.runHead, - Effect.timeout("1 second"), - ); + const subscription = yield* Fiber.join(subscriptionFiber); + const firstChange = yield* subscription.changes.pipe( + Stream.runHead, + Effect.timeout("1 second"), + ); - expect(subscription.latest).toBe(2); - expect(firstChange).toEqual(Option.some(2)); - }), - ), + expect(subscription.latest).toBe(2); + expect(firstChange).toEqual(Option.some(2)); + }), ); }); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index d33c2b10ed..be57317954 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -1,3 +1,5 @@ +import * as NodeNet from "node:net"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Cause from "effect/Cause"; @@ -102,37 +104,65 @@ runVcsDriverContractSuite({ }, }); -it.effect("lists the fetch and push URLs of a partial clone remote", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-partial-clone-remotes-", - }); - const driver = yield* GitVcsDriver.makeVcsDriverShape(); - yield* runGit(cwd, ["init"]); - yield* runGit(cwd, ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"]); - yield* runGit(cwd, [ - "remote", - "set-url", - "--push", - "origin", - "git@github.com:octocat/t3code.git", - ]); - yield* runGit(cwd, ["config", "remote.origin.promisor", "true"]); - yield* runGit(cwd, ["config", "remote.origin.partialclonefilter", "blob:none"]); - - const result = yield* driver.listRemotes(cwd); - assert.deepEqual(result.remotes, [ - { - name: "origin", - url: "https://github.com/pingdotgg/t3code.git", - pushUrl: Option.some("git@github.com:octocat/t3code.git"), - isPrimary: true, - }, - ]); - }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +it.effect.each([ + { + fetchUrl: "https://github.com/pingdotgg/t3code.git", + pushUrl: "git@github.com:octocat/t3code.git", + lineEnding: "\n", + }, + { fetchUrl: "../team repos/shared.git", pushUrl: "../team repos/push.git", lineEnding: "\n" }, + { + fetchUrl: " ../team repos/shared (fetch) [blob:none].git ", + pushUrl: "../team repos/push (push).git\t", + lineEnding: "\r\n", + }, +])( + "lists the fetch and push URLs of a partial clone remote (%j)", + ({ fetchUrl, pushUrl, lineEnding }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-partial-clone-remotes-", + }); + const process = yield* VcsProcess.VcsProcess; + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => + process.run(input).pipe( + Effect.map((result) => ({ + ...result, + stdout: result.stdout.replace(/\r?\n/g, lineEnding), + })), + ), + }), + ); + yield* runGit(cwd, ["init"]); + yield* runGit(cwd, ["remote", "add", "origin", fetchUrl]); + yield* runGit(cwd, ["remote", "set-url", "--push", "origin", pushUrl]); + yield* runGit(cwd, ["config", "remote.origin.promisor", "true"]); + yield* runGit(cwd, ["config", "remote.origin.partialclonefilter", "blob:none"]); + + const result = yield* driver.listRemotes(cwd); + assert.deepEqual(result.remotes, [ + { + name: "origin", + url: fetchUrl, + pushUrl: Option.some(pushUrl), + isPrimary: true, + }, + ]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +interface UntrackedBlobChange { + readonly git: Effect.Success>["git"]; + readonly write: ( + relativePath: string, + contents: string, + ) => Effect.Effect; + readonly checkpointRef: CheckpointRef; +} + const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* ( driver: Effect.Success>, cwd: string, @@ -154,6 +184,519 @@ const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* ( return { git, checkpointRef }; }); +it.effect.each(["interrupt", "timeout", "success"] as const)( + "checkpoint bulk staging cleans operation-owned packs after $0 and can retry", + (stop) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const liveProcess = yield* VcsProcess.VcsProcess; + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bulk-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const originalCheckpoint = (yield* git(["rev-parse", checkpointRef])).stdout; + const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index")); + const originalHead = (yield* git(["rev-parse", "HEAD"])).stdout; + yield* git(["config", "core.bigFileThreshold", "1m"]); + const crypto = yield* SecureRandom.SecureRandom; + const payload = yield* crypto.randomBytes(2 * 1024 * 1024); + yield* fs.writeFile(path.join(cwd, "a-media.bin"), payload); + + // Git keeps bulk-checkin's pack open while the next path's clean filter runs. + // The socket is a barrier, not a race against the speed of compression. + const connected = Promise.withResolvers(); + const sockets = new Set(); + let released = false; + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + sockets.add(socket); + connected.resolve(socket); + // Git can run the filter again while refreshing the staged entry. + if (released) socket.end(); + }), + ), + (server) => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + assert.isTrue(address !== null && typeof address !== "string"); + if (address === null || typeof address === "string") return; + const filter = path.join(sandbox, "filter.cjs"); + yield* fs.writeFileString( + filter, + `const s = require('node:net').connect(${address.port}, '127.0.0.1'); s.resume(); process.stdin.resume(); s.on('end', () => process.exit(0));`, + ); + yield* git(["config", "filter.barrier.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.barrier.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "z-gate filter=barrier\n"); + yield* fs.writeFileString(path.join(cwd, "z-gate"), "gate\n"); + const sharedPack = path.join(cwd, ".git/objects/pack/tmp_pack_other_operation"); + yield* fs.writeFileString(sharedPack, "owned by another Git operation"); + let objectDirectory = path.join(cwd, ".git/objects"); + const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + if (input.args.includes("add") && input.env?.GIT_OBJECT_DIRECTORY) + objectDirectory = input.env.GIT_OBJECT_DIRECTORY; + return liveProcess.run(input); + }, + }), + ); + const fiber = yield* captureDriver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + const socket = yield* Effect.promise(() => connected.promise).pipe( + Effect.raceFirst( + Fiber.join(fiber).pipe( + Effect.flatMap((result) => + Exit.isFailure(result) + ? Effect.failCause(result.cause) + : Effect.die("capture ended before the filter connected"), + ), + ), + ), + ); + const packs = (yield* fs.readDirectory(path.join(objectDirectory, "pack"))).filter( + (name) => name.startsWith("tmp_pack_") && name !== "tmp_pack_other_operation", + ); + assert.strictEqual(packs.length, 1); + assert.isAbove( + Number((yield* fs.stat(path.join(objectDirectory, "pack", packs[0]!))).size), + 1024 * 1024, + ); + // An overlapping capture publishes the same large blob while the first + // still owns an unfinished pack. Its objects/ref must survive either exit. + const concurrentRef = CheckpointRef.make("refs/t3/checkpoints/concurrent"); + const concurrentDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => + liveProcess.run({ ...input, args: ["-c", "filter.barrier.clean=cat", ...input.args] }), + }), + ); + yield* concurrentDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef: concurrentRef }); + const concurrentOid = (yield* git(["rev-parse", concurrentRef])).stdout; + const sharedPackNames = (yield* fs.readDirectory(path.join(cwd, ".git/objects/pack"))).sort(); + const packName = sharedPackNames.find((name) => name.endsWith(".pack")); + assert.isDefined(packName); + const sharedPackBytes = yield* fs.readFile(path.join(cwd, ".git/objects/pack", packName!)); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + else if (stop === "timeout") yield* TestClock.adjust("30 seconds"); + released = true; + socket.end(); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else if (stop === "timeout") { + assert.isTrue(Exit.isSuccess(result)); + if (Exit.isSuccess(result)) { + assert.isTrue(Exit.isFailure(result.value)); + if (Exit.isFailure(result.value)) { + const error = Cause.findErrorOption(result.value.cause); + assert.isTrue(Option.isSome(error) && error.value._tag === "VcsProcessTimeoutError"); + } + } + } else assert.isTrue(Exit.isSuccess(result) && Exit.isSuccess(result.value)); + assert.deepEqual( + (yield* fs.readDirectory(path.join(cwd, ".git/objects/pack"))).sort(), + sharedPackNames, + ); + assert.deepEqual( + yield* fs.readFile(path.join(cwd, ".git/objects/pack", packName!)), + sharedPackBytes, + ); + assert.strictEqual((yield* git(["rev-parse", concurrentRef])).stdout, concurrentOid); + assert.isFalse(yield* fs.exists(path.join(objectDirectory, "pack", packs[0]!))); + assert.isFalse(yield* fs.exists(objectDirectory)); + assert.strictEqual(yield* fs.readFileString(sharedPack), "owned by another Git operation"); + if (stop !== "success") + assert.strictEqual((yield* git(["rev-parse", checkpointRef])).stdout, originalCheckpoint); + assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex); + assert.strictEqual((yield* git(["rev-parse", "HEAD"])).stdout, originalHead); + assert.deepEqual(yield* fs.readFile(path.join(cwd, "a-media.bin")), payload); + + yield* git(["config", "filter.barrier.clean", "cat"]); + yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + assert.isFalse(yield* fs.exists(objectDirectory)); + const blob = (yield* git(["hash-object", "a-media.bin"])).stdout.trim(); + assert.strictEqual( + (yield* git(["rev-parse", `${checkpointRef}:a-media.bin`])).stdout.trim(), + blob, + ); + yield* fs.remove(sharedPack); + yield* git(["fsck", "--full"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect.each(["failure", "interrupt"] as const)( + "checkpoint publication $0 preserves existing refs and permits retry", + (stop) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-publish-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const previous = (yield* git(["show-ref"])).stdout; + yield* fs.writeFileString(path.join(cwd, "new.txt"), "new checkpoint content\n"); + const published = yield* Deferred.make(); + const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + link: (source, destination) => + fs.link(source, destination).pipe( + Effect.andThen(Deferred.succeed(published, undefined)), + Effect.andThen( + stop === "interrupt" + ? Effect.never + : Effect.fail( + PlatformError.systemError({ + _tag: "BadResource", + module: "FileSystem", + method: "link", + }), + ), + ), + ), + }), + ); + const fiber = yield* captureDriver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Deferred.await(published); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else { + assert.isTrue(Exit.isSuccess(result) && Exit.isFailure(result.value)); + if (Exit.isSuccess(result) && Exit.isFailure(result.value)) { + const error = Cause.findErrorOption(result.value.cause); + assert.isTrue( + Option.isSome(error) && + error.value._tag === "VcsCheckpointStorageError" && + error.value.stage === "publish", + ); + } + } + assert.strictEqual((yield* git(["show-ref"])).stdout, previous); + assert.deepEqual( + (yield* fs.readDirectory(path.join(cwd, ".git/objects"))).filter((name) => + name.startsWith("tmp_objdir-t3-checkpoint-"), + ), + [], + ); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + assert.strictEqual( + (yield* git(["show", `${checkpointRef}:new.txt`])).stdout, + "new checkpoint content\n", + ); + yield* git(["fsck", "--full"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect.each([ + { stop: "before git restore spawns", gate: "restore", index: "staged", file: "later\n" }, + { stop: "after git restore ran", gate: "clean", index: "head", file: "unstaged\n" }, +] as const)( + "checkpoint restore interrupted $stop leaves the $index index", + ({ gate, index, file }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const liveProcess = yield* VcsProcess.VcsProcess; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-restore-interrupt-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + yield* fs.writeFileString(path.join(cwd, "file.txt"), "later\n"); + yield* git(["add", "file.txt"]); + const stagedTree = (yield* git(["write-tree"])).stdout; + const entered = yield* Deferred.make(); + const gatedDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => + input.operation === "GitVcsDriver.checkpoints.restoreCheckpoint" && + input.args.includes(gate) + ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never)) + : liveProcess.run(input), + }), + ); + const fiber = yield* gatedDriver.checkpoints + .restoreCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Deferred.await(entered); + yield* Fiber.interrupt(fiber); + const result = yield* Fiber.await(fiber); + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + + assert.strictEqual( + (yield* git(["write-tree"])).stdout, + index === "head" ? (yield* git(["rev-parse", "HEAD^{tree}"])).stdout : stagedTree, + ); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "file.txt")), file); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint publication falls back to rename where hardlinks are unavailable", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-publish-no-links-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* git(["config", "core.bigFileThreshold", "1m"]); + yield* fs.writeFile(path.join(cwd, "media.bin"), yield* crypto.randomBytes(2 * 1024 * 1024)); + const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + link: () => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "link", + }), + ), + }), + ); + yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const files = yield* fs.readDirectory(path.join(cwd, ".git/objects/pack")); + assert.isTrue(files.some((name) => name.endsWith(".pack"))); + assert.isTrue(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef })); + assert.match((yield* git(["count-objects", "-v"])).stdout, /^garbage: 0$/m); + yield* git(["fsck", "--full"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "checkpoint publication preserves Git's shared object directory permissions", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-publish-shared-" }); + const git = (args: ReadonlyArray) => + driver.execute({ operation: "test.shared", cwd, args }); + yield* git(["init", "--shared=0660"]); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/shared"); + yield* fs.writeFileString(path.join(cwd, "shared.txt"), "new shared object\n"); + const blob = (yield* git(["hash-object", "-w", "shared.txt"])).stdout.trim(); + const directory = path.join(cwd, ".git/objects", blob.slice(0, 2)); + const expectedMode = (yield* fs.stat(directory)).mode & 0o7777; + yield* fs.remove(directory, { recursive: true }); + assert.isFalse(yield* fs.exists(directory)); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + assert.strictEqual((yield* fs.stat(directory)).mode & 0o7777, expectedMode); + yield* git(["fsck", "--full"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint capture ignores an inherited object directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-inherited-objects-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + const unrelated = path.join(sandbox, "unrelated"); + yield* git(["init", "--bare", unrelated]); + const unrelatedObjects = path.join(unrelated, "objects"); + // VcsProcess clears inherited selectors from git children; only the driver sees this one. + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }).pipe( + Effect.provideService(HostProcess.Environment, { + ...(yield* HostProcess.Environment), + GIT_OBJECT_DIRECTORY: unrelatedObjects, + }), + ); + assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n"); + assert.deepEqual( + (yield* fs.readDirectory(unrelatedObjects)).filter( + (name) => name !== "info" && name !== "pack", + ), + [], + ); + yield* git(["fsck", "--full"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect.each([ + { name: "nothing changed", reuses: true, change: () => Effect.void }, + { + name: "its conversion attributes changed while it was being captured", + reuses: false, + change: () => Effect.void, + during: ({ write }: UntrackedBlobChange) => + Effect.orDie(write(".gitattributes", "*.txt text eol=lf\n")), + }, + { + name: "its conversion config changed while it was being captured", + reuses: false, + change: () => Effect.void, + during: ({ git }: UntrackedBlobChange) => + Effect.orDie(Effect.asVoid(git(["config", "core.autocrlf", "true"]))), + }, + { + name: "its conversion attributes changed", + reuses: false, + change: ({ write }: UntrackedBlobChange) => write(".gitattributes", "*.txt text eol=lf\n"), + }, + { + name: "a clean filter named like an unset attribute now applies to it", + reuses: false, + change: ({ git, write }: UntrackedBlobChange) => + write(".git/info/attributes", "*.txt filter=unspecified\n").pipe( + Effect.andThen(git(["config", "filter.unspecified.clean", "tr a-z A-Z"])), + ), + }, + { + name: "its conversion config changed", + reuses: false, + change: ({ git }: UntrackedBlobChange) => git(["config", "core.autocrlf", "true"]), + }, + { + name: "it was rewritten at the same size", + reuses: false, + change: ({ write }: UntrackedBlobChange) => + write("nested/large.txt", "LINE\r\n".repeat(3 * 1024 * 1024)), + }, + { + name: "it became ignored", + reuses: false, + change: ({ write }: UntrackedBlobChange) => write(".gitignore", "nested/\n"), + }, + { + name: "HEAD now tracks it", + reuses: false, + change: ({ git }: UntrackedBlobChange) => + git(["add", "nested/large.txt"]).pipe(Effect.andThen(git(["commit", "-m", "track"]))), + }, + { + name: "its directory became a repository", + reuses: false, + change: ({ git }: UntrackedBlobChange) => + git(["init", "nested"]).pipe( + Effect.andThen( + git( + ["-C", "nested", "-c", "user.name=Test", "-c", "user.email=test@test.com"].concat([ + "commit", + "--allow-empty", + "-m", + "nested", + ]), + ), + ), + ), + }, + { + name: "its blob was pruned", + reuses: false, + change: ({ git, checkpointRef }: UntrackedBlobChange) => + git(["update-ref", "-d", checkpointRef]).pipe(Effect.andThen(git(["prune", "--expire=now"]))), + }, +])( + "checkpoint capture skips hashing an untracked file only while a fresh hash would match: $name", + ({ reuses, change, during }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveProcess = yield* VcsProcess.VcsProcess; + let reused = 0; + let afterPublish: Effect.Effect = Effect.void; + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + if (input.args.includes("core.ignorestat=true")) reused++; + // Only a capture whose staging took real time looks for files to remember. + if (input.args.includes("add")) + return liveProcess.run(input).pipe(Effect.tap(() => TestClock.adjust("1 second"))); + // The files are hashed and published by now, but not yet remembered. + return input.args.includes("update-ref") + ? liveProcess.run(input).pipe(Effect.tap(() => afterPublish)) + : liveProcess.run(input); + }, + }), + ); + // A driver that has never captured this workspace hashes every file, as a first capture does. + const fresh = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-untracked-blobs-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + const write = (relativePath: string, contents: string) => + fs.writeFileString(path.join(cwd, relativePath), contents); + yield* fs.makeDirectory(path.join(cwd, "nested")); + yield* write("nested/large.txt", "line\r\n".repeat(3 * 1024 * 1024)); + // Only files left alone for a few seconds before a capture are remembered. + yield* TestClock.adjust("36500 days"); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + // A file is remembered by the first capture that read its conversion rules before hashing it. + if (during !== undefined) afterPublish = during({ git, write, checkpointRef }); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + afterPublish = Effect.void; + + yield* change({ git, write, checkpointRef }); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const freshRef = CheckpointRef.make("refs/t3/checkpoints/fresh"); + yield* fresh.checkpoints.captureCheckpoint({ cwd, checkpointRef: freshRef }); + + assert.strictEqual(reused, reuses ? 1 : 0); + assert.strictEqual( + (yield* git(["rev-parse", `${checkpointRef}^{tree}`])).stdout, + (yield* git(["rev-parse", `${freshRef}^{tree}`])).stdout, + ); + yield* git(["fsck", "--connectivity-only"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect.each(["sha1", "sha256"] as const)( + "checkpoint object isolation supports linked worktrees with $0 objects", + (format) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-worktree-" }); + // A separator must remain part of the alternate's path, not split the list. + const platform = yield* HostProcess.Platform; + const cwd = path.join(sandbox, platform === "win32" ? "repo;space" : 'repo:space"\u0001'); + yield* fs.makeDirectory(cwd); + yield* driver.execute({ + operation: "test.init", + cwd, + args: ["init", `--object-format=${format}`], + }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + const worktree = path.join(sandbox, "linked"); + yield* git(["worktree", "add", "-b", "linked", worktree]); + yield* fs.writeFileString(path.join(worktree, "untracked.txt"), "linked worktree\n"); + const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index")); + yield* driver.checkpoints.captureCheckpoint({ cwd: worktree, checkpointRef }); + assert.strictEqual( + (yield* git(["show", `${checkpointRef}:untracked.txt`])).stdout, + "linked worktree\n", + ); + assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex); + yield* git(["fsck", "--full"]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("checkpoint capture skips untracked nested repositories without a commit", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -842,6 +1385,63 @@ it.effect.each([1_700_000_000, 1_700_000_000.9999])( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("a branch switch landing after the snapshot belongs to the next checkpoint", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveProcess = yield* VcsProcess.VcsProcess; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-switch-race-" }); + const git = (args: ReadonlyArray) => + driver.execute({ operation: "checkpoint-test", cwd, args }); + yield* git(["init"]); + yield* git(["config", "user.name", "Test"]); + yield* git(["config", "user.email", "test@test.com"]); + yield* fileSystem.writeFileString(path.join(cwd, "f.txt"), "A\n"); + yield* git(["add", "."]); + yield* git(["commit", "-m", "a"]); + yield* git(["checkout", "-b", "b"]); + yield* fileSystem.writeFileString(path.join(cwd, "f.txt"), "B\n"); + yield* git(["commit", "-am", "b"]); + yield* git(["checkout", "-"]); + const [first, second, third] = ["1", "2", "3"].map((turn) => + CheckpointRef.make(`refs/t3/checkpoints/switch-race/${turn}`), + ) as [CheckpointRef, CheckpointRef, CheckpointRef]; + const racedDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) { + const result = yield* liveProcess.run(input); + if (input.args.includes("write-tree")) yield* git(["checkout", "b"]).pipe(Effect.orDie); + return result; + }), + }), + ); + const changedSince = (fromCheckpointRef: CheckpointRef, toCheckpointRef: CheckpointRef) => + Effect.gen(function* () { + const refs = { cwd, fromCheckpointRef, toCheckpointRef }; + return { + patch: yield* driver.checkpoints.diffCheckpoints({ ...refs, ignoreWhitespace: false }), + authored: yield* driver.checkpoints.listAuthoredPaths(refs), + }; + }); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: first }); + yield* racedDriver.checkpoints.captureCheckpoint({ + cwd, + checkpointRef: second, + previousCheckpointRef: first, + }); + yield* driver.checkpoints.captureCheckpoint({ + cwd, + checkpointRef: third, + previousCheckpointRef: second, + }); + + assert.deepEqual(yield* changedSince(first, second), { patch: "", authored: null }); + assert.deepEqual(yield* changedSince(second, third), { patch: "", authored: null }); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("checkpoint capture preserves racy edits made after resetting the index", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1032,6 +1632,7 @@ it.effect.each(["committed", "unborn"] as const)( assert.deepStrictEqual(commands, [ "rev-parse", + ...(head === "committed" ? ["log"] : []), "config", ...(head === "committed" ? ["read-tree", "ls-files"] : []), "add", @@ -1097,6 +1698,8 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "write-tree", "commit-tree", "update-ref", + // Without a parsed top level, capture cannot rule out submodules. + "submodule", ]); assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n"); assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex); @@ -1254,6 +1857,154 @@ it.effect("restores a checkpoint before the first commit without staging its fil }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("restores edits to skip-worktree files whose checkpoint content matches HEAD", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-skip-worktree-restore-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + const skippedPath = path.join(cwd, "skipped.txt"); + yield* fileSystem.writeFileString(skippedPath, "original\n"); + yield* git(["add", "skipped.txt"]); + yield* git(["commit", "-m", "add skipped file"]); + yield* git(["update-index", "--skip-worktree", "skipped.txt"]); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + yield* fileSystem.writeFileString(skippedPath, "later\n"); + + assert.isTrue( + yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }), + ); + + assert.strictEqual(yield* fileSystem.readFileString(skippedPath), "original\n"); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("sparse restore rewrites manual skip-worktree files and keeps exclusions absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveProcess = yield* VcsProcess.VcsProcess; + // One byte per chunk, so the index listing splits inside every record. + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + const onStdoutChunk = input.onStdoutChunk; + return liveProcess.run( + onStdoutChunk === undefined + ? input + : { + ...input, + onStdoutChunk: (chunk) => { + for (let index = 0; index < chunk.length; index++) + onStdoutChunk(chunk.subarray(index, index + 1)); + }, + }, + ); + }, + }), + ); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sparse-restore-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + for (const name of ["in/normal", "in/skipped", "in/s space", "out/deep/absent", "out/stray"]) { + yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true }); + yield* fs.writeFileString(path.join(cwd, name), "original\n"); + } + yield* git(["add", "."]); + yield* git(["commit", "-m", "sparse fixture"]); + yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "in"]); + // Keeps Git from clearing the bit on files that are present. + yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]); + yield* git(["update-index", "--skip-worktree", "in/skipped", "in/s space"]); + const captureCwd = path.join(cwd, "in"); + yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef }); + yield* fs.writeFileString(path.join(cwd, "in/skipped"), "later\n"); + yield* fs.writeFileString(path.join(cwd, "in/s space"), "later\n"); + yield* fs.writeFileString(path.join(cwd, "in/normal"), "later\n"); + + for (const restoreCwd of [captureCwd, cwd]) { + assert.isTrue( + yield* driver.checkpoints.restoreCheckpoint({ + cwd: restoreCwd, + checkpointRef, + fallbackToHead: false, + }), + ); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/skipped")), "original\n"); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/s space")), "original\n"); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/normal")), "original\n"); + assert.isFalse(yield* fs.exists(path.join(cwd, "out"))); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("restores and deletes checkpoints inside populated submodules", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const git = (cwd: string, args: ReadonlyArray) => + driver.execute({ operation: "test", cwd, args }); + const makeRepository = Effect.fn("makeRepository")(function* (prefix: string) { + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix }); + yield* git(cwd, ["init"]); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "original\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "initial"]); + return cwd; + }); + const nested = yield* makeRepository("t3-submodule-nested-"); + const library = yield* makeRepository("t3-submodule-library-"); + const addSubmodule = (cwd: string, url: string, name: string) => + git(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", url, name]).pipe( + Effect.andThen(git(cwd, ["commit", "-m", `add ${name}`])), + ); + yield* addSubmodule(library, nested, "nested"); + const root = yield* makeRepository("t3-submodule-root-"); + yield* addSubmodule(root, library, "library"); + yield* git(root, [ + "-c", + "protocol.file.allow=always", + "submodule", + "update", + "--init", + "--recursive", + ]); + const files = ["file.txt", "library/file.txt", "library/nested/file.txt"].map((file) => + path.join(root, file), + ); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/submodules"); + yield* fileSystem.writeFileString(files[1]!, "captured\n"); + yield* driver.checkpoints.captureCheckpoint({ cwd: root, checkpointRef }); + + for (const file of files) { + yield* fileSystem.writeFileString(file, "changed\n"); + yield* fileSystem.writeFileString(`${file}.added`, "new\n"); + } + assert.isTrue( + yield* driver.checkpoints.restoreCheckpoint({ + cwd: root, + checkpointRef, + fallbackToHead: false, + }), + ); + + assert.deepStrictEqual( + yield* Effect.forEach(files, (file) => fileSystem.readFileString(file)), + ["original\n", "captured\n", "original\n"], + ); + for (const file of files) assert.isFalse(yield* fileSystem.exists(`${file}.added`)); + + yield* driver.checkpoints.deleteCheckpointRefs({ cwd: root, checkpointRefs: [checkpointRef] }); + for (const cwd of [root, path.join(root, "library"), path.join(root, "library", "nested")]) { + const ref = yield* git(cwd, ["for-each-ref", "refs/t3"]); + assert.strictEqual(ref.stdout, ""); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + // The real VCS process, spawning `command` wherever the driver runs git. const vcsProcessSpawning = (command: string) => Layer.effect( @@ -1316,6 +2067,128 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); +it.effect("GitVcsDriver fails repository probes when git cannot read the repository config", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-bad-config-" }); + // The included file's path appears in Git's message and must not read as "no repository". + const includeDir = path.join(root, "not a git repository"); + yield* fileSystem.makeDirectory(includeDir); + yield* fileSystem.writeFileString(path.join(includeDir, "included"), "invalid config\n"); + const configs = { + direct: "invalid config\n", + included: `[include]\n\tpath = ${path.join(includeDir, "included")}\n`, + }; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/bad-config/0"); + + for (const [name, config] of Object.entries(configs)) { + const cwd = path.join(root, name); + yield* fileSystem.makeDirectory(cwd); + yield* runGit(cwd, ["init"]); + yield* fileSystem.writeFileString(path.join(cwd, ".git", "config"), config); + const outcomes = { + isInsideWorkTree: Exit.isFailure(yield* Effect.exit(driver.isInsideWorkTree(cwd))), + detectRepository: Exit.isFailure(yield* Effect.exit(driver.detectRepository(cwd))), + hasCheckpointRef: Exit.isFailure( + yield* Effect.exit(driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef })), + ), + }; + assert.deepStrictEqual( + outcomes, + { isInsideWorkTree: true, detectRepository: true, hasCheckpointRef: true }, + `a bad ${name} config is an operational failure, not an absent repository or ref`, + ); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("GitVcsDriver reports no repository for a deleted cwd or a bare repository", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-no-work-tree-" }); + const bare = path.join(root, "bare.git"); + yield* fileSystem.makeDirectory(bare); + yield* runGit(bare, ["init", "--bare"]); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + + for (const cwd of [path.join(root, "deleted"), bare]) { + assert.equal(yield* driver.isInsideWorkTree(cwd), false, cwd); + assert.equal(yield* driver.detectRepository(cwd), null, cwd); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +// Git outputs CI's Git version cannot produce with a real repository. +const makeStubbedDriver = Effect.fn("test.makeStubbedDriver")(function* (output: { + readonly code: number; + readonly stdout: string; + readonly stderr: string; +}) { + const process = yield* VcsProcess.make.pipe( + Effect.provideService(ProcessRunner.ProcessRunner, { + run: () => + Effect.succeed({ + ...output, + code: ChildProcessSpawner.ExitCode(output.code), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }), + }), + ); + return yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, process), + ); +}); + +it.effect("GitVcsDriver reports no repository when old Git answers false before failing", () => + Effect.gen(function* () { + // Git before 2.38 ignores safe.bareRepository, so a bare repo prints "false" and exits 128. + const driver = yield* makeStubbedDriver({ + code: 128, + stdout: "false\n", + stderr: "fatal: this operation must be run in a work tree\n", + }); + + assert.equal(yield* driver.detectRepository(globalThis.process.cwd()), null); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("GitVcsDriver fails a checkpoint ref lookup when git cannot read its object", () => + Effect.gen(function* () { + const driver = yield* makeStubbedDriver({ + code: 1, + stdout: "", + stderr: "error: unable to open loose object 0733271782d6: Permission denied\n", + }); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/unreadable/0"); + + const exit = yield* Effect.exit( + driver.checkpoints.hasCheckpointRef({ cwd: globalThis.process.cwd(), checkpointRef }), + ); + assert.isTrue(Exit.isFailure(exit), "an unreadable checkpoint object is not an absent ref"); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("GitVcsDriver reads an absent checkpoint ref as absent despite a Git warning", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-git-warning-" }); + yield* runGit(cwd, ["init"]); + // Valid legacy config that makes every Git command print a deprecation warning. + yield* runGit(cwd, ["config", "core.fsyncObjectFiles", "true"]); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/absent/0"); + + assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef })); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + const gitCommandCount = (operation: string, outcome: string) => Metric.value( Metric.withAttributes(gitCommandsTotal, [ diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index ff129690b7..d0da1b3d09 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1,9 +1,11 @@ import * as NodeBuffer from "node:buffer"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -12,6 +14,7 @@ import { ChildProcessSpawner } from "effect/process"; import { GitCommandError, + VcsCheckpointStorageError, VcsProcessExitError, VcsUnsupportedOperationError, type VcsSwitchRefInput, @@ -37,12 +40,14 @@ import { } from "@t3tools/contracts"; import { isMissingExecutable } from "@t3tools/source-control-core/server/discovery"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; import { makeGitVcsDriverCore, PATCH_RENDER_PREFIX_ARGS, splitNullSeparatedGitStdoutPaths, } from "./GitVcsDriverCore.ts"; import * as CheckoutCloner from "./CheckoutCloner.ts"; +import * as CheckpointUntrackedBlobs from "./checkpointUntrackedBlobs.ts"; import * as VcsDriver from "./VcsDriver.ts"; import * as VcsProcess from "./VcsProcess.ts"; @@ -54,7 +59,6 @@ export interface ExecuteGitInput { readonly env?: NodeJS.ProcessEnv; readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number | null; - readonly forceKillAfterMs?: number; readonly maxOutputBytes?: number; readonly appendTruncationMarker?: boolean; /** With appendTruncationMarker, line callbacks continue beyond the buffer cap for progress-only consumers. */ @@ -122,7 +126,10 @@ export interface ExecuteGitProgress { } export interface CreateWorktreeProgress { - /** Git refuses existing paths; claimed paths belong to this call and can be removed on cancel. */ + /** + * Runs uninterruptibly once the worktree exists; from then on the caller owns its cleanup. + * For new-branch calls on Git supporting add --reason, cancellation before the claim removes what it made. + */ readonly onWorktreeClaimed?: (path: string) => Effect.Effect; readonly onCheckoutProgress?: (input: { percent: number; @@ -178,12 +185,16 @@ export interface GitPushResult { status: "pushed" | "skipped_up_to_date"; branch: string; upstreamBranch?: string | undefined; + /** Set when `upstreamBranch` is on a configured push remote instead of the tracked upstream. */ + pushRemote?: string | undefined; setUpstream?: boolean | undefined; } export interface GitPushTarget { remoteName: string; branchName: string; + /** The tracked upstream is current, yet pushes go to this configured push remote. */ + viaPushRemote: boolean; } export interface GitRangeContext { @@ -328,6 +339,8 @@ export class GitVcsDriver extends Context.Service< cwd: string, options?: GitRemoteStatusOptions, ) => Effect.Effect; + /** Refs, HEAD and shallow boundaries. Null when the snapshot cannot be read. */ + readonly readRefSnapshot: (cwd: string) => Effect.Effect; readonly prepareCommitContext: ( cwd: string, filePaths?: readonly string[], @@ -459,6 +472,8 @@ export class GitVcsDriver extends Context.Service< input: VcsSwitchRefInput, ) => Effect.Effect; readonly initRepo: (input: VcsInitInput) => Effect.Effect; + /** Drops cached refs after something outside this driver changed them, such as a clone into `cwd`. */ + readonly invalidateRefs: (cwd: string) => Effect.Effect; readonly listLocalBranchNames: (cwd: string) => Effect.Effect; } >()("t3/vcs/GitVcsDriver") {} @@ -468,6 +483,10 @@ const FLAGGED_INDEX_ENTRIES_MAX_BYTES = 1024 * 1024; const CHECKPOINT_RECOVERY_MAX_CANDIDATES = 64; const CHECKPOINT_RECOVERY_TIMEOUT = "5 seconds"; const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; +// Reflog subjects that only point a ref at an existing commit. Anything else counts as creating +// one, so an unknown subject keeps its commit attributed. +const REF_MOVE_REFLOG_SUBJECT = + /^(?:$|(?:checkout|reset|branch|clone|fetch)\b|[^:]*\((?:start|finish|abort|reset)\): |(?:merge|pull|rebase|cherry-pick)\b[^()]*: fast-forward$)/i; const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [ "-c", "core.fsmonitor=false", @@ -518,14 +537,10 @@ function parseGitRemoteVerboseOutput( output: string, ): Map { const remotes = new Map(); - for (const line of output.split("\n")) { - const trimmed = line.trim(); - if (trimmed.length === 0) { - continue; - } - + for (const line of output.split(/\r?\n/)) { + // Git uses a tab before the URL and one space before the direction; both can occur in URLs. // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. - const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed); + const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line); if (!match) { continue; } @@ -547,6 +562,13 @@ function parseGitRemoteVerboseOutput( return remotes; } +// Trace output and deprecation warnings can precede Git's own message, so check every line. +const hasStderrLine = (stderr: string, prefixes: ReadonlyArray) => + stderr.split("\n").some((line) => prefixes.some((prefix) => line.startsWith(prefix))); + +/** Operation of the error raised when Git cannot say whether a cwd is a work tree. */ +export const WORK_TREE_PROBE_OPERATION = "GitVcsDriver.probeWorkTree"; + const gitCommand = Effect.fn("GitVcsDriver.gitCommand")( ( process: VcsProcess.VcsProcess["Service"], @@ -555,6 +577,7 @@ const gitCommand = Effect.fn("GitVcsDriver.gitCommand")( args: ReadonlyArray, options?: { readonly stdin?: string; + readonly onSpawn?: () => void; readonly env?: NodeJS.ProcessEnv; readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number; @@ -570,6 +593,7 @@ const gitCommand = Effect.fn("GitVcsDriver.gitCommand")( cwd, spawnCwd: globalThis.process.cwd(), ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}), + ...(options?.onSpawn !== undefined ? { onSpawn: options.onSpawn } : {}), ...(options?.env !== undefined ? { env: options.env } : {}), ...(options?.allowNonZeroExit !== undefined ? { allowNonZeroExit: options.allowNonZeroExit } @@ -583,31 +607,65 @@ const gitCommand = Effect.fn("GitVcsDriver.gitCommand")( }), ); +const HEAD_MOVES_SCAN_LIMIT = 512; +const HEAD_MARK_TRAILER = "T3-Head-Moved-At"; +const HEAD_MARK_TRAILER_PATTERN = new RegExp(`^${HEAD_MARK_TRAILER}: (\\d+) (\\d+)$`, "m"); + export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const vcsProcess = yield* VcsProcess.VcsProcess; const random = yield* SecureRandom.SecureRandom; const hostPlatform = yield* HostProcess.Platform; + // Returns stdout, or null when there is no work tree. A non-repository exits 128 like a broken + // one, so only Git's message (pinned to the C locale) or a missing cwd tells them apart. + const probeWorkTree = Effect.fn("GitVcsDriver.probeWorkTree")(function* ( + operation: string, + cwd: string, + args: ReadonlyArray, + maxOutputBytes: number, + ) { + const result = yield* gitCommand(vcsProcess, operation, cwd, args, { + env: { LC_ALL: "C" }, + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes, + }).pipe(Effect.catchIf(isMissingExecutable, () => Effect.succeed(null))); + if (result === null) return null; + if (result.exitCode === 0) return result.stdout; + // Git before 2.38 answers "false" for a bare repo, then fails on --show-toplevel. + // Match line prefixes only: a path inside a diagnostic may contain the same words. + if ( + result.stdout.startsWith("false") || + hasStderrLine(result.stderr, [ + "fatal: not a git repository", + "fatal: cannot use bare repository", + ]) || + !(yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true))) + ) { + return null; + } + return yield* new VcsProcessExitError({ + operation: WORK_TREE_PROBE_OPERATION, + command: "git rev-parse", + cwd, + exitCode: result.exitCode, + detail: result.stderr.trim() || "git rev-parse failed", + }); + }); + const isInsideWorkTree: VcsDriver.VcsDriver["Service"]["isInsideWorkTree"] = (cwd) => - gitCommand( - vcsProcess, + probeWorkTree( "GitVcsDriver.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], - { - allowNonZeroExit: true, - timeoutMs: 5_000, - maxOutputBytes: 4_096, - }, - ).pipe( - Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"), - Effect.catchIf(isMissingExecutable, () => Effect.succeed(false)), - ); + 4_096, + ).pipe(Effect.map((stdout) => stdout?.trim() === "true")); const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) => gitCommand(vcsProcess, input.operation, input.cwd, input.args, { ...(input.stdin !== undefined ? { stdin: input.stdin } : {}), + ...(input.onSpawn !== undefined ? { onSpawn: input.onSpawn } : {}), ...(input.env !== undefined ? { env: input.env } : {}), ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}), ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}), @@ -622,19 +680,14 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "detectRepository", )(function* (cwd) { // One spawn answers all three; outside a work tree it exits non-zero or prints "false". - const result = yield* gitCommand( - vcsProcess, + const stdout = yield* probeWorkTree( "GitVcsDriver.detectRepository", cwd, ["rev-parse", "--is-inside-work-tree", "--show-toplevel", "--git-common-dir"], - { - allowNonZeroExit: true, - timeoutMs: 5_000, - maxOutputBytes: 16_384, - }, - ).pipe(Effect.catchIf(isMissingExecutable, () => Effect.succeed(null))); - if (result === null || result.exitCode !== 0) return null; - const lines = result.stdout.replace(/\r?\n$/u, "").split(/\r?\n/u); + 16_384, + ); + if (stdout === null) return null; + const lines = stdout.replace(/\r?\n$/u, "").split(/\r?\n/u); if (lines[0]?.trim() !== "true") return null; // A newline inside a path breaks the line framing; ask for each path on its own. if (lines.length !== 3) { @@ -833,14 +886,28 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit", cwd, args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`], + env: { LC_ALL: "C" }, allowNonZeroExit: true, }).pipe( - Effect.map((result) => { + Effect.flatMap((result) => { + // --quiet reports an absent ref as exit 1 with no error; an unreadable object also exits 1 + // but reports an error line. + if (result.exitCode === 1 && !hasStderrLine(result.stderr, ["error:", "fatal:"])) { + return Effect.succeed(null); + } if (result.exitCode !== 0) { - return null; + return Effect.fail( + new VcsProcessExitError({ + operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit", + command: "git rev-parse", + cwd, + exitCode: result.exitCode, + detail: result.stderr.trim() || "git rev-parse failed", + }), + ); } const commit = result.stdout.trim(); - return commit.length > 0 ? commit : null; + return Effect.succeed(commit.length > 0 ? commit : null); }), ); @@ -872,6 +939,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "--git-common-dir", "--git-path", "index", + "--show-toplevel", "--show-prefix", "--verify", "--quiet", @@ -882,13 +950,15 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const headExists = result.exitCode === 0; const headChecked = headExists || result.exitCode === 1; const lines = result.stdout.split("\n"); - const [gitCommonDir = "", indexPath = "", prefix = ""] = lines; - if (headChecked && lines.length === (headExists ? 5 : 4) && lines.at(-1) === "") { + const [gitCommonDir = "", indexPath = "", topLevel = "", prefix = "", head = ""] = lines; + if (headChecked && lines.length === (headExists ? 6 : 5) && lines.at(-1) === "") { return { gitCommonDir: gitCommonDir.trim(), indexPath: indexPath.trim(), + topLevel: topLevel.trim(), prefix, headExists, + head: headExists ? head : undefined, }; } // Git before 2.31 echoes --path-format, and a path containing a newline spans lines. @@ -902,11 +972,26 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( return { gitCommonDir: fallbackCommonDir, indexPath: undefined, + topLevel: undefined, prefix: prefixResult.stdout.replace(/\n$/, ""), headExists: headChecked ? headExists : yield* hasHeadCommit(cwd), + head: undefined, }; }); + // $displaypath is relative to cwd, so "../" marks submodules outside a nested workspace. + const listSubmodules = Effect.fn("GitVcsDriver.listSubmodules")(function* (cwd: string) { + const result = yield* execute({ + operation: "GitVcsDriver.checkpoints.listSubmodules", + cwd, + args: ["submodule", "foreach", "--quiet", 'printf "%s\\0" "$displaypath"'], + }); + return result.stdout + .split("\0") + .filter((entry) => entry !== "" && !entry.startsWith("../")) + .map((entry) => path.join(cwd, entry)); + }); + // Git defaults and macOS writeout-only can leave empty refs after crashes; flush before publication. // Set fsync first: Git 2.36 ignores unknown batch without resetting the method. // Batch fully flushes refs and equals fsync on macOS HFS+/APFS and Windows NTFS/ReFS. @@ -925,6 +1010,66 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // core.longpaths is disabled in the user's Git configuration. const longPaths = hostPlatform === "win32" ? ["-c", "core.longpaths=true"] : []; + // Newest first: the commit each HEAD move landed on, when, and Git's reason for it. + const readHeadMoves = (cwd: string) => + execute({ + operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION, + cwd, + args: [ + "-c", + "log.showSignature=false", + "log", + "--walk-reflogs", + "-n", + String(HEAD_MOVES_SCAN_LIMIT), + "--date=unix", + "--format=%H %gd %gs", + "HEAD", + "--", + ], + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => + result.exitCode !== 0 + ? [] + : result.stdout.split("\n").flatMap((line) => { + const [, to, at, reason] = /^([0-9a-f]+) HEAD@\{(\d+)\} (.*)$/.exec(line) ?? []; + return to === undefined || at === undefined || reason === undefined + ? [] + : [{ to, at, reason }]; + }), + ), + Effect.orElseSucceed(() => []), + ); + + // A checkpoint taken after a branch switch has a second parent: the checkpoint before it with + // the switch applied, which is where that turn started. Other ranges start at `from` itself. + const resolveTurnStart = (input: VcsDriver.VcsListAuthoredPathsInput) => + execute({ + operation: "GitVcsDriver.checkpoints.resolveTurnStart", + cwd: input.cwd, + args: [ + "-c", + "log.showSignature=false", + "log", + "--no-walk=unsorted", + "--format=%H %P", + `${input.fromCheckpointRef}^{commit}`, + `${input.toCheckpointRef}^2`, + ], + allowNonZeroExit: true, + }).pipe( + Effect.map((result): string => { + const [fromLine = "", startLine = ""] = result.stdout.trimEnd().split("\n"); + const [start = "", , startedFrom] = startLine.split(" "); + return result.exitCode === 0 && startedFrom === fromLine.split(" ")[0] + ? start + : input.fromCheckpointRef; + }), + ); + + const untrackedBlobs = CheckpointUntrackedBlobs.make(execute, fileSystem); + const checkpoints: VcsDriver.VcsCheckpointOps = { captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) { const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; @@ -939,15 +1084,57 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "-c", "splitIndex.sharedIndexExpire=never", ]; - const { gitCommonDir, indexPath, prefix, headExists } = yield* resolveCaptureRepository( - input.cwd, - ); + const { gitCommonDir, indexPath, topLevel, prefix, headExists, head } = + yield* resolveCaptureRepository(input.cwd); + // Read before the snapshot and pinned to the same HEAD: a switch that lands while files are + // being staged then belongs to the next checkpoint instead of being applied to this one. + const headMoves = head === undefined ? [] : yield* readHeadMoves(input.cwd); + const lastMove = headMoves.at(0); + // Moves share a second, so the mark also counts how many of that second it has seen. + const headMark = + lastMove !== undefined && lastMove.to === head + ? `${lastMove.at} ${headMoves.filter((move) => move.at === lastMove.at).length}` + : undefined; + const startedAt = yield* Clock.currentTimeMillis; const indexId = yield* random.uuidV4(); const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`); const hostEnv = yield* HostProcess.Environment; + // VcsProcess clears inherited object selectors, so every other command uses this store. + const sharedObjects = path.join(gitCommonDir, "objects"); + const quotedObjects = quoteGitPatchPath(sharedObjects); + // Isolate bulk-checkin packs so cleanup cannot remove another Git writer's objects. + const privateObjects = yield* Effect.acquireRelease( + fileSystem + .makeTempDirectory({ directory: sharedObjects, prefix: "tmp_objdir-t3-checkpoint-" }) + .pipe( + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ + operation, + cwd: input.cwd, + stage: "isolate", + cause, + }), + ), + ), + (directory) => + fileSystem.remove(directory, { recursive: true, force: true }).pipe( + Effect.catch((cause) => + Effect.logWarning("Could not remove private checkpoint objects", { + reason: cause.reason._tag, + }), + ), + ), + ); const commitEnv: NodeJS.ProcessEnv = { - ...hostEnv, GIT_INDEX_FILE: tempIndexPath, + GIT_OBJECT_DIRECTORY: privateObjects, + // A filter must not publish refs that depend on our disposable store. + GIT_QUARANTINE_PATH: privateObjects, + // Git accepts C-quoted alternate paths, including path-list separators. + GIT_ALTERNATE_OBJECT_DIRECTORIES: quotedObjects.startsWith('"') + ? quotedObjects + : `"${quotedObjects}"`, GIT_AUTHOR_NAME: "T3 Code", GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", GIT_COMMITTER_NAME: "T3 Code", @@ -1197,6 +1384,16 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( } } + // Untracked files have no stat data in a new index, so git add would rehash every one. + const untracked = + topLevel === undefined || head === undefined || sparseCheckout || workspaceIgnored + ? undefined + : { cwd: input.cwd, topLevel, head, env: commitEnv }; + const { reused, before } = + untracked === undefined + ? CheckpointUntrackedBlobs.NOTHING + : yield* untrackedBlobs.reuse({ ...untracked, indexConfig }); + const stageFiles = (exclusions: ReadonlyArray) => execute({ operation, @@ -1218,6 +1415,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ], env: commitEnv, }); + const stagingAt = yield* Clock.currentTimeMillis; yield* stageFiles([]).pipe( Effect.catchTags({ VcsProcessExitError: (error) => @@ -1251,6 +1449,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( GIT_INDEX_FILE: undefined, GIT_OBJECT_DIRECTORY: undefined, GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined, + GIT_QUARANTINE_PATH: undefined, }; const exclusions: Array = []; for (const entry of candidates) { @@ -1275,6 +1474,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), ); + const stagingMs = (yield* Clock.currentTimeMillis) - stagingAt; + const writeTreeResult = yield* execute({ operation, cwd: input.cwd, @@ -1292,8 +1493,137 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } - const message = `t3 checkpoint ref=${input.checkpointRef}`; - // HEAD is the parent so listAuthoredPaths can see how HEAD moved between checkpoints. + // Switching branches rewrites files the turn never wrote, and only HEAD's reflog tells a + // switch from a reset. The trailer marks where that reflog stood for the next checkpoint. + const turnStart = + headMark === undefined || input.previousCheckpointRef === undefined + ? null + : yield* Effect.gen(function* () { + const previous = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "-c", + "log.showSignature=false", + "log", + "--no-walk", + "--format=%H %T %ct %P%n%B", + `${input.previousCheckpointRef}^{commit}`, + ], + allowNonZeroExit: true, + }); + if (previous.exitCode !== 0) return null; + const [commit = "", tree = "", capturedAt = "", previousHead = ""] = previous.stdout + .slice(0, previous.stdout.indexOf("\n")) + .split(" "); + const [, markedAt, markedCount] = + HEAD_MARK_TRAILER_PATTERN.exec(previous.stdout) ?? []; + const oldestMarked = headMoves.findLastIndex((move) => move.at === markedAt); + // -1 when the scan ended inside the marked second, so the count cannot be placed. + const since = + oldestMarked === HEAD_MOVES_SCAN_LIMIT - 1 + ? -1 + : oldestMarked - Number(markedCount) + 1; + if (headMoves[since]?.to !== previousHead) return null; + const switches = headMoves + .slice(0, since) + .map((move, index) => ({ ...move, from: headMoves[index + 1]!.to })) + .filter( + (move) => + move.reason.startsWith("checkout: moving from ") && move.from !== move.to, + ) + .toReversed(); + const landedOn = switches.at(-1)?.to; + if (landedOn === undefined) return null; + + yield* execute({ + operation, + cwd: input.cwd, + args: [...indexConfig, "-c", "index.sparse=false", "read-tree", tree], + env: commitEnv, + }); + for (const { from, to } of switches) { + const changes = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "-c", + "core.quotePath=true", + "diff-tree", + "-r", + "--no-renames", + from, + to, + ], + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + outputMode: "error", + }); + // A switch succeeds only where the files it replaces were unmodified, so each + // changed path takes the destination's version. Mode 000000 drops the path. + const entries = changes.stdout + .split("\n") + // A switch leaves a submodule's own checkout where it was. + .filter((line) => line !== "" && !/^:(?:160000 |[0-7]{6} 160000 )/.test(line)) + .map((line) => + line.replace( + /^:[0-7]{6} ([0-7]{6}) [0-9a-f]+ ([0-9a-f]+) [A-Z]\t/, + "$1 $2\t", + ), + ); + if (entries.length === 0) continue; + yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...indexConfig, + "-c", + "index.sparse=false", + "update-index", + "--index-info", + ], + stdin: `${entries.join("\n")}\n`, + env: commitEnv, + }); + } + const startTree = (yield* execute({ + operation, + cwd: input.cwd, + args: [...indexConfig, ...durableWrite, "write-tree"], + env: commitEnv, + })).stdout.trim(); + if (startTree === "" || startTree === tree) return null; + const startCommit = yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...durableWrite, + "commit-tree", + startTree, + "-p", + landedOn, + "-p", + commit, + "-m", + `t3 checkpoint turn start ref=${input.checkpointRef}`, + ], + // listAuthoredPaths reads commits newer than the start as the turn's own. + env: { ...commitEnv, GIT_COMMITTER_DATE: `${capturedAt} +0000` }, + }); + return startCommit.stdout.trim() || null; + }).pipe( + Effect.catch((cause) => + Effect.logWarning("checkpoint branch switch turn start failed", { + cwd: input.cwd, + checkpointRef: input.checkpointRef, + cause: String(cause), + }).pipe(Effect.as(null)), + ), + ); + + const message = `t3 checkpoint ref=${input.checkpointRef}${ + headMark === undefined ? "" : `\n\n${HEAD_MARK_TRAILER}: ${headMark}` + }`; + // HEAD is the first parent so listAuthoredPaths can see how HEAD moved between checkpoints. const commitTreeResult = yield* execute({ operation, cwd: input.cwd, @@ -1301,7 +1631,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ...durableWrite, "commit-tree", treeOid, - ...(headExists ? ["-p", "HEAD"] : []), + ...(headExists ? ["-p", head ?? "HEAD"] : []), + ...(turnStart === null ? [] : ["-p", turnStart]), "-m", message, ], @@ -1318,13 +1649,144 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } + // Git writers have exited; bound publication by fanout directory. + yield* fileSystem.readDirectory(privateObjects).pipe( + Effect.flatMap((directories) => + Effect.forEach( + directories.filter( + (directory) => directory === "pack" || /^[0-9a-f]{2}$/.test(directory), + ), + (directory) => + Effect.gen(function* () { + const source = path.join(privateObjects, directory); + const destination = path.join(sharedObjects, directory); + // Most fanouts already exist; avoid constructing an EEXIST error + // for each of them on every capture. mkdir still handles the race. + if (!(yield* fileSystem.exists(destination))) + yield* fileSystem.makeDirectory(destination).pipe( + Effect.andThen( + Effect.gen(function* () { + // Git has already applied core.sharedRepository to the source. + // chmod bypasses umask, but never changes a pre-existing bucket. + const { mode } = yield* fileSystem.stat(source); + yield* fileSystem.chmod(destination, mode & 0o7777); + }), + ), + Effect.catchIf( + (cause) => cause.reason._tag === "AlreadyExists", + () => Effect.void, + ), + Effect.uninterruptible, + ); + const names = yield* fileSystem.readDirectory(source); + // Per-object spans would swamp the capture span for large workspaces. + const linkObject = Effect.fnUntraced(function* (name: string) { + const from = path.join(source, name); + const to = path.join(destination, name); + yield* fileSystem.link(from, to).pipe( + Effect.catchIf( + (cause) => + cause.reason._tag === "PermissionDenied" || + cause.reason._tag === "Unknown", + () => + Effect.gen(function* () { + if (yield* fileSystem.exists(to)) return; + // Git also falls back to rename without hardlinks; identical object names are interchangeable. + yield* fileSystem.rename(from, to); + }), + ), + Effect.catchIf( + (cause) => cause.reason._tag === "AlreadyExists", + () => Effect.void, + ), + ); + }); + if (directory !== "pack") { + yield* Effect.forEach( + names.filter((name) => /^(?:[0-9a-f]{38}|[0-9a-f]{62})$/.test(name)), + linkObject, + { discard: true }, + ); + return; + } + const files = new Set(names); + for (const name of names) { + if (!/^pack-(?:[0-9a-f]{40}|[0-9a-f]{64})\.pack$/.test(name)) continue; + const base = name.slice(0, -5); + if (!files.has(`${base}.idx`)) continue; + // Link metadata before the pack so an I/O error cannot strand a + // large unindexed pack. Defer cancellation across this short group + // of links. Never roll back shared links: a concurrent writer may + // already depend on them. Ref publication still happens last. + yield* Effect.forEach( + [".keep", ".promisor", ".rev", ".idx", ".pack"] + .map((extension) => `${base}${extension}`) + .filter((file) => files.has(file)), + linkObject, + { discard: true }, + ).pipe(Effect.uninterruptible); + } + }), + { concurrency: 16, discard: true }, + ), + ), + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ operation, cwd: input.cwd, stage: "publish", cause }), + ), + ); + yield* execute({ operation, cwd: input.cwd, args: [...durableWrite, "update-ref", input.checkpointRef, commitOid], }); + if (untracked !== undefined) { + yield* untrackedBlobs.remember({ + ...untracked, + tree: treeOid, + startedAt, + stagingMs, + reused, + before, + }); + } }).pipe(Effect.ensuring(cleanupTempIndex)); - }), + + // The tree records only each submodule's HEAD, so submodules keep their own ref. + const hasSubmodules = + topLevel === undefined || + (yield* fileSystem + .exists(path.join(topLevel, ".gitmodules")) + .pipe(Effect.orElseSucceed(() => true))); + if (!hasSubmodules) return; + // A submodule that cannot be captured drops its ref, so restore leaves it alone. + yield* listSubmodules(input.cwd).pipe( + Effect.flatMap((submodules) => + Effect.forEach( + submodules, + (cwd) => + checkpoints + .captureCheckpoint({ cwd, checkpointRef: input.checkpointRef }) + .pipe( + Effect.catch((cause) => + Effect.logWarning("submodule checkpoint capture failed", { cwd, cause }).pipe( + Effect.andThen( + checkpoints + .deleteCheckpointRefs({ cwd, checkpointRefs: [input.checkpointRef] }) + .pipe(Effect.ignore), + ), + ), + ), + ), + { discard: true }, + ), + ), + Effect.catch((cause) => + Effect.logWarning("submodule checkpoint capture failed", { cwd: input.cwd, cause }), + ), + ); + }, Effect.scoped), hasCheckpointRef: (input) => resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe( @@ -1349,23 +1811,16 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd: input.cwd, args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."], }); - // An empty index and checkpoint have nothing for git restore's pathspec to match. - if (tracked.stdout.length > 0) { - yield* execute({ - operation, - cwd: input.cwd, - args: [ - ...longPaths, - "restore", - "--source", - commitOid, - "--worktree", - "--staged", - "--", - ".", - ], - }); - } + const sparseConfig = + tracked.stdout.length > 0 + ? yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--bool", "core.sparseCheckout"], + allowNonZeroExit: true, + }) + : null; + const sparseCheckout = sparseConfig?.stdout.trim() === "true"; // Restoring away the last tracked file can remove a nested workspace directory. const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe( Effect.mapError( @@ -1388,6 +1843,95 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( args: [...longPaths, "reset", "--quiet", "--", "."], }); }); + let mutationStarted = false; + const onSpawn = () => { + mutationStarted = true; + }; + // Queued commands preserve user staging; spawned children stop before this scope resets it. + yield* Effect.addFinalizer((exit) => + mutationStarted && Exit.hasInterrupts(exit) ? resetIndex.pipe(Effect.ignore) : Effect.void, + ); + // An empty index and checkpoint have nothing for git restore's pathspec to match. + if (tracked.stdout.length > 0) { + const restore = [...longPaths, "restore", "--source", commitOid, "--worktree", "--staged"]; + // restore leaves skip-worktree paths alone. Outside a sparse checkout every such bit was + // set by hand and capture recorded the file, so override them all. + yield* execute({ + operation, + cwd: input.cwd, + args: [...restore, ...(sparseCheckout ? [] : ["--ignore-skip-worktree-bits"]), "--", "."], + onSpawn, + }); + if (sparseCheckout) { + // Sparse exclusions stay excluded; only skip-worktree paths the rules select are manual. + const manual = yield* Effect.gen(function* () { + const skipped: string[] = []; + let recordStart = true; + let keep = false; + let record: Uint8Array[] = []; + yield* vcsProcess.run({ + operation, + command: "git", + cwd: input.cwd, + args: ["ls-files", "--full-name", "--sparse", "-v", "-z", "--", "."], + maxOutputBytes: 4_096, + outputMode: "truncate", + // The index can be huge; keep only the "S "/"s " records of the NUL-delimited list. + onStdoutChunk: (chunk) => { + let start = 0; + while (start < chunk.length) { + const end = chunk.indexOf(0, start); + if (recordStart) { + keep = chunk[start] === 83 || chunk[start] === 115; + record = []; + } + if (keep) { + record.push(Buffer.from(chunk.subarray(start, end === -1 ? undefined : end))); + if (end !== -1) { + const entry = Buffer.concat(record).subarray(2); + record = []; + // Sparse directory entries are exclusions; stdin cannot carry non-UTF-8. + if (entry.at(-1) !== 47 && NodeBuffer.isUtf8(entry)) + skipped.push(entry.toString("utf8")); + } + } + recordStart = end !== -1; + if (!recordStart) break; + start = end + 1; + } + }, + }); + if (skipped.length === 0) return skipped; + const stdin = skipped.join("\0") + "\0"; + // check-rules echoes a subset of its input, so the input size bounds its output. + const rules = yield* execute({ + operation, + cwd: input.cwd, + args: ["sparse-checkout", "check-rules", "-z"], + stdin, + maxOutputBytes: Buffer.byteLength(stdin), + outputMode: "error", + }); + return rules.stdout.split("\0").filter((entry) => entry.length > 0); + }).pipe( + // A Git without ls-files --sparse or check-rules keeps the plain restore's result. + Effect.orElseSucceed((): string[] => []), + ); + if (manual.length > 0) { + yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...restore, + "--ignore-skip-worktree-bits", + "--pathspec-from-file=-", + "--pathspec-file-nul", + ], + stdin: manual.map((entry) => `:(top,literal)${entry}\0`).join(""), + }); + } + } + } yield* recreateWorkspace; const clean = execute({ operation, @@ -1395,6 +1939,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( args: [...longPaths, "clean", "-fd", "--", "."], env: { LC_ALL: "C" }, allowNonZeroExit: true, + onSpawn, }); let cleaned = yield* clean; // Removing a new .gitignore exposes the files it hid; clean again until nothing is left. @@ -1447,8 +1992,34 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( } yield* resetIndex; + // A submodule without this ref was not captured, and restoring it to HEAD would lose edits. + // The root is already restored, so a failing submodule must not hide that from the caller. + yield* listSubmodules(input.cwd).pipe( + Effect.flatMap((submodules) => + Effect.forEach( + submodules, + (cwd) => + checkpoints + .restoreCheckpoint({ + cwd, + checkpointRef: input.checkpointRef, + fallbackToHead: false, + }) + .pipe( + Effect.catch((cause) => + Effect.logWarning("submodule checkpoint restore failed", { cwd, cause }), + ), + ), + { discard: true }, + ), + ), + Effect.catch((cause) => + Effect.logWarning("submodule checkpoint restore failed", { cwd: input.cwd, cause }), + ), + ); + return true; - }), + }, Effect.scoped), diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) { const operation = "GitVcsDriver.checkpoints.diffCheckpoints"; @@ -1462,15 +2033,13 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "checkpoint.fallback_from_to_head": input.fallbackFromToHead, }); - let fromRevision: string = input.fromCheckpointRef; + let fromRevision = yield* resolveTurnStart(input); if (input.fallbackFromToHead === true) { const resolvedFromCommit = yield* resolveCheckpointCommit( input.cwd, input.fromCheckpointRef, ); - if (resolvedFromCommit) { - fromRevision = resolvedFromCommit; - } else { + if (!resolvedFromCommit) { const headCommit = yield* resolveHeadCommit(input.cwd); if (!headCommit) { return yield* new VcsProcessExitError({ @@ -1529,25 +2098,36 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) { const operation = "GitVcsDriver.checkpoints.listAuthoredPaths"; + const turnStart = yield* resolveTurnStart(input); const heads = yield* execute({ operation, cwd: input.cwd, args: [ "log", "--no-walk=unsorted", - "--format=%P %ct", - `${input.fromCheckpointRef}^{commit}`, + "--format=%ct %P", + `${turnStart}^{commit}`, `${input.toCheckpointRef}^{commit}`, ], }); const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n"); - const [startHead = "", capturedAt = ""] = fromLine.split(" "); - const [endHead = ""] = toLine.split(" "); + const [capturedAt = "", startHead = ""] = fromLine.split(" "); + const [, endHead = ""] = toLine.split(" "); if (startHead === "" || endHead === "" || startHead === endHead) { return null; } - const listPaths = (args: ReadonlyArray) => + const listLines = (args: ReadonlyArray, stdin?: string) => + execute({ + operation, + cwd: input.cwd, + // log.showSignature prints verification text into the output. + args: ["-c", "log.showSignature=false", ...args], + ...(stdin === undefined ? {} : { stdin }), + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + outputMode: "error", + }).pipe(Effect.map((result) => result.stdout.split("\n").filter((line) => line !== ""))); + const listPaths = (args: ReadonlyArray, stdin?: string) => execute({ operation, cwd: input.cwd, @@ -1563,26 +2143,73 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "--no-renames", "--no-ext-diff", ], + ...(stdin === undefined ? {} : { stdin }), maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, outputMode: "error", }).pipe(Effect.map((result) => result.stdout.split("\0"))); + + // A commit is an import when a fetch delivered it since the previous checkpoint and no + // reflog in any worktree shows this repository creating it. --all covers every worktree's + // HEAD, and with --walk-reflogs --since compares each entry's own time. + const listImportedCommits = Effect.gen(function* () { + const entries = (yield* listLines([ + "log", + "--walk-reflogs", + "--all", + `--since=@${capturedAt}`, + "--format=%H %gD %gs", + ])).map((line) => { + const [commit = "", selector = "", ...subject] = line.split(" "); + return { + commit, + fetched: selector.startsWith("refs/remotes/"), + subject: subject.join(" "), + }; + }); + // A push records commits this repository already had. + const fetchedTips = new Set( + entries + .filter((entry) => entry.fetched && entry.subject !== "update by push") + .map((entry) => entry.commit), + ); + if (fetchedTips.size === 0) return fetchedTips; + // Fetching another branch can deliver a commit that was made here and pushed. + const createdHere = new Set( + entries + .filter((entry) => !entry.fetched && !REF_MOVE_REFLOG_SUBJECT.test(entry.subject)) + .map((entry) => entry.commit), + ); + const fetched = yield* listLines( + ["rev-list", `--since=@${capturedAt}`, "--stdin"], + `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + ); + return new Set(fetched.filter((commit) => !createdHere.has(commit))); + }); + // Remerge diffs retain merge conflict fixes while excluding clean upstream changes. - const pathLists = yield* Effect.all( + const [recentCommits, ...pathLists] = yield* Effect.all( [ - listPaths(["diff", startHead, `${input.fromCheckpointRef}^{commit}`]), + listLines(["rev-list", `--since=@${capturedAt}`, `${startHead}..${endHead}`]), + listPaths(["diff", startHead, `${turnStart}^{commit}`]), listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]), listPaths(["log", "--format=", "--diff-merges=remerge", `${endHead}..${startHead}`]), - listPaths([ - "log", - "--format=", - "--diff-merges=remerge", - `--since=@${capturedAt}`, - `${startHead}..${endHead}`, - ]), ], { concurrency: "unbounded" }, ); - return new Set(pathLists.flat().filter((path) => path.length > 0)); + // Without readable reflogs every recent commit stays attributed, as before. + const importedCommits = + recentCommits.length === 0 + ? new Set() + : yield* listImportedCommits.pipe(Effect.orElseSucceed(() => new Set())); + const ownCommits = recentCommits.filter((commit) => !importedCommits.has(commit)); + const ownCommitPaths = + ownCommits.length === 0 + ? [] + : yield* listPaths( + ["log", "--no-walk=unsorted", "--stdin", "--format=", "--diff-merges=remerge"], + `${ownCommits.join("\n")}\n`, + ); + return new Set([...pathLists.flat(), ...ownCommitPaths].filter((path) => path.length > 0)); }), deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")( @@ -1598,6 +2225,10 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), { discard: true }, ); + const submodules = yield* listSubmodules(input.cwd).pipe(Effect.orElseSucceed(() => [])); + for (const cwd of submodules) { + yield* checkpoints.deleteCheckpointRefs({ cwd, checkpointRefs: input.checkpointRefs }); + } }, ), }; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d9a5e7d2b9..efaf982640 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1,18 +1,24 @@ // @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not. +import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; +import * as NodeNet from "node:net"; import * as NodePath from "node:path"; import * as NodeURL from "node:url"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, it, describe } from "@effect/vitest"; +import { afterAll, vi } from "vite-plus/test"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; 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 FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as PlatformError from "effect/PlatformError"; @@ -38,12 +44,14 @@ import { import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as ServerConfig from "../config.ts"; import { + isNonRepositoryGitStderr, makeGitVcsDriverCore, parseGitCheckoutProgressLine, splitNullSeparatedGitStdoutPaths, windowsLongPathConfigEnv, } from "./GitVcsDriverCore.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; +import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; import { gitConfigEnv } from "./VcsProcess.ts"; const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError)); @@ -131,6 +139,27 @@ const makeDriverReleasingLock = ( return { driver, failures }; }); +describe("isNonRepositoryGitStderr", () => { + it.each([ + "fatal: not a git repository (or any of the parent directories): .git", + "fatal: not a git repository: /missing-git-directory", + // Git 2.56+ wording for a `.git` gitfile that points at a missing directory. + "fatal: gitfile does not point to a valid repository: /tmp/worktrees/feature/.git", + "FATAL: GITFILE DOES NOT POINT TO A VALID REPOSITORY: /tmp/x/.git", + ])("classifies %j as a non-repository", (stderr) => { + assert.isTrue(isNonRepositoryGitStderr(stderr)); + }); + + it.each([ + "", + "fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.", + "fatal: Unable to create '/repo/.git/index.lock': File exists.", + "fatal: invalid gitfile format: /repo/.git", + ])("does not classify %j as a non-repository", (stderr) => { + assert.isFalse(isNonRepositoryGitStderr(stderr)); + }); +}); + it.effect("runs background Git in its own lane so user commands never queue behind it", () => Effect.gen(function* () { const gate = yield* Deferred.make(); @@ -317,6 +346,20 @@ const git = ( return result.stdout.trim(); }); +const [, gitMajor, gitMinor] = + /(\d+)\.(\d+)/u.exec(NodeChildProcess.execFileSync("git", ["--version"], { encoding: "utf8" })) ?? + []; +const gitHasReftable = Number(gitMajor) > 2 || (Number(gitMajor) === 2 && Number(gitMinor) >= 45); + +const gitWithStdin = ( + cwd: string, + args: ReadonlyArray, + stdin: string, +): Effect.Effect => + Effect.flatMap(GitVcsDriver.GitVcsDriver, (driver) => + driver.execute({ operation: "GitVcsDriver.test.git", cwd, args, stdin, timeoutMs: 10_000 }), + ).pipe(Effect.map((result) => result.stdout.trim())); + // Git blocks file submodule transports (CVE-2022-39253) despite repo config; local fixtures need env permission. const withGitFileProtocol = (effect: Effect.Effect) => Effect.flatMap(HostProcess.Environment, (env) => @@ -333,17 +376,49 @@ const initRepoWithCommit = ( GitVcsDriver.GitVcsDriver | FileSystem.FileSystem | Path.Path > => Effect.gen(function* () { - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* driver.initRepo({ cwd }); - yield* git(cwd, ["config", "user.email", "test@test.com"]); - yield* git(cwd, ["config", "user.name", "Test"]); + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + // Git commits whatever already sits in cwd, so only an empty one can take the shared copy. + const empty = + !(yield* fileSystem.exists(cwd)) || (yield* fileSystem.readDirectory(cwd)).length === 0; + if (empty) { + if (!repoTemplate) { + const template = yield* fileSystem.makeTempDirectory({ + prefix: "git-vcs-driver-template-", + }); + yield* commitInitialRepo(template); + repoTemplate = template; + } + yield* fileSystem.copy(repoTemplate, cwd); + } else { + yield* commitInitialRepo(cwd); + } + const head = yield* fileSystem.readFileString(pathService.join(cwd, ".git", "HEAD")); + return { initialBranch: head.trim().replace(/^ref: refs\/heads\//, "") }; + }); + +const commitInitialRepo = (cwd: string, initArgs: ReadonlyArray = []) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + yield* git(cwd, ["init", ...initArgs]); + // Newer Git detaches auto-maintenance after commit; its lock file would race the template copy. + yield* fileSystem.writeFileString( + pathService.join(cwd, ".git", "config"), + "[user]\n\temail = test@test.com\n\tname = Test\n[maintenance]\n\tauto = false\n", + { flag: "a" }, + ); yield* writeTextFile(cwd, "README.md", "# test\n"); yield* git(cwd, ["add", "."]); yield* git(cwd, ["commit", "-m", "initial commit"]); - const initialBranch = yield* git(cwd, ["branch", "--show-current"]); - return { initialBranch }; }); +// Most tests start from the same one-commit repository; they copy it instead of spawning git. +let repoTemplate: string | undefined; +afterAll(() => { + if (repoTemplate) NodeFS.rmSync(repoTemplate, { recursive: true, force: true }); +}); + it.effect.each(["root", "nested", "worktree"] as const)( "skips clean filters while the %s index is locked and resumes after unlock", (location) => @@ -485,7 +560,10 @@ it.effect.each([ assert.equal(created.failure.exitCode, hookExitCode); } const metadataQueries = spawnedArgs.filter((args) => args.includes("--git-common-dir")); - assert.deepStrictEqual(metadataQueries, [["rev-parse", "--git-common-dir"]]); + assert.deepStrictEqual( + metadataQueries, + Array.from({ length: 2 }, () => ["rev-parse", "--git-common-dir"]), + ); assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref"))); invalidationFailure = "none"; @@ -548,7 +626,7 @@ it.effect.each(["branch", "detached", "nested", "aliased-root", "aliased-nested" newRefName: "feature/cold", }); - assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1); + assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 2); assert.isFalse(spawnedArgs.some((args) => args.includes("--show-toplevel"))); assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref"))); spawnedArgs.length = 0; @@ -608,9 +686,12 @@ it.effect.each(["bare", "unborn"] as const)( assert.equal(Result.isSuccess(result), state === "bare"); if (Result.isFailure(result)) { assert.equal(result.failure.operation, "GitVcsDriver.createWorktree.createBranch"); - assert.equal(result.failure.detail, "git worktree add failed"); + assert.equal(result.failure.detail, "git branch failed"); } - assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1); + assert.equal( + spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, + state === "bare" ? 2 : 1, + ); assert.isFalse(spawnedArgs.some((args) => args[0] === "symbolic-ref")); spawnedArgs.length = 0; const refs = yield* driver.listRefs({ cwd }); @@ -625,6 +706,65 @@ it.effect.each(["bare", "unborn"] as const)( ).pipe(Effect.provide(layerTest)), ); +it.effect("reads the project's own repository when the server inherited GIT_DIR", () => + Effect.scoped( + Effect.gen(function* () { + const path = yield* Path.Path; + const cwd = yield* makeTmpDir(); + const other = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* initRepoWithCommit(other); + yield* git(other, ["switch", "-c", "other-repository"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); + vi.stubEnv("GIT_DIR", path.join(other, ".git")); + assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, initialBranch); + const refs = yield* driver.listRefs({ cwd }); + assert.isFalse(refs.refs.some((ref) => ref.name === "other-repository")); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect("reads a branch whose name starts with a parenthesis as attached", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["switch", "-c", "(topic"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const status = yield* driver.statusDetailsLocal(cwd, { includeDivergence: false }); + assert.equal(status.branch, "(topic"); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect.each(["an existing", "a new"] as const)( + "follows a checkout of %s branch made outside the driver after refs were cached", + (branch) => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + if (branch === "an existing") yield* git(cwd, ["branch", "feature/outside"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.listRefs({ cwd }); + + yield* git( + cwd, + branch === "an existing" + ? ["switch", "feature/outside"] + : ["switch", "-c", "feature/outside"], + ); + + const refs = (yield* driver.listRefs({ cwd })).refs; + const previous = refs.find((ref) => ref.name === initialBranch); + assert.isTrue(refs.find((ref) => ref.name === "feature/outside")?.current); + assert.isFalse(previous?.current); + assert.isNull(previous?.worktreePath ?? null); + }), + ).pipe(Effect.provide(layerTest)), +); + it.effect.each(["on a branch", "detached", "unborn"] as const)( "reads only the repository root for review requests that ignore the branch when %s", (state) => @@ -984,6 +1124,287 @@ describe("pullCurrentBranch", () => { }; }); + it.effect("resolves a status waiter when Pull claims its queued fetch", () => + Effect.scoped( + Effect.gen(function* () { + const { cwd, remoteHead } = yield* cloneBehindRemote; + const blockers: string[] = []; + for (let index = 0; index < 4; index++) { + const blocker = yield* cloneBehindRemote; + blockers.push(NodeFS.realpathSync.native(blocker.cwd)); + } + const targetPath = NodeFS.realpathSync.native(cwd); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const release = yield* Deferred.make(); + const blockersStarted = yield* Deferred.make(); + const targetEntered = yield* Deferred.make(); + let running = 0; + let targetFetches = 0; + let waiterSucceeded = false; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const handle = yield* delegate.spawn(command); + if (!ChildProcess.isStandardCommand(command) || !command.args.includes("fetch")) + return handle; + const commandCwd = String(command.options.cwd); + if (commandCwd === targetPath) targetFetches++; + if (blockers.includes(commandCwd)) { + running++; + if (running === 4) yield* Deferred.succeed(blockersStarted, undefined); + yield* Deferred.await(release); + } + return handle; + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + if (options.name === "GitVcsDriver.fetchRemoteForStatus.wait") { + const attribute = span.attribute.bind(span); + span.attribute = (key, value) => { + attribute(key, value); + if (key === "statusFetch.joining") Deferred.doneUnsafe(targetEntered, Effect.void); + }; + const end = span.end.bind(span); + span.end = (endTime, exit) => { + waiterSucceeded = Exit.isSuccess(exit); + end(endTime, exit); + }; + } + return span; + }, + }); + yield* Effect.gen(function* () { + for (const blocker of blockers) { + yield* driver.statusDetailsRemote(blocker).pipe(Effect.forkChild); + } + yield* Deferred.await(blockersStarted); + const status = yield* driver + .statusDetailsRemote(cwd) + .pipe(Effect.withTracer(tracer), Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(targetEntered); + const pull = yield* driver.pullCurrentBranch(cwd); + const refreshed = yield* Fiber.join(status); + assert.equal(pull.status, "pulled"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + assert.isTrue(waiterSucceeded); + assert.equal(refreshed.behindCount, 0); + assert.equal(targetFetches, 0); + }).pipe(Effect.ensuring(Deferred.succeed(release, undefined))); + }), + ).pipe(Effect.provide(layerTest)), + ); + + const claimedFetchFallbacks = ["diverged", "interrupted", "upstream-only"] as const; + + it.effect.each(claimedFetchFallbacks)( + "falls back to the claimed status fetch when Pull is %s", + (failure) => + Effect.scoped( + Effect.gen(function* () { + const { cwd, updater, remoteHead } = yield* cloneBehindRemote; + if (failure === "upstream-only") { + yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); + yield* writeTextFile(cwd, ".git/refs/remotes/origin/other.lock", ""); + } + if (failure === "diverged") { + yield* writeTextFile(cwd, "local.txt", "local\n"); + yield* git(cwd, ["add", "local.txt"]); + yield* git(cwd, ["commit", "-m", "local commit"]); + } + const blockers: string[] = []; + for (let index = 0; index < 4; index++) { + const blocker = yield* cloneBehindRemote; + blockers.push(NodeFS.realpathSync.native(blocker.cwd)); + } + const targetPath = NodeFS.realpathSync.native(cwd); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const release = yield* Deferred.make(); + const blockersStarted = yield* Deferred.make(); + const targetEntered = yield* Deferred.make(); + const targetFetchStarted = yield* Deferred.make(); + const pullBeforeFetch = yield* Deferred.make(); + const releasePull = yield* Deferred.make(); + let running = 0; + let targetFetches = 0; + let waiterSucceeded = false; + let targetFetchExitCode: number | undefined; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (ChildProcess.isStandardCommand(command)) { + const commandCwd = NodeFS.realpathSync.native(String(command.options.cwd)); + if ( + commandCwd === targetPath && + failure === "interrupted" && + command.args[0] === "rev-parse" && + command.args[1] === "HEAD" && + command.args.length === 2 + ) { + yield* Deferred.succeed(pullBeforeFetch, undefined); + yield* Deferred.await(releasePull); + } + } + const handle = yield* delegate.spawn(command); + if (!ChildProcess.isStandardCommand(command) || !command.args.includes("fetch")) + return handle; + const commandCwd = String(command.options.cwd); + if (commandCwd === targetPath) { + targetFetches++; + yield* Deferred.succeed(targetFetchStarted, undefined); + return ChildProcessSpawner.makeHandle({ + ...handle, + exitCode: handle.exitCode.pipe( + Effect.tap((exitCode) => + Effect.sync(() => { + targetFetchExitCode = exitCode; + }), + ), + ), + }); + } + if (blockers.includes(commandCwd)) { + running++; + if (running === 4) yield* Deferred.succeed(blockersStarted, undefined); + yield* Deferred.await(release); + } + return handle; + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + if (options.name === "GitVcsDriver.fetchRemoteForStatus.wait") { + const attribute = span.attribute.bind(span); + span.attribute = (key, value) => { + attribute(key, value); + if (key === "statusFetch.joining") + Deferred.doneUnsafe(targetEntered, Effect.void); + }; + const end = span.end.bind(span); + span.end = (endTime, exit) => { + waiterSucceeded = Exit.isSuccess(exit); + end(endTime, exit); + }; + } + return span; + }, + }); + yield* Effect.gen(function* () { + for (const blocker of blockers) { + yield* driver.statusDetailsRemote(blocker).pipe(Effect.forkChild); + } + yield* Deferred.await(blockersStarted); + const status = yield* driver + .statusDetailsRemote(cwd) + .pipe(Effect.withTracer(tracer), Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(targetEntered); + if (failure === "interrupted") { + const pull = yield* driver.pullCurrentBranch(cwd).pipe(Effect.forkChild); + yield* Deferred.await(pullBeforeFetch); + yield* Fiber.interrupt(pull); + const exit = yield* Fiber.await(pull); + assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)); + } else if (failure === "upstream-only") { + assert.equal((yield* driver.pullCurrentBranch(cwd)).status, "pulled"); + yield* (yield* FileSystem.FileSystem).remove( + `${cwd}/.git/refs/remotes/origin/other.lock`, + ); + } else { + const error = yield* Effect.flip(driver.pullCurrentBranch(cwd)); + assert.equal(error.operation, "GitVcsDriver.pullCurrentBranch.pull"); + } + assert.equal(targetFetches, 0); + yield* Deferred.succeed(release, undefined); + yield* Deferred.await(targetFetchStarted); + assert.isTrue((yield* Fiber.join(status)).isRepo); + assert.isTrue(waiterSucceeded); + assert.equal(targetFetches, 1); + assert.equal(targetFetchExitCode, 0); + if (failure === "upstream-only") { + assert.equal(yield* git(cwd, ["rev-parse", "refs/remotes/origin/other"]), remoteHead); + } + }).pipe( + Effect.ensuring( + Effect.all([ + Deferred.succeed(release, undefined), + Deferred.succeed(releasePull, undefined), + ]), + ), + ); + }), + ).pipe(Effect.provide(layerTest)), + ); + + it.effect("waits for a running status fetch before starting Pull", () => + Effect.scoped( + Effect.gen(function* () { + const { cwd, remoteHead } = yield* cloneBehindRemote; + const targetPath = NodeFS.realpathSync.native(cwd); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const fetchStarted = yield* Deferred.make(); + const releaseFetch = yield* Deferred.make(); + const pullResolvedCommonDir = yield* Deferred.make(); + const pullStarted = yield* Deferred.make(); + const events: string[] = []; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (!ChildProcess.isStandardCommand(command)) return yield* delegate.spawn(command); + const target = NodeFS.realpathSync.native(String(command.options.cwd)) === targetPath; + if (target && command.args.includes("pull")) { + events.push("pull-spawn"); + yield* Deferred.succeed(pullStarted, undefined); + } + const handle = yield* delegate.spawn(command); + if (target && command.args.includes("fetch")) { + yield* Deferred.succeed(fetchStarted, undefined); + yield* Deferred.await(releaseFetch); + yield* handle.exitCode; + events.push("fetch-exit"); + } + return handle; + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + if (options.name === "resolveGitCommonDir") { + const end = span.end.bind(span); + span.end = (endTime, exit) => { + end(endTime, exit); + Deferred.doneUnsafe(pullResolvedCommonDir, Effect.void); + }; + } + return span; + }, + }); + yield* Effect.gen(function* () { + yield* driver.statusDetailsRemote(cwd).pipe(Effect.forkChild); + yield* Deferred.await(fetchStarted); + const pull = yield* driver + .pullCurrentBranch(cwd) + .pipe(Effect.withTracer(tracer), Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(pullResolvedCommonDir); + assert.isFalse(yield* Deferred.isDone(pullStarted)); + assert.isUndefined(pull.pollUnsafe()); + yield* Deferred.succeed(releaseFetch, undefined); + const result = yield* Fiber.join(pull); + assert.equal(result.status, "pulled"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + assert.deepEqual(events, ["fetch-exit", "pull-spawn"]); + }).pipe(Effect.ensuring(Deferred.succeed(releaseFetch, undefined))); + }), + ).pipe(Effect.provide(layerTest)), + ); + it.effect("still fetches other branches on the first pull", () => Effect.gen(function* () { const driver = yield* GitVcsDriver.GitVcsDriver; @@ -1143,6 +1564,48 @@ describe("pullCurrentBranch", () => { ), ), ); + + // A slow smudge filter (LFS) can hold the checkout past 30 seconds; killing it there leaves a + // half-updated working tree. The automatic pulls and pull request refresh use these defaults. + it.effect.each(["pull", "merge"] as const)( + "lets a slow %s checkout finish instead of killing it at 30 seconds", + (subcommand) => + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const { cwd, remoteHead } = yield* cloneBehindRemote; + yield* git(cwd, ["fetch", "origin"]); + const checkoutStarted = yield* Deferred.make(); + const releaseCheckout = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const handle = yield* delegate.spawn(command); + if (!ChildProcess.isStandardCommand(command) || command.args[0] !== subcommand) { + return handle; + } + yield* Deferred.succeed(checkoutStarted, undefined); + return ChildProcessSpawner.makeHandle({ + ...handle, + exitCode: Deferred.await(releaseCheckout).pipe(Effect.andThen(handle.exitCode)), + }); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const move = + subcommand === "pull" + ? Effect.asVoid(driver.pullCurrentBranch(cwd)) + : Effect.asVoid(driver.refreshCheckedOutBranch({ cwd, targetCommit: remoteHead })); + const moving = yield* move.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(checkoutStarted); + yield* TestClock.adjust("60 seconds"); + yield* Deferred.succeed(releaseCheckout, undefined); + + yield* Fiber.join(moving); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + }).pipe(Effect.provide(layerTest)), + ); }); it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => @@ -1388,6 +1851,53 @@ it.effect("reads worktrees from git that rejects worktree list -z", () => ), ); +it.effect("commits selected files with git that rejects --pathspec-from-file", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + // Git before 2.25 has no `add --pathspec-from-file` and exits with a usage error. + const oldGitSpawner = ChildProcessSpawner.make((command) => { + if (!ChildProcess.isStandardCommand(command)) { + return Effect.die("expected a standard Git command"); + } + if (command.args.at(-1) === "version") { + return Effect.succeed(makeSuccessfulHandle("git version 2.24.4\n")); + } + if (command.args.some((arg) => String(arg).startsWith("--pathspec-from-file"))) { + return Effect.succeed(makeFailedHandle("error: unknown option `pathspec-from-file=-'")); + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, oldGitSpawner), + ); + yield* Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const selected = ["selected[1].txt", "-dash.txt", "with space.txt"]; + for (const file of selected) yield* writeTextFile(cwd, file, "selected\n"); + yield* writeTextFile(cwd, "left.txt", "left\n"); + + yield* driver.commit(cwd, "Selected", "", { stage: { filePaths: selected } }); + + assert.sameMembers( + (yield* git(cwd, ["show", "--pretty=", "--name-only", "-z", "HEAD"])) + .split("\0") + .filter(Boolean), + selected, + ); + assert.equal(yield* git(cwd, ["status", "--porcelain"]), "?? left.txt"); + }).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); + }), + ).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + it.effect("does not report a separate git dir as the worktree of its branch", () => Effect.scoped( Effect.gen(function* () { @@ -1605,6 +2115,37 @@ it.effect("does not fetch for status when the branch tracks a local branch", () ).pipe(Effect.provide(layerTest)), ); +it.effect("does not fetch for status when the automatic fetch interval is zero", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const fetches: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command) && command.args.includes("fetch")) { + fetches.push(command.args.map(String)); + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(VcsAutomaticFetchInterval, Effect.succeed(Duration.zero)), + ); + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "--set-upstream", "origin", initialBranch]); + + yield* driver.statusDetails(cwd); + const status = yield* driver.statusDetailsRemote(cwd); + + assert.equal(status.upstreamRef, `origin/${initialBranch}`); + assert.deepStrictEqual(fetches, []); + }), + ).pipe(Effect.provide(layerTest)), +); + it.effect("lets a worktree checkout that is still working run past five minutes", () => Effect.gen(function* () { const checkoutStarted = yield* Deferred.make(); @@ -1613,7 +2154,8 @@ it.effect("lets a worktree checkout that is still working run past five minutes" Effect.gen(function* () { if (!ChildProcess.isStandardCommand(command)) return yield* Effect.die("expected Git command"); - if (!command.args.includes("worktree")) return makeSuccessfulHandle(""); + if (!command.args.includes("worktree") || command.args.includes("-h")) + return makeSuccessfulHandle(""); yield* Deferred.succeed(checkoutStarted, undefined); return ChildProcessSpawner.makeHandle({ ...makeSuccessfulHandle(""), @@ -1720,6 +2262,53 @@ it.effect("cancels a slow submodule checkout without reporting best-effort succe ), ); +// regression: #18537 the fetch before creating a worktree outgrew the 30s default +it.effect.each(["healthy", "hung"] as const)("bounds a %s remote fetch at five minutes", (fetch) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const finished = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcess.isStandardCommand(command) && command.args[0] === "fetch" + ? ChildProcessSpawner.makeHandle({ + ...makeSuccessfulHandle(""), + exitCode: Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(finished)), + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + }) + : makeNonRepositoryHandle(), + ), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const fetching = yield* driver + .fetchRemote({ cwd: yield* makeTmpDir(), remoteName: "origin" }) + .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(started); + yield* TestClock.adjust("31 seconds"); + if (fetch === "healthy") yield* Deferred.succeed(finished, undefined); + else { + yield* TestClock.adjust("268 seconds"); + assert.isUndefined(fetching.pollUnsafe()); + yield* TestClock.adjust("1 second"); + } + + const result = yield* Fiber.join(fetching); + assert.equal( + Result.isFailure(result) ? result.failure.detail : "fetched", + fetch === "healthy" ? "fetched" : "Git command timed out.", + ); + }).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + describe("rejected git refs", () => { const remoteUrl = "https://user:token-123@git.example.invalid/org/secret-repo.git"; const failedPush = `error: failed to push some refs to '${remoteUrl}'`; @@ -1803,20 +2392,62 @@ describe("rejected git refs", () => { }); it.layer(layerTest)("GitVcsDriver core integration", (it) => { - it.effect("keeps large change sets available for status and commit preparation", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* git(cwd, ["init"]); - yield* git(cwd, ["config", "user.email", "test@test.com"]); - yield* git(cwd, ["config", "user.name", "Test"]); - const files = Array.from( - { length: 6_000 }, - (_, index) => `file-${String(index).padStart(5, "0")}-${"x".repeat(160)}.txt`, - ); - yield* Effect.forEach(files, (file) => fs.writeFileString(path.join(cwd, file), "before\n"), { + // regression: #26577 a timed-out git that outlives its timeout holds a process permit + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "kills a timed-out git command that ignores SIGTERM", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const pathService = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const markerPath = pathService.join(yield* makeTmpDir(), "outlived-timeout"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const trapped = yield* Deferred.make(); + + const command = yield* driver + .execute({ + operation: "GitVcsDriver.test.ignoresSigterm", + cwd, + args: [ + "-c", + `alias.hang=!trap '' TERM; echo trapped; sleep 3; touch '${markerPath}'`, + "hang", + ], + progress: { + onStdoutLine: (line) => + line === "trapped" ? Deferred.succeed(trapped, undefined) : Effect.void, + }, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(trapped); + // The driver's timeout ends a command the same way: by interrupting it. + yield* Fiber.interrupt(command); + + assert.isFalse( + yield* fileSystem.exists(markerPath), + "the timed-out git command kept running until it finished on its own", + ); + }), + ); + + it.effect("keeps large change sets available for status and commit preparation", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["init"]); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + // Selected paths add up to more than Linux's default 2 MiB argument limit. + const dir = "d".repeat(200); + yield* fs.makeDirectory(path.join(cwd, dir)); + const files = Array.from( + { length: 6_000 }, + (_, index) => `${dir}/file-${String(index).padStart(5, "0")}-${"x".repeat(160)}.txt`, + ); + yield* Effect.forEach(files, (file) => fs.writeFileString(path.join(cwd, file), "before\n"), { concurrency: 16, discard: true, }); @@ -1840,6 +2471,10 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isNotNull(context); assert.isAbove(context!.stagedSummary.length, 1_000_000); assert.lengthOf(context!.stagedSummary.split("\n"), files.length); + const selected = files.slice(1); + yield* driver.commit(cwd, "selected", "", { stage: { filePaths: selected } }); + assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "selected"); + assert.equal(yield* git(cwd, ["status", "--porcelain"]), `M ${files[0]}`); }), ); describe("structured errors", () => { @@ -1875,6 +2510,28 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("fails with a GitCommandError when spawn throws", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const driver = yield* GitVcsDriver.GitVcsDriver; + + // Over the OS argument limit, Node's spawn throws E2BIG synchronously. + const error = yield* driver + .execute({ + operation: "GitVcsDriver.test.spawnThrow", + cwd, + args: ["status", "x".repeat(4 * 1024 * 1024)], + }) + .pipe(Effect.flip); + + assert.deepInclude(error, { + _tag: "GitCommandError", + operation: "GitVcsDriver.test.spawnThrow", + detail: "Failed to spawn Git process.", + }); + }), + ); + // regression: #8645 name the cause of a failed git command it.effect("names the branch conflict behind a failed worktree add", () => Effect.gen(function* () { @@ -1933,7 +2590,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { it.effect.each([ { action: "worktree add", detail: "git worktree add failed" }, - { action: "worktree add -b", detail: "git worktree add failed" }, + { action: "worktree add -b", detail: "git branch failed" }, { action: "switch", detail: "git checkout failed" }, ])( "reports a missing ref during $action with stable, redacted diagnostics", @@ -1948,6 +2605,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const spawner = ChildProcessSpawner.make((command) => { if ( ChildProcess.isStandardCommand(command) && + !command.args.includes("-h") && (command.args.includes("worktree") || command.args[0] === "branch" || command.args[0] === "checkout") @@ -1982,6 +2640,128 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("explains a non-fast-forward push from a host with a translated Git", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + const other = yield* makeTmpDir("git-other-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "--set-upstream", "origin", initialBranch]); + yield* git(other, ["clone", "--branch", initialBranch, remote, "."]); + yield* git(other, [ + "-c", + "user.email=t@t", + "-c", + "user.name=T", + "commit", + "--allow-empty", + "-m", + "remote", + ]); + yield* git(other, ["push", "origin", initialBranch]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "local"]); + const locales: Array = []; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command) && command.args.includes("push")) { + locales.push(command.options.env?.LANGUAGE); + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const hostEnv = yield* HostProcess.Environment; + + const error = yield* driver + .pushCurrentBranch(cwd, null) + .pipe( + Effect.provideService(HostProcess.Environment, { ...hostEnv, LANGUAGE: "de" }), + Effect.flip, + ); + + assert.equal(error.reason, "push_rejected_non_fast_forward"); + assert.isNotEmpty(locales); + for (const locale of locales) assert.equal(locale, "C"); + }), + ); + + it.effect("lets a slow remote branch checkout finish without blocking config writes", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/feature"]); + yield* git(cwd, ["fetch", "origin"]); + const checkoutStarted = yield* Deferred.make(); + const releaseCheckout = yield* Deferred.make(); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + // Holds the real checkout open like a slow LFS smudge filter would. + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const handle = yield* delegate.spawn(command); + if (!ChildProcess.isStandardCommand(command) || command.args[0] !== "checkout") { + return handle; + } + yield* Deferred.succeed(checkoutStarted, undefined); + return ChildProcessSpawner.makeHandle({ + ...handle, + exitCode: Deferred.await(releaseCheckout).pipe(Effect.andThen(handle.exitCode)), + }); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + + const switching = yield* driver + .switchRef({ cwd, refName: "origin/feature" }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(checkoutStarted); + yield* TestClock.adjust("60 seconds"); + yield* driver.createRef({ cwd, refName: "other" }); + yield* Deferred.succeed(releaseCheckout, undefined); + + const result = yield* Fiber.join(switching); + assert.equal(result.refName, "feature"); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature@{upstream}"]), + "origin/feature", + ); + }), + ); + + it.effect( + "switches a remote ref to its tracking branch when a tag shares the branch name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/v1.2"]); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["branch", "--track", "v1.2", "origin/v1.2"]); + yield* git(cwd, ["tag", "v1.2"]); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + + const result = yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({ + cwd, + refName: "origin/v1.2", + }); + + assert.equal(result.refName, "v1.2"); + assert.equal(yield* git(cwd, ["symbolic-ref", "HEAD"]), "refs/heads/v1.2"); + }), + ); + it.effect.each([ // Git cannot tell a missing revision from a missing file in these. { label: "an argument that may be a path", args: ["log", "-1", "missing"] }, @@ -2276,9 +3056,22 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const { initialBranch } = yield* initRepoWithCommit(cwd); const driver = yield* GitVcsDriver.GitVcsDriver; yield* git(cwd, ["checkout", "-b", "feature/commits"]); - for (let index = 0; index < 102; index++) { - yield* git(cwd, ["commit", "--allow-empty", "-m", `feature ${index}`]); - } + const parent = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* gitWithStdin( + cwd, + ["fast-import", "--quiet"], + Array.from({ length: 102 }, (_, index) => { + const message = `feature ${index}`; + return [ + "commit refs/heads/feature/commits", + `committer Test ${1_700_000_000 + index} +0000`, + `data ${Buffer.byteLength(message)}`, + message, + ...(index === 0 ? [`from ${parent}`] : []), + "", + ].join("\n"); + }).join(""), + ); const result = yield* driver.getReviewBranchCommits({ cwd, baseRef: initialBranch }); assert.strictEqual(result.truncated, true); @@ -2461,7 +3254,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); const source = dirty.sources.find((source) => source.kind === "working-tree")!; assert.deepStrictEqual(source.files, [ - { path: "untracked.txt", previousPath: null, additions: 1, deletions: 0 }, + { + path: "untracked.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, ]); assert.include(source.diff, "+untracked content"); }), @@ -2567,7 +3366,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isTrue(metadata.sources[0]!.patchesDeferred); assert.isEmpty(metadata.sources[0]!.diff); assert.deepStrictEqual(metadata.sources[0]!.files, [ - { path: "README.md", previousPath: null, additions: 1, deletions: 1 }, + { + path: "README.md", + previousPath: null, + changeType: "change", + additions: 1, + deletions: 1, + }, ]); }), ); @@ -2613,6 +3418,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("keeps the review working beside a nested repository with no commits", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["init", "scaffold"]); + const committed = `${cwd}/committed`; + yield* (yield* FileSystem.FileSystem).makeDirectory(committed); + yield* initRepoWithCommit(committed); + yield* writeTextFile(cwd, "README.md", "# tracked change\n"); + yield* writeTextFile(cwd, "untracked.txt", "untracked contents\n"); + + const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); + const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; + + assert.include(diff, "+# tracked change"); + assert.include(diff, "+untracked contents"); + assert.notInclude(diff, "scaffold"); + assert.include(diff, "diff --git a/committed b/committed"); + + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: null, + insertions: 3, + deletions: 1, + }); + }), + ); + it.effect("keeps untracked filenames with pathspec magic in the review", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -2637,7 +3471,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); const scopedSource = scoped.sources.find((source) => source.kind === "working-tree")!; assert.deepStrictEqual(scopedSource.files, [ - { path: ":(exclude)after.ts", previousPath: null, additions: 1, deletions: 0 }, + { + path: ":(exclude)after.ts", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, ]); assert.include(scopedSource.diff, "+literal pathspec contents"); assert.notInclude(scopedSource.diff, "ordinary.ts"); @@ -2660,7 +3500,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const source = preview.sources.find((candidate) => candidate.kind === "working-tree")!; assert.deepStrictEqual(source.files, [ - { path: "excluded/new.ts", previousPath: null, additions: 1, deletions: 0 }, + { + path: "excluded/new.ts", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, ]); assert.include(source.diff, "+outside the cone"); }), @@ -2703,7 +3549,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const source = preview.sources.find((candidate) => candidate.kind === "working-tree")!; assert.deepStrictEqual(source.files, [ - { path: "after.ts", previousPath: "before.ts", additions: 1, deletions: 1 }, + { + path: "after.ts", + previousPath: "before.ts", + changeType: "rename-changed", + additions: 1, + deletions: 1, + }, ]); const scoped = yield* driver.getReviewDiffPreview({ cwd, @@ -2823,7 +3675,15 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const preview = yield* driver.getReviewDiffPreview({ cwd }); assert.deepStrictEqual( preview.sources.find((source) => source.kind === "working-tree")!.files, - [{ path: "untracked.txt", previousPath: null, additions: 1, deletions: 0 }], + [ + { + path: "untracked.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, + ], ); assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/filter-runs")), ""); assert.deepStrictEqual(yield* fs.readFile(indexPath), originalIndex); @@ -2863,8 +3723,20 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const preview = yield* driver.getReviewDiffPreview({ cwd }); const dirty = preview.sources.find((source) => source.kind === "working-tree")!; assert.deepStrictEqual(dirty.files, [ - { path: "tracked.txt", previousPath: null, additions: 1, deletions: 1 }, - { path: "untracked.txt", previousPath: null, additions: 1, deletions: 0 }, + { + path: "tracked.txt", + previousPath: null, + changeType: "change", + additions: 1, + deletions: 1, + }, + { + path: "untracked.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, ]); assert.include(dirty.diff, "-before"); assert.include(dirty.diff, "+after!"); @@ -2928,14 +3800,44 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { } assert.deepStrictEqual(branch.files, [ - { path: "a-large.txt", previousPath: null, additions: 4000, deletions: 0 }, - { path: "untracked.txt", previousPath: null, additions: 4000, deletions: 0 }, - { path: "z-last.txt", previousPath: null, additions: 1, deletions: 0 }, + { + path: "a-large.txt", + previousPath: null, + changeType: "new", + additions: 4000, + deletions: 0, + }, + { + path: "untracked.txt", + previousPath: null, + changeType: "new", + additions: 4000, + deletions: 0, + }, + { path: "z-last.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, ]); assert.deepStrictEqual(dirty.files, [ - { path: "a-large.txt", previousPath: null, additions: 4000, deletions: 4000 }, - { path: "untracked.txt", previousPath: null, additions: 4000, deletions: 0 }, - { path: "z-last.txt", previousPath: null, additions: 1, deletions: 1 }, + { + path: "a-large.txt", + previousPath: null, + changeType: "change", + additions: 4000, + deletions: 4000, + }, + { + path: "untracked.txt", + previousPath: null, + changeType: "new", + additions: 4000, + deletions: 0, + }, + { + path: "z-last.txt", + previousPath: null, + changeType: "change", + additions: 1, + deletions: 1, + }, ]); }), ); @@ -2946,10 +3848,12 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const { initialBranch } = yield* initRepoWithCommit(cwd); const driver = yield* GitVcsDriver.GitVcsDriver; yield* writeTextFile(cwd, "mode-only.sh", "echo unchanged\n"); - yield* git(cwd, ["add", "mode-only.sh"]); + yield* writeTextFile(cwd, "removed.txt", "removed\n"); + yield* git(cwd, ["add", "mode-only.sh", "removed.txt"]); yield* git(cwd, ["commit", "-m", "add executable candidate"]); yield* git(cwd, ["checkout", "-b", "feature/paths"]); yield* git(cwd, ["mv", "README.md", "renamed.md"]); + yield* git(cwd, ["rm", "removed.txt"]); yield* writeTextFile(cwd, "[literal].txt", "literal\n"); yield* writeTextFile(cwd, " leading.txt", "whitespace path\n"); yield* writeTextFile(cwd, "l.txt", "other\n"); @@ -2989,12 +3893,28 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.deepInclude(branch.files ?? [], { path: "renamed.md", previousPath: "README.md", + changeType: "rename-pure", + additions: 0, + deletions: 0, + }); + assert.deepInclude(branch.files ?? [], { + path: "removed.txt", + previousPath: null, + changeType: "deleted", + additions: 0, + deletions: 1, + }); + assert.deepInclude(branch.files ?? [], { + path: "mode-only.sh", + previousPath: null, + changeType: "change", additions: 0, deletions: 0, }); assert.deepInclude(branch.files ?? [], { path: "binary.dat", previousPath: null, + changeType: "new", additions: 0, deletions: 0, }); @@ -3002,6 +3922,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.deepInclude(branch.files ?? [], { path: "tab\tand\nnewline.txt", previousPath: null, + changeType: "new", additions: 1, deletions: 0, }); @@ -3020,8 +3941,14 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const preview = yield* driver.getReviewDiffPreview({ cwd }); const dirty = preview.sources.find((source) => source.kind === "working-tree")!; assert.deepStrictEqual(dirty.files, [ - { path: "staged.txt", previousPath: null, additions: 1, deletions: 0 }, - { path: "untracked.txt", previousPath: null, additions: 1, deletions: 0 }, + { path: "staged.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, + { + path: "untracked.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, ]); assert.include(dirty.diff, "b/staged.txt"); assert.include(dirty.diff, "b/untracked.txt"); @@ -3205,6 +4132,77 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("loads working-tree contents as Git diffs them under the ident attribute", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + const filePath = (yield* Path.Path).join(cwd, "README.md"); + const committed = "$Id$\nfirst\nsecond\n"; + yield* writeTextFile(cwd, ".gitattributes", "README.md ident\n"); + yield* writeTextFile(cwd, "README.md", committed); + yield* writeTextFile(cwd, "PLAIN.md", "plain\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "add ident keyword"]); + // Checkout smudges the keyword to `$Id: $`. + yield* fileSystem.remove(filePath); + yield* git(cwd, ["checkout-index", "--force", "README.md"]); + const smudged = yield* fileSystem.readFileString(filePath); + assert.match(smudged, /^\$Id: [0-9a-f]{40} \$\n/); + yield* writeTextFile(cwd, "README.md", smudged.replace("first", "edited")); + yield* writeTextFile(cwd, "PLAIN.md", "$Id: literal $\n"); + const disk = yield* fileSystem.readFile(filePath); + + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd), + ); + const plain = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { oldPath: "PLAIN.md", newPath: "PLAIN.md" }), + ); + + assert.deepStrictEqual(contents, { + oldContents: committed, + newContents: "$Id$\nedited\nsecond\n", + }); + assert.strictEqual(plain.newContents, "$Id: literal $\n"); + yield* writeTextFile(cwd, "README.md", "$Id: x $Id: y $\n"); + const sharedDollar = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd), + ); + assert.strictEqual(sharedDollar.newContents, "$Id$Id: y $\n"); + yield* git(cwd, ["config", "filter.unrelated.clean", "touch filter-ran; cat"]); + yield* writeTextFile(cwd, ".gitattributes", "README.md ident text eol=lf\n"); + yield* writeTextFile( + cwd, + "README.md", + smudged.replace("first", "edited").replaceAll("\n", "\r\n"), + ); + const crlf = yield* driver.getReviewDiffFileContents(makeReviewDiffFileContentsInput(cwd)); + assert.strictEqual(crlf.newContents, "$Id$\r\nedited\r\nsecond\r\n"); + yield* fileSystem.writeFile(filePath, disk); + yield* writeTextFile(cwd, ".gitattributes", "README.md ident=set\n"); + const literal = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd), + ); + assert.strictEqual(literal.newContents, smudged.replace("first", "edited")); + yield* writeTextFile(cwd, ".gitattributes", "README.md ident filter=probe\n"); + yield* git(cwd, ["config", "filter.probe.clean", "touch filter-ran; cat"]); + const filtered = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd), + ); + assert.strictEqual(filtered.newContents, literal.newContents); + yield* writeTextFile(cwd, ".gitattributes", "README.md ident filter=unspecified\n"); + yield* git(cwd, ["config", "filter.unspecified.clean", "touch filter-ran; cat"]); + const reservedFilter = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd), + ); + assert.strictEqual(reservedFilter.newContents, literal.newContents); + assert.isFalse(yield* fileSystem.exists((yield* Path.Path).join(cwd, "filter-ran"))); + assert.deepStrictEqual(yield* fileSystem.readFile(filePath), disk); + }), + ); + it.effect("Changes combines commits, uncommitted edits, and untracked files", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3221,7 +4219,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const clean = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); assert.deepStrictEqual(sourceFiles(clean, "working-tree"), []); assert.deepStrictEqual(sourceFiles(clean, "branch-range"), [ - { path: "README.md", previousPath: null, additions: 1, deletions: 0 }, + { + path: "README.md", + previousPath: null, + changeType: "change", + additions: 1, + deletions: 0, + }, ]); yield* writeTextFile(cwd, "README.md", "# test\ncommitted\ndirty\n"); @@ -3229,14 +4233,26 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const dirty = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); const changes = dirty.sources.find((source) => source.kind === "branch-range")!; assert.deepStrictEqual(changes.files, [ - { path: "README.md", previousPath: null, additions: 2, deletions: 0 }, - { path: "new.txt", previousPath: null, additions: 1, deletions: 0 }, + { + path: "README.md", + previousPath: null, + changeType: "change", + additions: 2, + deletions: 0, + }, + { path: "new.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, ]); assert.strictEqual(changes.diff.match(/^diff --git a\/README\.md /gm)?.length, 1); assert.include(changes.diff, "+dirty"); assert.deepStrictEqual(sourceFiles(dirty, "working-tree"), [ - { path: "README.md", previousPath: null, additions: 1, deletions: 0 }, - { path: "new.txt", previousPath: null, additions: 1, deletions: 0 }, + { + path: "README.md", + previousPath: null, + changeType: "change", + additions: 1, + deletions: 0, + }, + { path: "new.txt", previousPath: null, changeType: "new", additions: 1, deletions: 0 }, ]); }), ); @@ -3265,7 +4281,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const changes = preview.sources.find((source) => source.kind === "branch-range")!; assert.strictEqual(changes.baseRef, "origin/main"); assert.deepStrictEqual(changes.files, [ - { path: "unpushed.txt", previousPath: null, additions: 1, deletions: 0 }, + { + path: "unpushed.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, ]); }), ); @@ -3304,10 +4326,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const changes = preview.sources.find((source) => source.kind === "branch-range")!; assert.strictEqual(changes.baseRef, baseRef); assert.deepStrictEqual(changes.files, [ - { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, - ]); - } - + { + path: "feature.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, + ]); + } + for (const baseRef of ["origin/main", "upstream/missing", "main"]) { yield* git(cwd, ["config", "branch.feature/configured-base.gh-merge-base", baseRef]); const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); @@ -3338,8 +4366,20 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const changes = preview.sources.find((source) => source.kind === "branch-range")!; assert.strictEqual(changes.baseRef, "refs/remotes/upstream/main"); assert.deepStrictEqual(changes.files, [ - { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, - { path: "upstream.txt", previousPath: null, additions: 1, deletions: 1 }, + { + path: "feature.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, + { + path: "upstream.txt", + previousPath: null, + changeType: "change", + additions: 1, + deletions: 1, + }, ]); const contents = yield* driver.getReviewDiffFileContents( makeReviewDiffFileContentsInput(cwd, { @@ -3394,7 +4434,11 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { // Base config reads start only after status completes; hold every one until the rename lands. const spawner = ChildProcessSpawner.make((command) => Effect.gen(function* () { - if (ChildProcess.isStandardCommand(command) && command.args[0] === "config") { + if ( + ChildProcess.isStandardCommand(command) && + command.args[0] === "config" && + !command.args.includes("status.showUntrackedFiles") + ) { if (!(yield* Ref.getAndSet(renameClaimed, true))) { yield* git(cwd, ["branch", "-m", "t3/temporary", "feature/named"]).pipe( Effect.provideService(GitVcsDriver.GitVcsDriver, outer), @@ -3451,7 +4495,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const changes = preview.sources.find((source) => source.kind === "branch-range")!; assert.strictEqual(changes.baseRef, baseRef); assert.deepStrictEqual(changes.files, [ - { path: "README.md", previousPath: null, additions: 1, deletions: 0 }, + { + path: "README.md", + previousPath: null, + changeType: "change", + additions: 1, + deletions: 0, + }, ]); const scoped = yield* driver.getReviewDiffPreview({ cwd, @@ -3500,7 +4550,15 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const explicit = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); assert.deepStrictEqual( explicit.sources.find((source) => source.kind === "branch-range")!.files, - [{ path: "detached.txt", previousPath: null, additions: 1, deletions: 0 }], + [ + { + path: "detached.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, + ], ); const implicit = yield* driver.getReviewDiffPreview({ cwd }); assert.deepStrictEqual( @@ -3530,7 +4588,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const changes = preview.sources.find((source) => source.kind === "branch-range")!; assert.isNull(changes.baseRef); assert.deepStrictEqual(changes.files, [ - { path: "new.txt", previousPath: null, additions: 2, deletions: 0 }, + { path: "new.txt", previousPath: null, changeType: "new", additions: 2, deletions: 0 }, ]); const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); assert.deepStrictEqual(status.branchChanges, { @@ -3561,7 +4619,15 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const preview = yield* driver.getReviewDiffPreview({ cwd, baseRef: initialBranch }); assert.deepStrictEqual( preview.sources.find((source) => source.kind === "branch-range")!.files, - [{ path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }], + [ + { + path: "feature.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, + ], ); } }), @@ -3593,6 +4659,25 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports a local upstream without a slash and its divergence", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const initialBranch = yield* git(cwd, ["symbolic-ref", "--short", "HEAD"]); + yield* git(cwd, ["branch", "feature"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "advance base"]); + yield* git(cwd, ["checkout", "feature"]); + yield* git(cwd, ["branch", `--set-upstream-to=${initialBranch}`]); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const remoteStatus = yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false }); + assert.equal(remoteStatus.upstreamRef, initialBranch); + assert.equal(remoteStatus.hasUpstream, true); + assert.equal(remoteStatus.aheadCount, 0); + assert.equal(remoteStatus.behindCount, 1); + }), + ); + it.effect("does not open a project folder laid out as a bare repository", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3668,6 +4753,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { { path: "repeated.txt", previousPath: null, + changeType: "change", additions: Number(additions), deletions: Number(removals), }, @@ -3718,6 +4804,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reads Changes totals without rewriting the real index for stat-dirty files", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "tracked.txt", "same content\n"); + yield* git(cwd, ["add", "tracked.txt"]); + yield* git(cwd, ["commit", "-m", "add tracked file"]); + yield* fileSystem.utimes(path.join(cwd, "tracked.txt"), 1_000_000_000, 1_000_000_000); + const indexPath = path.join(cwd, ".git", "index"); + const originalIndex = yield* fileSystem.readFile(indexPath); + + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + + assert.strictEqual(status.branchChanges?.insertions, 0); + assert.strictEqual(status.branchChanges?.deletions, 0); + // Writing the index takes index.lock, which makes concurrent user Git writes fail. + assert.deepStrictEqual(yield* fileSystem.readFile(indexPath), originalIndex); + }), + ); + it.effect("reads Changes totals with untracked files when requested", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3814,6 +4923,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["checkout", "-b", "feature/many-untracked"]); yield* writeTextFile(cwd, ".git/info/exclude", "ignored.txt\n"); yield* writeTextFile(cwd, "bulk[1]/ignored.txt", "ignored\n"); + const clean = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(clean.branchChanges, { + baseRef: "main", + insertions: 0, + deletions: 0, + }); + assert.deepStrictEqual(untrackedScanRoots, []); yield* Effect.forEach( Array.from({ length: 1_001 }, (_, index) => `bulk[1]/${index}.txt`), (file) => writeTextFile(cwd, file, "one\ntwo\n"), @@ -3838,18 +4954,157 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { deletions: 0, }); assert.deepStrictEqual(untrackedScanRoots, [ - scenario === "normal" ? [":(top,literal)bulk[1]/"] : [], + scenario === "normal" || scenario === "no" ? [":(top,literal)bulk[1]/"] : [], ]); - if (scenario === "normal") { + if (scenario === "normal" || scenario === "no") { assert.deepStrictEqual( status.workingTree.files.map((file) => file.path), ["bulk[1]/"], ); + } else if (scenario === "all") { + assert.lengthOf(status.workingTree.files, 1_001); } } }), ); + it.effect( + "reports a new repository without waiting on a huge untracked file's line count", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* git(cwd, ["init", "-b", "main"]); + yield* writeTextFile(cwd, "small.txt", "line\n"); + yield* writeTextFile(cwd, "large.data", ""); + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + yield* fileSystem.truncate(pathService.join(cwd, "large.data"), 8 * 1024 * 1024 * 1024); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const totalsDiffSettled = yield* Deferred.make(); + const largeFileDiffAbandonedAt = yield* Deferred.make(); + // Stands in for `git diff --numstat` reading gigabytes of untracked file content. + const readsLargeFile = (command: ChildProcess.Command) => { + const indexFile = + ChildProcess.isStandardCommand(command) && + command.args.includes("--numstat") && + command.options.env?.GIT_INDEX_FILE; + return ( + typeof indexFile === "string" && + NodeFS.readFileSync(indexFile).includes(Buffer.from("large.data")) + ); + }; + const spawner = ChildProcessSpawner.make((command) => + readsLargeFile(command) + ? Deferred.succeed(totalsDiffSettled, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + ...makeSuccessfulHandle(""), + isRunning: Effect.succeed(true), + exitCode: Effect.never.pipe( + Effect.onInterrupt(() => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + Deferred.succeed(largeFileDiffAbandonedAt, now), + ), + ), + ), + ), + }), + ), + ) + : delegate.spawn(command), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const startedAt = yield* Clock.currentTimeMillis; + + const status = yield* driver + .statusDetailsLocal(cwd, { includeDivergence: false, includeBranchChanges: true }) + .pipe(Effect.forkChild); + yield* Effect.raceFirst(Deferred.await(totalsDiffSettled), Fiber.await(status)); + // Git's default command timeout, which is what releases the status on main. + yield* TestClock.adjust("30 seconds"); + const reported = yield* Fiber.join(status); + + const statusHeldForMs = (yield* Deferred.isDone(largeFileDiffAbandonedAt)) + ? (yield* Deferred.await(largeFileDiffAbandonedAt)) - startedAt + : 0; + assert.isAtMost(statusHeldForMs, 5_000, "status waited on the untracked line count"); + assert.isTrue(reported.isRepo); + assert.strictEqual(reported.branch, "main"); + }).pipe(Effect.provide(layerServerConfig)), + ); + + it.effect("counts totals when a large unstaged copy of a removed file stays on disk", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + yield* writeTextFile(cwd, "asset.data", "old\n"); + yield* git(cwd, ["add", "asset.data"]); + yield* git(cwd, ["commit", "-m", "add asset"]); + yield* git(cwd, ["rm", "--cached", "asset.data"]); + yield* fileSystem.truncate(pathService.join(cwd, "asset.data"), 257 * 1024 * 1024); + yield* writeTextFile(cwd, "ordinary.txt", "new\n"); + + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + + assert.deepStrictEqual(status.branchChanges, { + baseRef: null, + insertions: 1, + deletions: 1, + }); + const preview = yield* driver.getReviewDiffPreview({ cwd, metadataOnly: true }); + assert.deepStrictEqual( + preview.sources.find((source) => source.kind === "working-tree")?.files, + [ + { + path: "asset.data", + previousPath: null, + changeType: "deleted", + additions: 0, + deletions: 1, + }, + { + path: "ordinary.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, + ], + ); + }), + ); + + it.effect("keeps an oversized untracked file out of the review diff", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + yield* writeTextFile(cwd, "README.md", "# tracked change\n"); + yield* writeTextFile(cwd, "ordinary.txt", "new\n"); + yield* writeTextFile(cwd, "large.data", ""); + // Sparse: the logical size is over the budget without allocating it. + yield* fileSystem.truncate(pathService.join(cwd, "large.data"), 257 * 1024 * 1024); + + const preview = yield* driver.getReviewDiffPreview({ cwd, metadataOnly: true }); + + const source = preview.sources.find((source) => source.kind === "working-tree")!; + assert.isUndefined(source.files); + assert.isUndefined(source.patchesDeferred); + assert.isTrue(source.truncated); + assert.include(source.diff, "+# tracked change"); + assert.include(source.diff, "b/ordinary.txt"); + assert.notInclude(source.diff, "large.data"); + }), + ); + it.effect("reports changes to a file named HEAD", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3985,7 +5240,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("reports remote status on unborn HEAD without failing", () => + it.effect("reports status on unborn HEAD without failing or dropping its upstream", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const driver = yield* GitVcsDriver.GitVcsDriver; @@ -3999,6 +5254,32 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.equal(status.hasUpstream, false); assert.equal(status.aheadCount, 0); assert.equal(status.behindCount, 0); + + const seed = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + yield* initRepoWithCommit(seed); + yield* git(remote, ["init", "--bare"]); + yield* git(seed, ["push", remote, `HEAD:refs/heads/${initialBranch}`]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["config", `branch.${initialBranch}.remote`, "origin"]); + yield* git(cwd, ["config", `branch.${initialBranch}.merge`, `refs/heads/${initialBranch}`]); + assert.equal((yield* driver.statusDetailsLocal(cwd)).hasUpstream, true); + }), + ); + + it.effect("reports no branch while a clone has not checked out HEAD yet", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.initRepo({ cwd }); + // `git clone` points HEAD here until checkout; status then prints `branch.head (unknown)`. + yield* (yield* FileSystem.FileSystem).writeFileString( + NodePath.join(cwd, ".git", "HEAD"), + "ref: refs/heads/.invalid\n", + ); + + assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, null); }), ); @@ -4069,6 +5350,100 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("a ref snapshot detects branch identity, ref and ancestry changes", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + const updater = yield* makeTmpDir("git-vcs-driver-updater-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + yield* git(updater, ["clone", remote, "."]); + yield* git(updater, ["config", "user.email", "test@test.com"]); + yield* git(updater, ["config", "user.name", "Test"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const snapshot = driver.readRefSnapshot(cwd); + + // Newer Git can create origin/HEAD on the first fetch. + yield* git(cwd, ["fetch", "origin"]); + const initial = yield* snapshot; + assert.isNotNull(initial); + yield* git(cwd, ["fetch", "origin"]); + assert.equal(yield* snapshot, initial); + + yield* git(cwd, ["branch", "same-commit"]); + const beforeCheckout = yield* snapshot; + const refsBeforeCheckout = yield* git(cwd, ["show-ref", "--head"]); + yield* git(cwd, ["checkout", "same-commit"]); + assert.equal(yield* git(cwd, ["show-ref", "--head"]), refsBeforeCheckout); + const afterCheckout = yield* snapshot; + assert.isNotNull(afterCheckout); + assert.notEqual(afterCheckout, beforeCheckout); + yield* git(cwd, ["checkout", "--detach"]); + assert.equal(yield* git(cwd, ["show-ref", "--head"]), refsBeforeCheckout); + const detached = yield* snapshot; + assert.isNotNull(detached); + assert.notEqual(detached, beforeCheckout); + assert.notEqual(detached, afterCheckout); + assert.equal(yield* snapshot, detached); + yield* git(cwd, ["checkout", initialBranch]); + assert.equal(yield* snapshot, beforeCheckout); + yield* git(cwd, ["branch", "-d", "same-commit"]); + + yield* writeTextFile(updater, "remote.txt", "remote\n"); + yield* git(updater, ["add", "remote.txt"]); + yield* git(updater, ["commit", "-m", "remote commit"]); + yield* git(updater, ["push", "origin", initialBranch]); + assert.equal(yield* snapshot, initial); + yield* git(cwd, ["fetch", "origin"]); + const fetched = yield* snapshot; + assert.notEqual(fetched, initial); + + const shallow = yield* makeTmpDir("git-vcs-driver-shallow-"); + yield* git(shallow, ["clone", "--depth=1", NodeURL.pathToFileURL(remote).href, "."]); + const shallowRefs = yield* git(shallow, ["show-ref", "--head"]); + const shallowSnapshot = yield* driver.readRefSnapshot(shallow); + assert.isNotNull(shallowSnapshot); + const shallowWorktree = yield* makeTmpDir("git-vcs-driver-shallow-worktree-"); + yield* git(shallow, ["worktree", "add", "--detach", shallowWorktree]); + const worktreeSnapshot = yield* driver.readRefSnapshot(shallowWorktree); + assert.isNotNull(worktreeSnapshot); + yield* git(shallow, ["fetch", "--unshallow", "origin"]); + assert.equal(yield* git(shallow, ["show-ref", "--head"]), shallowRefs); + const unshallowSnapshot = yield* driver.readRefSnapshot(shallow); + const unshallowWorktreeSnapshot = yield* driver.readRefSnapshot(shallowWorktree); + assert.isNotNull(unshallowSnapshot); + assert.isNotNull(unshallowWorktreeSnapshot); + assert.notEqual(unshallowSnapshot, shallowSnapshot); + assert.notEqual(unshallowWorktreeSnapshot, worktreeSnapshot); + + yield* git(cwd, ["checkout", "--detach"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "detached"]); + assert.notEqual(yield* snapshot, fetched); + + const head = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* driver.execute({ + operation: "GitVcsDriver.test.git", + cwd, + args: ["update-ref", "--stdin"], + stdin: Array.from( + { length: 16_000 }, + (_, index) => `create refs/heads/snapshot-${String(index).padStart(5, "0")} ${head}\n`, + ).join(""), + }); + yield* git(cwd, ["pack-refs", "--all"]); + const large = yield* snapshot; + assert.isNotNull(large); + assert.isAbove(Buffer.byteLength(large ?? "", "utf8"), 1_000_000); + assert.equal(yield* snapshot, large); + yield* git(cwd, ["update-ref", "refs/heads/snapshot-00000", "HEAD~1"]); + assert.notEqual(yield* snapshot, large); + + assert.isNull(yield* driver.readRefSnapshot(yield* makeTmpDir())); + }), + ); + it.effect("does not start Git auto-maintenance from background upstream fetches", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4097,6 +5472,37 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("leaves FETCH_HEAD to the user's own pulls in background upstream fetches", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + const updater = yield* makeTmpDir("git-vcs-driver-updater-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + + yield* git(updater, ["clone", remote, "."]); + yield* git(updater, ["config", "user.email", "test@test.com"]); + yield* git(updater, ["config", "user.name", "Test"]); + yield* writeTextFile(updater, "remote.txt", "remote\n"); + yield* git(updater, ["add", "remote.txt"]); + yield* git(updater, ["commit", "-m", "remote commit"]); + yield* git(updater, ["push", "origin", initialBranch]); + const fetchHeadPath = (yield* Path.Path).join(cwd, ".git", "FETCH_HEAD"); + assert.equal(NodeFS.existsSync(fetchHeadPath), false); + + const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd); + + assert.equal(status.behindCount, 1); + assert.equal( + NodeFS.existsSync(fetchHeadPath), + false, + "background status fetch wrote .git/FETCH_HEAD, which an overlapping `git pull` merges from", + ); + }), + ); + it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4130,6 +5536,83 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("does not report a default branch the remote deleted after the clone", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-origin-"); + yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", "development"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", "development", "development:main"]); + yield* git(cwd, ["remote", "set-head", "origin", "development"]); + yield* git(remote, ["--git-dir=.", "symbolic-ref", "HEAD", "refs/heads/main"]); + yield* git(cwd, ["push", "origin", "--delete", "development"]); + yield* git(cwd, ["fetch", "--prune", "origin"]); + + const driver = yield* GitVcsDriver.GitVcsDriver; + const defaultBranch = yield* driver.resolveDefaultBranchName(cwd, "origin"); + + assert.notEqual(defaultBranch, "development"); + for (const refName of ["origin/HEAD", "HEAD~1", "main^", "@{-1}", "-", ":/fix"]) + assert.isNull(yield* driver.resolveWorktreeBaseRemote({ cwd, refName })); + assert.deepEqual( + yield* driver.resolveWorktreeBaseRemote({ cwd, refName: "feature/a\u00a0b" }), + { remoteName: "origin", branchName: "feature/a\u00a0b" }, + ); + }), + ); + + it.effect.each(["checkout", "bare-backed worktree"] as const)( + "uses the only remote's HEAD for default-branch detection without origin in a %s", + (layout) => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const path = yield* Path.Path; + const source = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-github-"); + yield* initRepoWithCommit(source); + yield* git(remote, ["init", "--bare"]); + yield* git(source, ["branch", "-M", "trunk"]); + yield* git(source, ["remote", "add", "github", remote]); + yield* git(source, ["push", "-u", "github", "trunk"]); + let cwd = source; + if (layout === "bare-backed worktree") { + const container = yield* makeTmpDir("git-vcs-driver-bare-"); + const gitDirArgs = ["--git-dir", path.join(container, "repo.git")]; + cwd = path.join(container, "trunk"); + yield* git(container, ["init", "--bare", "repo.git"]); + yield* git(container, [...gitDirArgs, "config", "user.email", "test@test.com"]); + yield* git(container, [...gitDirArgs, "config", "user.name", "Test"]); + yield* git(container, [...gitDirArgs, "remote", "add", "github", remote]); + yield* git(container, [...gitDirArgs, "fetch", "github"]); + yield* git(container, [ + ...gitDirArgs, + "worktree", + "add", + "--track", + "-b", + "trunk", + cwd, + "github/trunk", + ]); + } + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/github/HEAD", + "refs/remotes/github/trunk", + ]); + + assert.isTrue((yield* driver.statusDetailsLocal(cwd)).isDefaultBranch); + const remoteStatus = yield* driver.statusDetailsRemote(cwd); + assert.equal(remoteStatus.defaultBranch, "trunk"); + assert.isTrue(remoteStatus.isDefaultBranch); + + yield* git(cwd, ["remote", "add", "origin", remote]); + assert.isNull((yield* driver.statusDetailsRemote(cwd)).defaultBranch); + }), + ); + it.effect("makes background upstream status fetches non-interactive", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4215,25 +5698,21 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("reports staged file counts on unborn HEAD without failing", () => + it.effect("reports net file counts from the empty tree on unborn HEAD", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const driver = yield* GitVcsDriver.GitVcsDriver; yield* driver.initRepo({ cwd }); - yield* git(cwd, ["config", "user.email", "test@test.com"]); - yield* git(cwd, ["config", "user.name", "Test"]); yield* writeTextFile(cwd, "initial.ts", "// first file\n"); yield* git(cwd, ["add", "initial.ts"]); + yield* writeTextFile(cwd, "initial.ts", "// edited after staging\n"); - const status = yield* driver.statusDetails(cwd); + const status = yield* driver.statusDetailsLocal(cwd); assert.equal(status.isRepo, true); - assert.equal(status.workingTree.files.length, 1); - const file = status.workingTree.files[0]; - if (file) { - assert.equal(file.path, "initial.ts"); - assert.equal(file.insertions, 1); - } + assert.deepStrictEqual(status.workingTree.files, [ + { path: "initial.ts", insertions: 1, deletions: 0 }, + ]); }), ); }); @@ -4407,13 +5886,14 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const { initialBranch } = yield* initRepoWithCommit(cwd); const driver = yield* GitVcsDriver.GitVcsDriver; const oid = yield* git(cwd, ["rev-parse", "HEAD"]); - for (let index = 0; index <= 100; index += 1) { - yield* git(cwd, [ - "update-ref", - `refs/heads/${index === 0 ? "topic" : `topic-${index}`}`, - oid, - ]); - } + yield* gitWithStdin( + cwd, + ["update-ref", "--stdin"], + Array.from( + { length: 101 }, + (_, index) => `create refs/heads/${index === 0 ? "topic" : `topic-${index}`} ${oid}\n`, + ).join(""), + ); const result = yield* driver .renameBranch({ cwd, oldBranch: initialBranch, newBranch: "topic" }) .pipe(Effect.result); @@ -4485,6 +5965,58 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect.each(["untracked", "other-remote"] as const)( + "refuses a remote switch that collides with a local branch (%s)", + (tracking) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", remote]); + yield* git(cwd, ["push", "upstream", "HEAD:refs/heads/feature"]); + yield* git(cwd, ["fetch", "upstream"]); + yield* git(cwd, ["checkout", "--no-track", "-b", "feature"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "Local work"]); + if (tracking === "other-remote") { + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["branch", "--set-upstream-to=origin/feature", "feature"]); + } + const featureHead = yield* git(cwd, ["rev-parse", "feature"]); + const upstream = yield* git(cwd, [ + "for-each-ref", + "--format=%(upstream)", + "refs/heads/feature", + ]); + yield* git(cwd, ["checkout", initialBranch]); + const head = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* writeTextFile(cwd, "README.md", "Uncommitted work\n"); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const result = yield* driver + .switchRef({ cwd, refName: "upstream/feature" }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(result)); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), head); + assert.equal(yield* git(cwd, ["rev-parse", "feature"]), featureHead); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(upstream)", "refs/heads/feature"]), + upstream, + ); + assert.equal( + yield* (yield* FileSystem.FileSystem).readFileString( + (yield* Path.Path).join(cwd, "README.md"), + ), + "Uncommitted work\n", + ); + // Selecting the existing local branch remains an explicit, attached checkout. + assert.equal((yield* driver.switchRef({ cwd, refName: "feature" })).refName, "feature"); + assert.equal(yield* git(cwd, ["symbolic-ref", "HEAD"]), "refs/heads/feature"); + }), + ); + it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4588,13 +6120,179 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("worktree operations", () => { - it.effect("uses parallel checkout without skipping filters or hooks", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.GitVcsDriver; + it.effect.each(["current", "legacy"] as const)( + "preserves another creator's worktree on its new branch at the same path (%s)", + (version) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const path = NodePath.join(yield* makeTmpDir("git-worktrees-"), "contested"); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const reachedAdd = yield* Deferred.make(); + let paused = false; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if ( + ChildProcess.isStandardCommand(command) && + command.args.includes("worktree") && + command.args.includes("add") + ) { + if (command.args.includes("-h")) { + return version === "legacy" + ? makeFailedHandle("usage: git worktree add [--lock]") + : yield* delegate.spawn(command); + } + if (!paused) { + paused = true; + yield* Deferred.succeed(reachedAdd, undefined); + return yield* Effect.never; + } + } + return yield* delegate.spawn(command); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const creator = yield* driver + .createWorktree({ + cwd, + path, + refName: initialBranch, + newRefName: "contested", + }) + .pipe(Effect.forkChild); + yield* Deferred.await(reachedAdd); + yield* git(cwd, ["worktree", "add", "--", path, "contested"]); + yield* writeTextFile(path, "owned-by-B.txt", "keep this work\n"); + yield* Fiber.interrupt(creator); + assert.include(yield* git(cwd, ["worktree", "list", "--porcelain"]), path); + assert.equal(yield* git(path, ["branch", "--show-current"]), "contested"); + assert.equal( + yield* (yield* FileSystem.FileSystem).readFileString( + NodePath.join(path, "owned-by-B.txt"), + ), + "keep this work\n", + ); + const created = yield* driver.createWorktree({ + cwd, + path: `${path}-retry`, + refName: initialBranch, + newRefName: "retry", + }); + assert.equal(yield* git(created.worktree.path, ["branch", "--show-current"]), "retry"); + assert.notInclude(yield* git(cwd, ["worktree", "list", "--porcelain"]), "locked"); + }), + ); + + it.effect.each(["main", "linked"] as const)( + "removes its worktree and branch when cancelled before the claim (%s)", + (checkout) => + Effect.gen(function* () { + const repo = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(repo); + const cwd = + checkout === "main" + ? repo + : NodePath.join(yield* makeTmpDir("git-linked-"), "checkout"); + if (checkout === "linked") { + yield* git(repo, ["config", "worktree.useRelativePaths", "true"]); + yield* git(repo, ["worktree", "add", "--detach", cwd]); + } + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "cancelled ü"); + const hookPath = path.join(repo, ".git/hooks/post-checkout"); + const connected = Promise.withResolvers(); + const sockets = new Set(); + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + sockets.add(socket); + connected.resolve(); + }), + ), + (server) => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + assert.isTrue(address !== null && typeof address !== "string"); + if (address === null || typeof address === "string") return; + const gate = path.join(cwd, "hook-gate.cjs"); + yield* fs.writeFileString( + gate, + `const s = require('node:net').connect(${address.port}, '127.0.0.1'); s.on('connect', () => process.stderr.write('Updating files: 50% (1/1000)\\n')); s.resume();`, + ); + yield* writeTextFile( + repo, + ".git/hooks/post-checkout", + `#!/bin/sh\nexec "${process.execPath.replaceAll("\\", "/")}" "${gate.replaceAll("\\", "/")}"\n`, + ); + yield* fs.chmod(hookPath, 0o755); + const hookStarted = yield* Deferred.make(); + let claims = 0; + const input = { + cwd, + path: worktreePath, + refName: initialBranch, + newRefName: "t3/cancel", + }; + const worktrees = git(cwd, ["worktree", "list", "--porcelain"]); + + const cancelled = yield* driver + .createWorktree(input, { + progress: { + onCheckoutProgress: ({ total }) => + total === 1000 ? Deferred.succeed(hookStarted, undefined) : Effect.void, + onWorktreeClaimed: () => Effect.sync(() => void claims++), + }, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(hookStarted); + yield* Effect.promise(() => connected.promise); + assert.include(yield* worktrees, worktreePath); + yield* Fiber.interrupt(cancelled); + + assert.equal(claims, 0); + assert.notInclude(yield* worktrees, worktreePath); + assert.equal(yield* git(cwd, ["branch", "--list", "t3/cancel"]), ""); + assert.isFalse(yield* fs.exists(worktreePath)); + + // A retry gets the same path and branch, and a claimed worktree outlives a later cancel. + yield* fs.remove(hookPath); + const claimed = yield* Deferred.make(); + const retry = yield* driver + .createWorktree(input, { + progress: { onWorktreeClaimed: () => Deferred.succeed(claimed, undefined) }, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(claimed); + yield* Fiber.interrupt(retry); + assert.include(yield* worktrees, worktreePath); + assert.notInclude(yield* worktrees, "locked"); + assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "t3/cancel"); + }), + ); + + it.effect("uses parallel checkout without skipping filters or hooks", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; yield* git(cwd, ["config", "filter.test.smudge", "sed s/original/filtered/g"]); yield* writeTextFile(cwd, ".gitattributes", "asset.txt filter=test\n"); yield* writeTextFile(cwd, "asset.txt", "original\n"); @@ -4644,6 +6342,19 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { `${expected}\n`, ); } + yield* writeTextFile( + cwd, + ".git/hooks/post-checkout", + '#!/bin/sh\ngit worktree unlock "$PWD" 2>/dev/null || :\ngit worktree lock --reason user-kept "$PWD"\n', + ); + const lockedPath = path.join(yield* makeTmpDir("git-worktrees-"), "hook-locked"); + yield* driver.createWorktree({ + cwd, + path: lockedPath, + refName: initialBranch, + newRefName: "feature/hook-locked", + }); + assert.include(yield* git(cwd, ["worktree", "list", "--porcelain"]), "locked user-kept"); }), ); @@ -4678,6 +6389,114 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isTrue(Result.isSuccess(result), "worktree creation failed in the hook"); }), ); + // regression: #25367 a checkout that writes over 1 MB to stderr failed on the output cap + it.effect.each([false, true])( + "creates the worktree when git worktree add writes over 1 MB (progress: %s)", + (withProgress) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* writeTextFile( + cwd, + ".git/hooks/post-checkout", + "#!/bin/sh\nhead -c 1100000 /dev/zero | tr '\\0' x >&2\nexit 0\n", + ); + yield* fs.chmod(path.join(cwd, ".git/hooks/post-checkout"), 0o755); + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "noisy"); + + const result = yield* driver + .createWorktree( + { cwd, path: worktreePath, refName: initialBranch, newRefName: "t3/noisy" }, + withProgress ? { progress: { onCheckoutProgress: () => Effect.void } } : undefined, + ) + .pipe(Effect.result); + + assert.isTrue( + Result.isSuccess(result), + Result.isFailure(result) ? result.failure.message : "", + ); + assert.equal( + yield* git(worktreePath, ["rev-parse", "HEAD"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + }), + ); + it.effect("refreshes a new worktree's index once its checkout second is over", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + for (let file = 0; file < 50; file++) { + yield* writeTextFile(cwd, `src/file-${file}.txt`, `contents ${file}\n`); + } + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "more files"]); + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "fresh"); + + // The refresh waits on the clock that stamps the files. + yield* TestClock.withLive( + driver.createWorktree({ + cwd, + path: worktreePath, + refName: initialBranch, + newRefName: "feature/fresh", + }), + ); + + // Git re-reads every entry stamped in the index's own second or later. + const indexPath = path.resolve( + worktreePath, + yield* git(worktreePath, ["rev-parse", "--git-path", "index"]), + ); + const indexMtime = Option.getOrThrow((yield* fs.stat(indexPath)).mtime); + const indexSecond = Math.floor(indexMtime.getTime() / 1000); + const entrySeconds = Array.from( + (yield* git(worktreePath, ["ls-files", "--debug"])).matchAll(/^ {2}mtime: (\d+):/gm), + ([, seconds]) => Number(seconds), + ); + assert.equal(entrySeconds.length, 51); + assert.deepEqual( + entrySeconds.filter((seconds) => seconds >= indexSecond), + [], + ); + }), + ); + it.effect("returns the worktree when its index refresh fails", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + // Something else takes the new worktree's index lock as soon as its checkout ends. + yield* writeTextFile( + cwd, + ".git/hooks/post-checkout", + '#!/bin/sh\ntouch "$(git rev-parse --git-path index).lock"\n', + ); + yield* fs.chmod(path.join(cwd, ".git/hooks/post-checkout"), 0o755); + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "locked"); + + const created = yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: initialBranch, + newRefName: "feature/locked", + }); + + assert.equal(created.worktree.path, worktreePath); + const indexPath = path.resolve( + worktreePath, + yield* git(worktreePath, ["rev-parse", "--git-path", "index"]), + ); + assert.isTrue(yield* fs.exists(`${indexPath}.lock`)); + }), + ); it.effect.each(["commit", "short-commit", "tag", "revision"] as const)( "creates a worktree from a %s without recording it as a PR base", (kind) => @@ -4713,6 +6532,28 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("explains a new branch that collides with an existing branch namespace", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "werkstatt"]); + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const error = yield* driver + .createWorktree({ + cwd, + path: path.join(yield* makeTmpDir("git-worktrees-"), "conflict"), + refName: initialBranch, + newRefName: "werkstatt/baseline", + }) + .pipe(Effect.flip); + + assert.equal(error._tag, "GitCommandError"); + assert.equal(error.operation, "GitVcsDriver.createWorktree.createBranch"); + assert.equal(error.reason, "ref_name_conflict"); + }), + ); + // regression: #28354 a failed worktree add left its new branch behind and blocked retries it.effect("removes the new branch when the worktree cannot be added", () => Effect.gen(function* () { @@ -4824,6 +6665,44 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("gives parallel renames to one generated name distinct branches", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const path = yield* Path.Path; + const worktrees = yield* makeTmpDir("git-worktrees-"); + const driver = yield* GitVcsDriver.GitVcsDriver; + // A multi-model send launches one worktree per model with the same message, so their + // generated names often match and the renames can land together. + const temporaryBranches = ["t3/aaaa1111", "t3/bbbb2222", "t3/cccc3333"]; + yield* Effect.forEach(temporaryBranches, (branch) => + driver.createWorktree({ + cwd, + path: path.join(worktrees, branch.replace("/", "-")), + refName: initialBranch, + newRefName: branch, + }), + ); + + const renamed = yield* Effect.forEach( + temporaryBranches, + (branch) => + driver.renameBranch({ + cwd: path.join(worktrees, branch.replace("/", "-")), + oldBranch: branch, + newBranch: "feat/add-search", + }), + { concurrency: "unbounded" }, + ); + + assert.deepStrictEqual(renamed.map((result) => result.branch).toSorted(), [ + "feat/add-search", + "feat/add-search-1", + "feat/add-search-2", + ]); + }), + ); + it.effect.each(["release/v2", "refs/heads/release/v2", "deadbeef"])( "records the branch name when creating a worktree from %s", (baseRef) => @@ -4943,7 +6822,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(cwd, ["submodule", "add", submoduleRepo, "shared"]); + // A file URL transfers a pack like a network remote; a plain path hardlinks silently. + yield* git(cwd, ["submodule", "add", NodeURL.pathToFileURL(submoduleRepo).href, "shared"]); yield* git(cwd, ["commit", "-m", "add submodule"]); const recordedHead = yield* git(submoduleRepo, ["rev-parse", "HEAD"]); yield* writeTextFile(submoduleRepo, "SHARED.md", "# newer remote default\n"); @@ -5018,7 +6898,11 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(pathService.join(worktreePath, "shared"), ["status", "--porcelain"]), "", ); - if (progress) assert.isNotEmpty(yield* Ref.get(lines)); + if (progress) { + assert.isTrue( + (yield* Ref.get(lines)).some((line) => line.startsWith("Receiving objects")), + ); + } }).pipe(withGitFileProtocol), ); @@ -5027,12 +6911,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const fileSystem = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; + const submoduleRepo = yield* makeTmpDir("git-submodule-"); + yield* initRepoWithCommit(submoduleRepo); + const cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* writeTextFile( - cwd, - ".gitmodules", - '[submodule "missing"]\n\tpath = missing\n\turl = /nonexistent/repo.git\n', + yield* git(cwd, ["submodule", "add", NodeURL.pathToFileURL(submoduleRepo).href, "shared"]); + yield* fileSystem.writeFileString( + pathService.join(cwd, ".gitmodules"), + (yield* fileSystem.readFileString(pathService.join(cwd, ".gitmodules"))) + + '[submodule "missing"]\n\tpath = missing\n\turl = /nonexistent/repo.git\n', ); yield* git(cwd, ["add", "."]); const gitlink = yield* git(cwd, ["rev-parse", "HEAD"]); @@ -5065,7 +6953,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.lengthOf(results, 1); assert.isFalse(results[0]!.ok); assert.include(results[0]!.detail, "GitVcsDriver.createWorktree.updateSubmodules"); - }), + // A submodule that did clone must not be left as a bare gitdir that reads as modified. + assert.equal(yield* git(worktreePath, ["status", "--porcelain"]), ""); + }).pipe(withGitFileProtocol), ); it.effect("creates worktrees under the configured worktrees directory", () => @@ -5091,6 +6981,22 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { ); assert.equal(yield* fileSystem.exists(created.worktree.path), true); + yield* git(cwd, ["worktree", "remove", "--force", created.worktree.path]); + yield* git(cwd, ["branch", "-D", "feature/custom-dir"]); + yield* fileSystem.makeDirectory(created.worktree.path); + const leftover = pathService.join(created.worktree.path, "notes.txt"); + yield* fileSystem.writeFileString(leftover, "my notes"); + const recreated = yield* driver.createWorktree( + { cwd, path: null, refName: initialBranch, newRefName: "feature/custom-dir" }, + { worktreesDirectory }, + ); + assert.notEqual(recreated.worktree.path, created.worktree.path); + assert.equal( + yield* git(recreated.worktree.path, ["branch", "--show-current"]), + "feature/custom-dir", + ); + assert.deepEqual(yield* fileSystem.readDirectory(created.worktree.path), ["notes.txt"]); + const error = yield* driver .createWorktree( { cwd, path: null, refName: initialBranch, newRefName: "feature/relative-dir" }, @@ -5371,6 +7277,41 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect.skipIf(!symlinksSupported)( + "removes a worktree whose .git file git-annex replaced with a symlink, keeping the symlink when refused", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const pathService = yield* Path.Path; + const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "annexed"); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: initialBranch, + newRefName: "feature/annexed", + }); + const gitFile = pathService.join(worktreePath, ".git"); + const adminDir = (yield* git(worktreePath, ["rev-parse", "--absolute-git-dir"])).trim(); + NodeFS.rmSync(gitFile); + NodeFS.symlinkSync(adminDir, gitFile); + yield* writeTextFile(worktreePath, "notes.txt", "draft\n"); + + const refused = yield* Effect.result(driver.removeWorktree({ cwd, path: worktreePath })); + + assert.isTrue(Result.isFailure(refused)); + assert.isTrue(NodeFS.lstatSync(gitFile).isSymbolicLink()); + assert.equal(NodeFS.realpathSync(gitFile), NodeFS.realpathSync(adminDir)); + NodeFS.rmSync(pathService.join(worktreePath, "notes.txt")); + + yield* driver.removeWorktree({ cwd, path: worktreePath }); + + assert.isFalse(NodeFS.existsSync(worktreePath)); + assert.isFalse(NodeFS.existsSync(adminDir)); + }), + ); + it.effect("leaves a folder alone that only shares the worktree's short name", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -5495,6 +7436,112 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("remote operations", () => { + it.effect.each([ + { + configuration: "ordinary", + fetchRefspecs: ["+refs/heads/*:refs/remotes/origin/*"], + addsMapping: false, + }, + { + configuration: "restricted", + fetchRefspecs: [ + "+refs/heads/main:refs/remotes/origin/main", + "+refs/heads/team/*:refs/remotes/origin/team/*", + "+refs/heads/release/release-*:refs/remotes/origin/release/release-*", + ], + addsMapping: true, + }, + ])( + "sets a fetched branch's upstream with $configuration fetch configuration", + ({ fetchRefspecs, addsMapping }) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["config", "--unset-all", "remote.origin.fetch"]); + for (const refspec of fetchRefspecs) { + yield* git(cwd, ["config", "--add", "remote.origin.fetch", refspec]); + } + const remoteBranch = "feature/example-change"; + const branch = "review/example-change"; + const mapping = `+refs/heads/${remoteBranch}*:refs/remotes/origin/${remoteBranch}*`; + yield* git(cwd, [ + "push", + remote, + "HEAD:refs/heads/main", + `HEAD:refs/heads/${remoteBranch}`, + ]); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.fetchRemoteTrackingBranch({ cwd, remoteName: "origin", remoteBranch }); + yield* git(cwd, ["checkout", "--no-track", "-b", branch, `origin/${remoteBranch}`]); + + const input = { cwd, branch, remoteName: "origin", remoteBranch }; + yield* driver.setBranchUpstream(input); + yield* driver.setBranchUpstream(input); + + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", `${branch}@{upstream}`]), + `origin/${remoteBranch}`, + ); + assert.equal(yield* git(cwd, ["config", `branch.${branch}.remote`]), "origin"); + assert.equal( + yield* git(cwd, ["config", `branch.${branch}.merge`]), + `refs/heads/${remoteBranch}`, + ); + assert.deepEqual( + (yield* git(cwd, ["config", "--get-all", "remote.origin.fetch"])).split("\n"), + addsMapping ? [...fetchRefspecs, mapping] : fetchRefspecs, + ); + // A merged PR's head is deleted; later fetches of the remote must keep working. + yield* git(remote, ["--git-dir", remote, "branch", "-D", remoteBranch]); + yield* git(cwd, ["fetch", "origin"]); + }), + ); + + it.effect.each(["ordinary", "restricted"] as const)( + "retries upstream configuration with a config lock and %s fetch mappings", + (configuration) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "origin", "https://example.invalid/repo.git"]); + if (configuration === "restricted") { + yield* git(cwd, [ + "config", + "remote.origin.fetch", + `+refs/heads/${initialBranch}:refs/remotes/origin/${initialBranch}`, + ]); + } + yield* git(cwd, ["branch", "review/pr-head"]); + yield* git(cwd, ["update-ref", "refs/remotes/origin/pr-head", "HEAD"]); + const lockPath = (yield* Path.Path).join(cwd, ".git", "config.lock"); + yield* (yield* FileSystem.FileSystem).writeFileString(lockPath, ""); + const { driver, failures } = yield* makeDriverReleasingLock( + configuration === "restricted" + ? (args) => args[0] === "config" && args[1] === "--add" + : (args) => args.includes("--set-upstream-to"), + lockPath, + ); + + yield* TestClock.withLive( + driver.setBranchUpstream({ + cwd, + branch: "review/pr-head", + remoteName: "origin", + remoteBranch: "pr-head", + }), + ); + + assert.equal(yield* Ref.get(failures), 1); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "review/pr-head@{upstream}"]), + "origin/pr-head", + ); + }), + ); + it.effect("ensureRemote reuses a partial clone remote and avoids its name", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -5519,7 +7566,62 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("ensureRemote returns the remote a parallel call added for the same URL", () => + it.effect.each(["\n", "\r\n"])( + "ensureRemote preserves spaces in fetch URLs and reserves their names (%j)", + (lineEnding) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fetchUrl = " ../team repos/shared (fetch) [blob:none].git "; + const pushUrl = "../team repos/push (push).git"; + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", fetchUrl]); + yield* git(cwd, ["remote", "set-url", "--push", "origin", pushUrl]); + yield* git(cwd, ["config", "remote.origin.promisor", "true"]); + yield* git(cwd, ["config", "remote.origin.partialclonefilter", "blob:none"]); + const liveDriver = yield* GitVcsDriver.GitVcsDriver; + const listing = yield* liveDriver.execute({ + cwd, + args: ["remote", "-v"], + operation: "test", + }); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => + ChildProcess.isStandardCommand(command) && + command.args[0] === "remote" && + command.args[1] === "-v" + ? Effect.succeed(makeSuccessfulHandle(listing.stdout.replace(/\r?\n/g, lineEnding))) + : delegate.spawn(command), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + + assert.equal( + yield* driver.ensureRemote({ cwd, preferredName: "origin", url: fetchUrl }), + "origin", + ); + assert.equal( + yield* driver.ensureRemote({ cwd, preferredName: "origin", url: pushUrl }), + "origin-1", + ); + const fetch = yield* liveDriver.execute({ + cwd, + args: ["config", "--get", "remote.origin.url"], + operation: "test", + }); + const push = yield* liveDriver.execute({ + cwd, + args: ["config", "--get", "remote.origin.pushurl"], + operation: "test", + }); + assert.equal(fetch.stdout, `${fetchUrl}\n`); + assert.equal(push.stdout, `${pushUrl}\n`); + assert.equal(yield* git(cwd, ["config", "--get", "remote.origin-1.url"]), pushUrl); + }), + ); + + it.effect("ensureRemote returns the remote a parallel call added for the same URL", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); yield* git(cwd, ["init"]); @@ -5575,39 +7677,82 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("tracks a remote start point once another process releases the config lock", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", initialBranch]); - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const lockPath = path.join(cwd, ".git", "config.lock"); - yield* fileSystem.writeFileString(lockPath, ""); - const { driver, failures } = yield* makeDriverReleasingLock( - (args) => args.some((arg) => arg.startsWith("--set-upstream-to")), - lockPath, - ); + it.effect.each(["createWorktree", "switchRef"] as const)( + "tracks a remote start point once another process releases the config lock: %s", + (operation) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `${initialBranch}:refs/heads/feature/tracked`]); + yield* git(cwd, ["fetch", "origin"]); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const lockPath = path.join(cwd, ".git", "config.lock"); + yield* fileSystem.writeFileString(lockPath, ""); + const { driver, failures } = yield* makeDriverReleasingLock( + (args) => args.some((arg) => arg.startsWith("--set-upstream-to")), + lockPath, + ); - // The upstream retry waits on the real clock; the lock is already gone by then. - yield* TestClock.withLive( - driver.createWorktree({ - cwd, - path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"), - refName: `origin/${initialBranch}`, - newRefName: "feature/tracked", - }), - ); + // The upstream retry waits on the real clock; the lock is already gone by then. + if (operation === "createWorktree") { + yield* TestClock.withLive( + driver.createWorktree({ + cwd, + path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"), + refName: "origin/feature/tracked", + newRefName: "feature/tracked", + }), + ); + } else { + const switched = yield* TestClock.withLive( + driver.switchRef({ cwd, refName: "origin/feature/tracked" }), + ); + assert.equal(switched.refName, "feature/tracked"); + } - assert.equal(yield* Ref.get(failures), 1); - assert.equal( - yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]), - `origin/${initialBranch}`, - ); - }), + assert.equal(yield* Ref.get(failures), 1); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]), + "origin/feature/tracked", + ); + }), + ); + + it.effect( + "leaves no untracked branch behind when the config stays locked during a switch", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", remote]); + yield* git(cwd, ["push", "upstream", `${initialBranch}:refs/heads/feature`]); + yield* git(cwd, ["fetch", "upstream"]); + const fileSystem = yield* FileSystem.FileSystem; + const lockPath = (yield* Path.Path).join(cwd, ".git", "config.lock"); + yield* fileSystem.writeFileString(lockPath, ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + // The upstream retry waits on the real clock before giving up. + yield* TestClock.withLive(driver.switchRef({ cwd, refName: "upstream/feature" })).pipe( + Effect.flip, + ); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal(yield* git(cwd, ["branch", "--list", "feature"]), ""); + + yield* fileSystem.remove(lockPath); + const switched = yield* driver.switchRef({ cwd, refName: "upstream/feature" }); + assert.equal(switched.refName, "feature"); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature@{upstream}"]), + "upstream/feature", + ); + }), ); it.effect("fetches a remote branch into a tracking branch past another process's lock", () => @@ -5746,6 +7891,60 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("commit context", () => { + it.effect("reads history through a chain of shared clones", () => + Effect.gen(function* () { + const root = yield* makeTmpDir(); + const fileSystem = yield* FileSystem.FileSystem; + const driver = yield* GitVcsDriver.GitVcsDriver; + const seed = `${root}/clone-0`; + yield* fileSystem.makeDirectory(seed); + yield* initRepoWithCommit(seed); + let previous = seed; + for (let index = 1; index <= 6; index += 1) { + const next = `${root}/clone-${index}`; + yield* git(root, ["clone", "--quiet", "--shared", previous, next]); + previous = next; + } + // Six shared clones deep is within Git's alternate limit, not one level deeper. + yield* writeTextFile(previous, "README.md", "changed\n"); + const chained = yield* driver.prepareCommitContext(previous, ["README.md"]); + assert.include(chained?.stagedSummary ?? "", "M\tREADME.md"); + assert.include(chained?.stagedPatch ?? "", "-# test"); + }), + ); + + it.effect("leaves no objects behind when no commit follows, in a linked worktree too", () => + Effect.gen(function* () { + const repo = yield* makeTmpDir(); + yield* initRepoWithCommit(repo); + const linked = `${repo}/linked`; + yield* git(repo, ["worktree", "add", "--quiet", linked]); + const driver = yield* GitVcsDriver.GitVcsDriver; + + for (const cwd of [repo, linked]) { + yield* writeTextFile(cwd, "README.md", `changed in ${cwd}\n`); + yield* writeTextFile(cwd, "draft.txt", `drafted in ${cwd}\n`); + const blobs = [ + yield* git(cwd, ["hash-object", "draft.txt"]), + yield* git(cwd, ["hash-object", "README.md"]), + ]; + const context = yield* driver.prepareCommitContext(cwd); + assert.include(context?.stagedPatch ?? "", `+drafted in ${cwd}`); + assert.include(context?.stagedPatch ?? "", "-# test"); + for (const blob of blobs) { + const probe = yield* driver.execute({ + operation: "GitVcsDriver.test.git", + cwd, + args: ["cat-file", "-e", blob], + allowNonZeroExit: true, + timeoutMs: 10_000, + }); + assert.notEqual(probe.exitCode, 0, `${blob} stayed in the repository`); + } + } + }), + ); + it.effect("prepares source patches without running textconv", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -5792,28 +7991,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("prepares selected files without staging and commits only those files", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - - yield* writeTextFile(cwd, "a.txt", "a\n"); - yield* writeTextFile(cwd, "b.txt", "b\n"); - - const context = yield* driver.prepareCommitContext(cwd, ["a.txt"]); - assert.include(context?.stagedSummary ?? "", "a.txt"); - assert.notInclude(context?.stagedSummary ?? "", "b.txt"); - assert.equal(yield* git(cwd, ["diff", "--cached", "--name-only"]), ""); + it.effect.each(["root", "aliased-nested"] as const)( + "prepares selected files without staging and commits only those files from %s", + (location) => + Effect.gen(function* () { + const sandbox = yield* makeTmpDir(); + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const repository = path.join(sandbox, "repo"); + const nested = path.join(repository, "sub", "dir"); + yield* fileSystem.makeDirectory(nested, { recursive: true }); + yield* initRepoWithCommit(repository); + const cwd = location === "aliased-nested" ? path.join(sandbox, "link") : repository; + if (location === "aliased-nested") NodeFS.symlinkSync(nested, cwd, "junction"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const selected = "sub/dir/a.txt"; + yield* writeTextFile(repository, selected, "a\n"); + yield* writeTextFile(repository, "b.txt", "b\n"); - const commit = yield* driver.commit(cwd, "Add a", "", { stage: { filePaths: ["a.txt"] } }); - assert.match(commit.commitSha, /^[a-f0-9]{40}$/); - assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "Add a"); + const context = yield* driver.prepareCommitContext(cwd, [selected]); + assert.include(context?.stagedSummary ?? "", "a.txt"); + assert.notInclude(context?.stagedSummary ?? "", "b.txt"); + assert.equal(yield* git(repository, ["diff", "--cached", "--name-only"]), ""); - const status = yield* git(cwd, ["status", "--porcelain"]); - assert.include(status, "?? b.txt"); - assert.notInclude(status, "a.txt"); - }), + const commit = yield* driver.commit(cwd, "Add a", "", { + stage: { filePaths: [selected] }, + }); + assert.match(commit.commitSha, /^[a-f0-9]{40}$/); + assert.equal(yield* git(repository, ["log", "-1", "--pretty=%s"]), "Add a"); + assert.equal( + yield* git(repository, ["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"]), + selected, + ); + const status = yield* git(repository, ["status", "--porcelain"]); + assert.include(status, "?? b.txt"); + assert.notInclude(status, "a.txt"); + }), ); it.effect("stops a selected-file commit when another process holds the index lock", () => @@ -5886,30 +8099,49 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { ); it.effect.each([ - { location: "root", conflict: false }, - { location: "nested", conflict: false }, - { location: "worktree", conflict: false }, - { location: "root", conflict: true }, - { location: "nested", conflict: true }, - { location: "worktree", conflict: true }, + { location: "root", conflict: false, encoding: "utf8" }, + { location: "nested", conflict: false, encoding: "utf8" }, + { location: "worktree", conflict: false, encoding: "utf8" }, + { location: "root", conflict: true, encoding: "utf8" }, + { location: "nested", conflict: true, encoding: "utf8" }, + { location: "worktree", conflict: true, encoding: "utf8" }, + { location: "root", conflict: true, encoding: "utf16le" }, + { location: "root", conflict: true, encoding: "utf16le", large: true }, ])( - "rejects selected-file merge commits without mutation ($location, conflict: $conflict)", - ({ location, conflict }) => + "rejects selected-file merge commits without mutation ($location, conflict: $conflict, $encoding)", + ({ location, conflict, encoding, large }) => Effect.gen(function* () { let cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); + const writeReadme = (text: string) => + Effect.sync(() => + NodeFS.writeFileSync( + NodePath.join(cwd, "README.md"), + encoding === "utf16le" ? Buffer.from(`\ufeff${text}`, "utf16le") : text, + ), + ); + if (encoding === "utf16le") { + yield* writeTextFile( + cwd, + ".gitattributes", + "README.md text working-tree-encoding=UTF-16\n", + ); + yield* writeReadme("base\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "Declare UTF-16 encoding"]); + } const driver = yield* GitVcsDriver.GitVcsDriver; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; yield* git(cwd, ["checkout", "-b", "feature"]); yield* writeTextFile(cwd, "feature.txt", "feature\n"); - if (conflict) yield* writeTextFile(cwd, "README.md", "feature version\n"); + if (conflict) yield* writeReadme("feature version\n"); yield* git(cwd, ["add", "."]); yield* git(cwd, ["commit", "-m", "Feature"]); const featureHead = yield* git(cwd, ["rev-parse", "HEAD"]); yield* git(cwd, ["checkout", initialBranch]); yield* writeTextFile(cwd, "main.txt", "main\n"); - if (conflict) yield* writeTextFile(cwd, "README.md", "main version\n"); + if (conflict) yield* writeReadme("main version\n"); yield* git(cwd, ["add", "."]); yield* git(cwd, ["commit", "-m", "Main"]); const mainHead = yield* git(cwd, ["rev-parse", "HEAD"]); @@ -5958,7 +8190,20 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), mainHead); assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); - if (conflict) yield* writeTextFile(cwd, "README.md", "resolved version\n"); + const resolvedText = `Heading\n=======\n\nresolved${large ? "x".repeat(17 * 1024 * 1024) : ""}\n`; + if (conflict) { + const unresolved = yield* driver + .commit(commitCwd, "Unresolved merge", "", { stage: {} }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(unresolved), "committed an unresolved conflict"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), mainHead); + assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); + // A lone "=======" is a heading underline, not a conflict boundary. + yield* writeReadme(resolvedText); + assert.isNotNull( + yield* driver.prepareCommitContext(commitCwd, undefined, { includePatch: false }), + ); + } yield* driver.commit(commitCwd, "Finish merge", "", { stage: {} }); assert.equal( yield* git(cwd, ["show", "-s", "--format=%P", "HEAD"]), @@ -5967,11 +8212,155 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isFalse(NodeFS.existsSync(path.join(gitDir, "MERGE_HEAD"))); assert.equal(yield* git(cwd, ["show", "HEAD:feature.txt"]), "feature"); assert.equal(yield* git(cwd, ["show", "HEAD:unrelated.txt"]), "unrelated"); - if (conflict) - assert.equal(yield* git(cwd, ["show", "HEAD:README.md"]), "resolved version"); + if (large) { + assert.equal( + yield* git(cwd, ["cat-file", "-s", "HEAD:README.md"]), + String(Buffer.byteLength(resolvedText)), + ); + } else if (conflict) + assert.equal( + yield* git(cwd, ["show", "HEAD:README.md"]), + "Heading\n=======\n\nresolved", + ); + }), + ); + + it.effect("reports a merge resolved to HEAD's tree as committable", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + // A branch named MERGE_HEAD is not a merge in progress. + yield* git(cwd, ["branch", "MERGE_HEAD"]); + assert.isNull(yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false })); + yield* git(cwd, ["branch", "-D", "MERGE_HEAD"]); + yield* git(cwd, ["checkout", "-b", "feature"]); + yield* writeTextFile(cwd, "README.md", "feature version\n"); + yield* git(cwd, ["commit", "-am", "Feature"]); + yield* git(cwd, ["checkout", initialBranch]); + yield* writeTextFile(cwd, "README.md", "main version\n"); + yield* git(cwd, ["commit", "-am", "Main"]); + const merge = yield* driver.execute({ + operation: "test.merge", + cwd, + args: ["merge", "feature"], + allowNonZeroExit: true, + }); + assert.equal(merge.exitCode, 1); + yield* writeTextFile(cwd, "README.md", "main version\n"); + + assert.isNotNull( + yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false }), + ); + }), + ); + + it.effect.each([ + { operation: "cherry-pick", head: "CHERRY_PICK_HEAD", refs: "files" }, + { operation: "revert", head: "REVERT_HEAD", refs: "files" }, + // Reftable keeps CHERRY_PICK_HEAD and REVERT_HEAD as refs with no file under .git. + { operation: "cherry-pick", head: "CHERRY_PICK_HEAD", refs: "reftable" }, + { operation: "revert", head: "REVERT_HEAD", refs: "reftable" }, + ])( + "rejects selected-file commits during a $operation ($refs)", + ({ operation, head, refs }, ctx) => + Effect.gen(function* () { + if (refs === "reftable" && !gitHasReftable) + return ctx.skip("Needs Git 2.45 or later for reftable."); + const cwd = yield* makeTmpDir(); + if (refs === "reftable") yield* commitInitialRepo(cwd, ["--ref-format=reftable"]); + else yield* initRepoWithCommit(cwd); + // Reftable leaves .git/HEAD as a stub, so ask Git for the branch. + const initialBranch = yield* git(cwd, ["symbolic-ref", "--short", "HEAD"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["checkout", "-b", "other"]); + yield* writeTextFile(cwd, "README.md", "other version\n"); + yield* writeTextFile(cwd, "picked.txt", "picked\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "Other"]); + if (operation === "cherry-pick") yield* git(cwd, ["checkout", initialBranch]); + yield* writeTextFile(cwd, "README.md", "main version\n"); + yield* git(cwd, ["commit", "-am", "Main"]); + const originalHead = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, ["branch", head]); + const result = yield* driver.execute({ + operation: `test.${operation}`, + cwd, + args: [operation, operation === "cherry-pick" ? "other" : "HEAD~1"], + allowNonZeroExit: true, + }); + assert.equal(result.exitCode, 1); + yield* writeTextFile(cwd, "README.md", "resolved version\n"); + yield* git(cwd, ["add", "README.md"]); + const selected = operation === "cherry-pick" ? "picked.txt" : "README.md"; + + const commit = yield* driver + .commit(cwd, "Partial", "", { stage: { filePaths: [selected] } }) + .pipe(Effect.result); + + assert.isTrue(Result.isFailure(commit), `Selected-file ${operation} commit succeeded`); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), originalHead); + assert.equal( + yield* git(cwd, [ + "-c", + "core.warnAmbiguousRefs=false", + "rev-parse", + "--verify", + "--symbolic-full-name", + head, + ]), + head, + ); }), ); + it.effect("rejects selected-file commits during a multi-commit no-commit cherry-pick", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "a.txt", "base a\n"); + yield* writeTextFile(cwd, "b.txt", "base b\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "Base"]); + yield* git(cwd, ["checkout", "-b", "feature"]); + yield* writeTextFile(cwd, "a.txt", "feature a\n"); + yield* writeTextFile(cwd, "b.txt", "feature b\n"); + yield* git(cwd, ["commit", "-am", "Feature one"]); + yield* writeTextFile(cwd, "later.txt", "later\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "Feature two"]); + yield* git(cwd, ["checkout", initialBranch]); + yield* writeTextFile(cwd, "a.txt", "main a\n"); + yield* writeTextFile(cwd, "b.txt", "main b\n"); + yield* git(cwd, ["commit", "-am", "Main"]); + const head = yield* git(cwd, ["rev-parse", "HEAD"]); + const started = yield* driver.execute({ + operation: "test.sequencer", + cwd, + args: ["cherry-pick", "--no-commit", "feature~1", "feature"], + allowNonZeroExit: true, + }); + assert.equal(started.exitCode, 1); + yield* writeTextFile(cwd, "a.txt", "resolved a\n"); + const gitDir = yield* git(cwd, ["rev-parse", "--absolute-git-dir"]); + assert.isFalse(NodeFS.existsSync(path.join(gitDir, "CHERRY_PICK_HEAD"))); + const names = ["index", "sequencer/todo", "sequencer/head"]; + const before = names.map((name) => NodeFS.readFileSync(path.join(gitDir, name))); + + const error = yield* driver + .commit(cwd, "Partial", "", { stage: { filePaths: ["a.txt"] } }) + .pipe(Effect.flip); + assert.include(error.detail, "Cannot commit selected files during a cherry-pick or revert"); + assert.deepEqual( + names.map((name) => NodeFS.readFileSync(path.join(gitDir, name))), + before, + ); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), head); + }), + ); + it.effect("treats selected file paths literally", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -5999,6 +8388,53 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("keeps other files conflicted through a selected-file commit", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + // git stash pop leaves README.md conflicted with no merge in progress. + yield* writeTextFile(cwd, "README.md", "stashed version\n"); + yield* git(cwd, ["stash"]); + yield* writeTextFile(cwd, "README.md", "committed version\n"); + yield* git(cwd, ["commit", "-am", "Change README"]); + const pop = yield* driver.execute({ + operation: "test.stashPop", + cwd, + args: ["stash", "pop"], + allowNonZeroExit: true, + }); + assert.equal(pop.exitCode, 1); + yield* writeTextFile(cwd, "other.txt", "other\n"); + const head = yield* git(cwd, ["rev-parse", "HEAD"]); + const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nested = path.join(cwd, "nested"); + yield* fs.makeDirectory(nested); + // A formatting hook stages its edit into the temporary index that --only commits from. + yield* writeTextFile( + cwd, + ".git/hooks/pre-commit", + "#!/bin/sh\necho formatted >> other.txt\ngit add other.txt\n", + ); + yield* fs.chmod(path.join(cwd, ".git/hooks/pre-commit"), 0o755); + + yield* driver.commit(cwd, "Add other", "", { stage: { filePaths: ["other.txt"] } }); + + assert.equal(yield* git(cwd, ["rev-parse", "HEAD~1"]), head); + assert.equal(yield* git(cwd, ["show", "--pretty=", "--name-only", "HEAD"]), "other.txt"); + assert.equal(yield* git(cwd, ["show", "HEAD:other.txt"]), "other\nformatted"); + assert.equal(yield* git(cwd, ["show", ":other.txt"]), "other\nformatted"); + assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); + const all = yield* driver.prepareCommitContext(nested).pipe(Effect.flip); + assert.equal( + all.detail, + "Cannot commit with unresolved merge conflicts in README.md. Resolve them, then commit.", + ); + }), + ); + const commitWithHooks = (hooks: Record) => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -6293,7 +8729,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); const changes = preview.sources.find((source) => source.kind === "branch-range")!; assert.deepStrictEqual(changes.files, [ - { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, + { + path: "feature.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, ]); assert.include(changes.diff, "+feature work"); assert.notInclude(changes.diff, "upstream-only work"); @@ -6395,7 +8837,70 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("pushes with upstream setup and skips when already up to date", () => + it.effect.each([false, true])( + "pushes with upstream setup and skips when already up to date (autoSetupMerge=%s)", + (autoSetupMerge) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + if (autoSetupMerge) { + yield* git(cwd, ["config", "branch.autoSetupMerge", "always"]); + } + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* (yield* GitVcsDriver.GitVcsDriver).createRef({ + cwd, + refName: "feature/push", + }); + yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({ + cwd, + refName: "feature/push", + }); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "-A"]); + yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add feature", ""); + + const driver = yield* GitVcsDriver.GitVcsDriver; + if (autoSetupMerge) { + assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/push.remote"), "."); + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/push.merge"), + `refs/heads/${initialBranch}`, + ); + } + + const pushed = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null); + assert.deepInclude(pushed, { + status: "pushed", + branch: "feature/push", + setUpstream: true, + }); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + "origin/feature/push", + ); + + if (autoSetupMerge) { + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/push.t3-merge-base"), + initialBranch, + ); + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/push.t3-merge-base-ref"), + `refs/heads/${initialBranch}`, + ); + } + + const skipped = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null); + assert.deepInclude(skipped, { + status: "skipped_up_to_date", + branch: "feature/push", + }); + }), + ); + + it.effect("republishes a branch whose upstream was deleted", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-remote-"); @@ -6414,22 +8919,70 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["add", "-A"]); yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add feature", ""); - const pushed = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null); - assert.deepInclude(pushed, { - status: "pushed", - branch: "feature/push", - setUpstream: true, - }); + yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null); + + yield* git(cwd, ["push", "origin", "--delete", "feature/push"]); + yield* writeTextFile(cwd, "followup.txt", "followup\n"); + yield* git(cwd, ["add", "-A"]); + yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add followup", ""); + const republished = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null); + assert.deepInclude(republished, { status: "pushed", branch: "feature/push" }); assert.equal( - yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), - "origin/feature/push", + yield* git(remote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + yield* git(cwd, ["rev-parse", "HEAD"]), ); - const skipped = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null); - assert.deepInclude(skipped, { - status: "skipped_up_to_date", - branch: "feature/push", - }); + const fork = yield* makeTmpDir("git-fork-"); + yield* git(fork, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "fork", fork]); + yield* git(cwd, ["remote", "add", "feature", fork]); + yield* git(cwd, ["push", "-u", "fork", "feature/push"]); + yield* git(cwd, ["push", "fork", "--delete", "feature/push"]); + yield* writeTextFile(cwd, "fork.txt", "fork\n"); + yield* git(cwd, ["add", "-A"]); + yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add fork change", ""); + assert.deepInclude( + yield* (yield* GitVcsDriver.GitVcsDriver).resolvePushTarget(cwd, { + branch: "feature/push", + hasUpstream: false, + }), + { remoteName: "fork", branchName: "feature/push" }, + ); + const forkRepublished = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch( + cwd, + null, + ); + assert.deepInclude(forkRepublished, { upstreamBranch: "fork/feature/push" }); + assert.equal( + yield* git(fork, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + + yield* git(cwd, ["config", "branch.feature/push.remote", "."]); + yield* git(cwd, ["config", "branch.feature/push.merge", "refs/heads/push"]); + yield* writeTextFile(cwd, "local.txt", "local\n"); + yield* git(cwd, ["add", "-A"]); + yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add local change", ""); + const localUpstreamGone = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch( + cwd, + null, + ); + assert.deepInclude(localUpstreamGone, { upstreamBranch: "origin/feature/push" }); + + yield* git(cwd, ["push", "fork", "HEAD:refs/heads/release"]); + yield* git(cwd, ["branch", "-u", "fork/release"]); + yield* git(cwd, ["push", "fork", "--delete", "release"]); + yield* writeTextFile(cwd, "release.txt", "release\n"); + yield* git(cwd, ["add", "-A"]); + yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add release change", ""); + yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null); + assert.equal( + yield* (yield* GitVcsDriver.GitVcsDriver).readConfigValue( + cwd, + "branch.feature/push.t3-merge-base", + ), + "release", + ); }), ); @@ -6536,6 +9089,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(originRemote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), publishedHead, ); + + const pushOnlyRemote = yield* makeTmpDir("git-push-only-remote-"); + yield* git(pushOnlyRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "set-url", "--push", "origin", pushOnlyRemote]); + const pushedToPushUrl = yield* driver.pushCurrentBranch(cwd, null); + assert.deepInclude(pushedToPushUrl, { status: "pushed", branch }); + assert.equal( + yield* git(pushOnlyRemote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + head, + ); }), ); @@ -6578,62 +9141,194 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("publishes a branch tracking its base under its own name, not the base", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-remote-"); - const upstream = yield* makeTmpDir("git-upstream-"); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* git(cwd, ["branch", "-M", "main"]); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", "main"]); - yield* git(cwd, ["checkout", "-b", "dev"]); - yield* git(cwd, ["push", "-u", "origin", "dev"]); - const devSha = yield* git(cwd, ["rev-parse", "HEAD"]); - yield* git(upstream, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "upstream", upstream]); - yield* writeTextFile(cwd, "upstream.txt", "upstream work\n"); - yield* git(cwd, ["add", "-A"]); - yield* driver.commit(cwd, "Add upstream update", ""); - yield* git(cwd, ["push", "upstream", "dev"]); - const upstreamDevSha = yield* git(cwd, ["rev-parse", "HEAD"]); - yield* git(cwd, ["checkout", "-b", "feature/x", "upstream/dev"]); - yield* writeTextFile(cwd, "feature.txt", "feature\n"); - yield* git(cwd, ["add", "-A"]); - yield* driver.commit(cwd, "Add feature", ""); + it.effect.each([ + { baseBranch: "dev", local: false, branch: "feature/x", deleted: false }, + { baseBranch: "dev", local: true, branch: "feature/x", deleted: false }, + { baseBranch: "feature/base", local: true, branch: "feature/x", deleted: false }, + { baseBranch: "upstream", local: true, branch: "feature/x", deleted: false }, + { baseBranch: "upstream/feature/x", local: true, branch: "feature/x", deleted: false }, + { baseBranch: "dev", local: false, branch: "origin/dev", deleted: true }, + ])( + "publishes $branch tracking $baseBranch (local=$local, deleted=$deleted) without updating the base", + ({ baseBranch, local, branch, deleted }) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + const upstream = yield* makeTmpDir("git-upstream-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", "main"]); + yield* git(cwd, ["checkout", "--no-track", "-b", baseBranch]); + yield* git(cwd, ["push", "-u", "origin", baseBranch]); + const devSha = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(upstream, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", upstream]); + yield* writeTextFile(cwd, "upstream.txt", "upstream work\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add upstream update", ""); + yield* git(cwd, ["push", "upstream", baseBranch]); + const upstreamDevSha = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, [ + "checkout", + "--track", + "-b", + branch, + local ? `refs/heads/${baseBranch}` : `refs/remotes/upstream/${baseBranch}`, + ]); + assert.equal( + yield* driver.readConfigValue(cwd, `branch.${branch}.remote`), + local ? "." : "upstream", + ); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add feature", ""); + if (deleted) { + yield* git(cwd, ["push", "upstream", "--delete", baseBranch]); + } + const publishBranch = branch === "origin/dev" ? "dev" : branch; + assert.deepInclude( + yield* driver.resolvePushTarget(cwd, { branch, hasUpstream: !deleted }), + { remoteName: "origin", branchName: publishBranch }, + ); - const pushed = yield* driver.pushCurrentBranch(cwd, null); + const pushed = yield* driver.pushCurrentBranch(cwd, null); - assert.deepInclude(pushed, { - status: "pushed", - branch: "feature/x", - upstreamBranch: "origin/feature/x", - setUpstream: true, - }); - assert.equal( - yield* git(remote, ["--git-dir=.", "log", "-1", "--pretty=%s", "feature/x"]), - "Add feature", - ); - assert.equal(yield* git(remote, ["--git-dir=.", "rev-parse", "dev"]), devSha); - assert.equal(yield* git(upstream, ["--git-dir=.", "rev-parse", "dev"]), upstreamDevSha); - assert.equal( - yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), - "origin/feature/x", - ); - assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.t3-merge-base"), "dev"); + assert.deepInclude(pushed, { + status: "pushed", + branch, + upstreamBranch: `origin/${publishBranch}`, + setUpstream: true, + }); + assert.equal( + yield* git(remote, ["--git-dir=.", "log", "-1", "--pretty=%s", publishBranch]), + "Add feature", + ); + if (publishBranch !== baseBranch) { + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", `refs/heads/${baseBranch}`]), + devSha, + ); + } + assert.equal( + yield* git(upstream, [ + "--git-dir=.", + "for-each-ref", + "--format=%(objectname)", + `refs/heads/${baseBranch}`, + ]), + deleted ? "" : upstreamDevSha, + ); + assert.equal( + yield* git(cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"]), + `refs/remotes/origin/${publishBranch}`, + ); + assert.equal( + yield* driver.readConfigValue(cwd, `branch.${branch}.t3-merge-base`), + baseBranch, + ); + assert.equal( + yield* driver.readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`), + local ? `refs/heads/${baseBranch}` : `refs/remotes/upstream/${baseBranch}`, + ); + assert.equal(yield* git(cwd, ["rev-parse", `refs/heads/${baseBranch}`]), upstreamDevSha); - const preview = yield* driver.getReviewDiffPreview({ cwd }); - const changes = preview.sources.find((source) => source.kind === "branch-range")!; - assert.deepStrictEqual(changes.files, [ - { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, - ]); - assert.equal(changes.baseRef, "upstream/dev"); - }), + if (deleted) return; + + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.deepStrictEqual(changes.files, [ + { + path: "feature.txt", + previousPath: null, + changeType: "new", + additions: 1, + deletions: 0, + }, + ]); + assert.equal( + changes.baseRef, + local ? `refs/heads/${baseBranch}` : `upstream/${baseBranch}`, + ); + }), ); - it.effect("keeps a recorded merge base when publishing a tracked branch", () => + it.effect.each([ + { upstreamRef: "refs/remotes/origin/main", baseKey: "gh-merge-base" }, + { upstreamRef: "refs/heads/main", baseKey: "gh-merge-base" }, + { upstreamRef: "refs/heads/main", baseKey: "t3-merge-base" }, + ])( + "keeps a recorded $baseKey when publishing a branch tracking $upstreamRef", + ({ upstreamRef, baseKey }) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", "main"]); + yield* git(cwd, ["checkout", "--track", "-b", "feature/y", upstreamRef]); + yield* git(cwd, ["config", `branch.feature/y.${baseKey}`, "release/v2"]); + yield* git(cwd, [ + "config", + "branch.feature/y.t3-merge-base-ref", + "refs/heads/release/v2", + ]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add feature", ""); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { + status: "pushed", + branch: "feature/y", + upstreamBranch: "origin/feature/y", + setUpstream: true, + }); + assert.equal( + yield* driver.readConfigValue(cwd, `branch.feature/y.${baseKey}`), + "release/v2", + ); + assert.equal(yield* driver.readBranchBase(cwd, "feature/y"), "release/v2"); + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/y.t3-merge-base-ref"), + "refs/heads/release/v2", + ); + }), + ); + + it.effect.each(["main", "feature/base"])( + "rejects publishing a branch tracking local %s without a git remote", + (parent) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", parent]); + yield* git(cwd, ["checkout", "--track", "-b", "child", `refs/heads/${parent}`]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add feature", ""); + const parentSha = yield* git(cwd, ["rev-parse", `refs/heads/${parent}`]); + + const error = yield* driver.pushCurrentBranch(cwd, null).pipe(Effect.flip); + + assert.equal(error._tag, "GitCommandError"); + assert.equal(error.operation, "GitVcsDriver.pushCurrentBranch"); + assert.equal( + error.detail, + "Cannot push because no git remote is configured for this repository.", + ); + assert.equal(yield* git(cwd, ["rev-parse", `refs/heads/${parent}`]), parentSha); + }), + ); + + it.effect("publishes a local-tracking branch named like a remote ref under its full name", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-remote-"); @@ -6643,8 +9338,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(remote, ["init", "--bare"]); yield* git(cwd, ["remote", "add", "origin", remote]); yield* git(cwd, ["push", "-u", "origin", "main"]); - yield* git(cwd, ["checkout", "-b", "feature/y", "origin/main"]); - yield* git(cwd, ["config", "branch.feature/y.gh-merge-base", "release/v2"]); + const mainSha = yield* git(cwd, ["rev-parse", "refs/heads/main"]); + yield* git(cwd, ["checkout", "--track", "-b", "origin/main", "refs/heads/main"]); yield* writeTextFile(cwd, "feature.txt", "feature\n"); yield* git(cwd, ["add", "-A"]); yield* driver.commit(cwd, "Add feature", ""); @@ -6653,13 +9348,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.deepInclude(pushed, { status: "pushed", - branch: "feature/y", - upstreamBranch: "origin/feature/y", - setUpstream: true, + branch: "origin/main", + upstreamBranch: "origin/origin/main", }); + assert.equal(yield* git(remote, ["--git-dir=.", "rev-parse", "refs/heads/main"]), mainSha); assert.equal( - yield* driver.readConfigValue(cwd, "branch.feature/y.gh-merge-base"), - "release/v2", + yield* git(remote, ["--git-dir=.", "log", "-1", "--pretty=%s", "refs/heads/origin/main"]), + "Add feature", ); }), ); @@ -6696,6 +9391,32 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(remote, ["--git-dir=.", "log", "-1", "--pretty=%s", "effect-atom"]), "Add alias update", ); + + yield* git(cwd, ["push", "my-org/upstream", "--delete", "effect-atom"]); + assert.deepInclude( + yield* driver.resolvePushTarget(cwd, { + branch: "upstream/effect-atom", + hasUpstream: false, + }), + { remoteName: "my-org/upstream", branchName: "effect-atom" }, + ); + assert.deepInclude(yield* driver.pushCurrentBranch(cwd, null), { + upstreamBranch: "my-org/upstream/effect-atom", + setUpstream: true, + }); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", "refs/heads/effect-atom"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + assert.equal( + yield* git(remote, [ + "--git-dir=.", + "for-each-ref", + "--format=%(refname)", + "refs/heads/upstream/", + ]), + "", + ); }), ); @@ -6734,6 +9455,196 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.notEqual(originMain.exitCode, 0); }), ); + + it.effect.each(["branch.topic.pushRemote", "remote.pushDefault"] as const)( + "pushes a branch tracking its upstream head to the %s remote", + (configKey) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const upstreamRemote = yield* makeTmpDir("git-upstream-remote-"); + const forkRemote = yield* makeTmpDir("git-fork-remote-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(upstreamRemote, ["init", "--bare"]); + yield* git(forkRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", upstreamRemote]); + yield* git(cwd, ["remote", "add", "fork", forkRemote]); + yield* git(cwd, ["checkout", "-b", "topic"]); + yield* git(cwd, ["push", "upstream", "topic"]); + yield* git(cwd, ["push", "fork", "topic"]); + yield* git(cwd, ["branch", "--set-upstream-to=upstream/topic"]); + yield* git(cwd, ["config", configKey, "fork"]); + const upstreamTopicSha = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* writeTextFile(cwd, "fork.txt", "fork\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add fork update", ""); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { + status: "pushed", + branch: "topic", + upstreamBranch: "fork/topic", + pushRemote: "fork", + setUpstream: false, + }); + assert.equal( + yield* git(forkRemote, ["--git-dir=.", "log", "-1", "--pretty=%s", "topic"]), + "Add fork update", + ); + assert.equal( + yield* git(upstreamRemote, ["--git-dir=.", "rev-parse", "topic"]), + upstreamTopicSha, + ); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + "upstream/topic", + ); + }), + ); + + it.effect.each(["deleted", "rewound"] as const)( + "pushes an up-to-date tracked branch to the push remote when its branch there is %s", + (forkState) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const upstreamRemote = yield* makeTmpDir("git-upstream-remote-"); + const forkRemote = yield* makeTmpDir("git-fork-remote-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(upstreamRemote, ["init", "--bare"]); + yield* git(forkRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", upstreamRemote]); + yield* git(cwd, ["remote", "add", "fork", forkRemote]); + yield* git(cwd, ["checkout", "-b", "topic"]); + yield* writeTextFile(cwd, "upstream.txt", "upstream\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add upstream update", ""); + yield* git(cwd, ["push", "-u", "upstream", "topic"]); + yield* git(cwd, ["config", "remote.pushDefault", "fork"]); + // Another checkout changes the fork after this one last fetched it, + // leaving a local fork/topic that still contains HEAD. + yield* git(cwd, ["push", "fork", "topic"]); + yield* git( + forkRemote, + forkState === "deleted" + ? ["--git-dir=.", "update-ref", "-d", "refs/heads/topic"] + : ["--git-dir=.", "update-ref", "refs/heads/topic", "topic~1"], + ); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { + status: "pushed", + upstreamBranch: "fork/topic", + pushRemote: "fork", + }); + assert.equal( + yield* git(forkRemote, ["--git-dir=.", "log", "-1", "--pretty=%s", "topic"]), + "Add upstream update", + ); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + "upstream/topic", + ); + }), + ); + + it.effect.each([ + { pushUrls: [], status: "skipped_up_to_date" }, + { pushUrls: ["mirror"], status: "pushed" }, + { pushUrls: ["fork", "mirror"], status: "pushed" }, + ] as const)( + "skips an up-to-date tracked branch only when every push URL has it (pushurl $pushUrls)", + ({ pushUrls, status }) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const upstreamRemote = yield* makeTmpDir("git-upstream-remote-"); + const remotes = { + fork: yield* makeTmpDir("git-fork-remote-"), + mirror: yield* makeTmpDir("git-mirror-remote-"), + }; + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(upstreamRemote, ["init", "--bare"]); + yield* git(remotes.fork, ["init", "--bare"]); + yield* git(remotes.mirror, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", upstreamRemote]); + yield* git(cwd, ["remote", "add", "fork", remotes.fork]); + yield* git(cwd, ["checkout", "-b", "topic"]); + yield* git(cwd, ["push", "-u", "upstream", "topic"]); + yield* git(cwd, ["push", "fork", "topic"]); + yield* git(cwd, ["config", "remote.pushDefault", "fork"]); + for (const name of pushUrls) { + yield* git(cwd, ["remote", "set-url", "--add", "--push", "fork", remotes[name]]); + } + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { status, upstreamBranch: "fork/topic", pushRemote: "fork" }); + const head = yield* git(cwd, ["rev-parse", "HEAD"]); + for (const name of pushUrls) { + assert.equal( + yield* git(remotes[name], ["--git-dir=.", "rev-parse", "refs/heads/topic"]), + head, + ); + } + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + "upstream/topic", + ); + }), + ); + + it.effect("pushes an up-to-date branch whose tracked remote has a separate push URL", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fetchRemote = yield* makeTmpDir("git-fetch-remote-"); + const pushRemote = yield* makeTmpDir("git-push-remote-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(fetchRemote, ["init", "--bare"]); + yield* git(pushRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", fetchRemote]); + yield* git(cwd, ["checkout", "-b", "topic"]); + yield* git(cwd, ["push", "-u", "origin", "topic"]); + yield* git(cwd, ["remote", "set-url", "--push", "origin", pushRemote]); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { status: "pushed", upstreamBranch: "origin/topic" }); + assert.equal( + yield* git(pushRemote, ["--git-dir=.", "rev-parse", "refs/heads/topic"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + }), + ); + + it.effect("skips an up-to-date branch whose differently named upstream is its base", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const upstreamRemote = yield* makeTmpDir("git-upstream-remote-"); + const forkRemote = yield* makeTmpDir("git-fork-remote-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(upstreamRemote, ["init", "--bare"]); + yield* git(forkRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", upstreamRemote]); + yield* git(cwd, ["remote", "add", "fork", forkRemote]); + yield* git(cwd, ["push", "upstream", "HEAD:refs/heads/release"]); + yield* git(cwd, ["fetch", "upstream"]); + yield* git(cwd, ["checkout", "-b", "topic", "--track", "upstream/release"]); + yield* git(cwd, ["config", "remote.pushDefault", "fork"]); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { + status: "skipped_up_to_date", + upstreamBranch: "upstream/release", + }); + assert.equal(yield* git(forkRemote, ["--git-dir=.", "branch", "--list", "topic"]), ""); + }), + ); }); }); @@ -6832,3 +9743,141 @@ describe("Windows long path configuration", () => { } }); }); + +it.layer(layerTest)("branch change totals after a failed read", (it) => { + it.effect("do not list untracked files again on every status read", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* makeTmpDir("git-untracked-totals-"); + yield* initRepoWithCommit(cwd); + const many = path.join(cwd, "many"); + yield* fs.makeDirectory(many); + yield* Effect.forEach( + Array.from({ length: 5_001 }, (_, index) => index), + (index) => fs.writeFileString(path.join(many, `file-${index}`), ""), + { concurrency: 64, discard: true }, + ); + + let listings = 0; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => + Effect.suspend(() => { + if ( + ChildProcess.isStandardCommand(command) && + command.args.includes("ls-files") && + command.args.includes("--others") + ) + listings++; + return delegate.spawn(command); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const read = driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + + assert.strictEqual((yield* read).branchChanges, undefined, "too many files to count"); + assert.strictEqual(listings, 1); + yield* read; + yield* read; + assert.strictEqual(listings, 1, "the failed listing is not repeated within the backoff"); + + yield* TestClock.adjust("1 minute"); + yield* read; + assert.strictEqual(listings, 2, "it is retried once the backoff passes"); + yield* TestClock.adjust("1 minute"); + yield* read; + assert.strictEqual(listings, 2, "and the next backoff is longer"); + + // A change at the untracked-roots level scans again at once and counts again. + yield* fs.remove(many, { recursive: true }); + yield* writeTextFile(cwd, "notes.txt", "one\ntwo\n"); + const status = yield* read; + assert.strictEqual(listings, 3); + assert.deepStrictEqual(status.branchChanges, { baseRef: null, insertions: 2, deletions: 0 }); + }), + ); + + it.effect("back off a timed-out branch diff until it expires or HEAD moves", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir("git-branch-totals-timeout-"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(cwd, ["checkout", "-b", "feature"]); + yield* writeTextFile(cwd, "feature.txt", "one\n"); + yield* git(cwd, ["add", "feature.txt"]); + yield* git(cwd, ["commit", "-m", "feature"]); + + let diffs = 0; + let hang = true; + const diffStarted = yield* Queue.unbounded(); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => + Effect.suspend(() => { + // Status diffs the working tree against HEAD; the branch totals diff the merge base. + if ( + !ChildProcess.isStandardCommand(command) || + !command.args.includes("diff-index") || + command.args.includes("HEAD") + ) { + return delegate.spawn(command); + } + diffs++; + if (!hang) return delegate.spawn(command); + return Queue.offer(diffStarted, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + ...makeSuccessfulHandle(""), + isRunning: Effect.succeed(true), + exitCode: Effect.never, + }), + ), + ); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const read = driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + + const first = yield* read.pipe(Effect.forkChild); + yield* Queue.take(diffStarted); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(first)).branchChanges, undefined); + assert.strictEqual(diffs, 1); + assert.strictEqual((yield* read).branchChanges, undefined); + assert.strictEqual(diffs, 1, "the same HEAD and base are not diffed within the backoff"); + + hang = false; + yield* TestClock.adjust("1 minute"); + assert.deepStrictEqual((yield* read).branchChanges, { + baseRef: "main", + insertions: 1, + deletions: 0, + }); + assert.strictEqual(diffs, 2, "it is retried once the backoff passes"); + + hang = true; + const again = yield* read.pipe(Effect.forkChild); + yield* Queue.take(diffStarted); + yield* TestClock.adjust("30 seconds"); + yield* Fiber.join(again); + yield* read; + assert.strictEqual(diffs, 3); + + hang = false; + yield* writeTextFile(cwd, "feature.txt", "one\ntwo\n"); + yield* git(cwd, ["commit", "-am", "more"]); + const status = yield* read; + assert.strictEqual(diffs, 4, "a new HEAD diffs again within the backoff"); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "main", + insertions: 2, + deletions: 0, + }); + }), + ); +}); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 4dabf3b493..89bb1fa039 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1,7 +1,10 @@ import * as Cache from "effect/Cache"; +import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Data from "effect/Data"; +import * as Deferred from "effect/Deferred"; import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -26,6 +29,7 @@ import { type GitCommandFailureReason, T3_PROJECT_FILE_NAME, type ReviewBranchCommitsInput, + type ReviewDiffChangeType, type ReviewDiffFileContentsInput, type ReviewDiffPreviewInput, type ReviewDiffFileStat, @@ -42,7 +46,12 @@ import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; -import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts"; +import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; +import { + explicitBareRepositoryEnv, + gitConfigEnv, + unsetInheritedRepositoryEnv, +} from "./VcsProcess.ts"; import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; @@ -63,10 +72,19 @@ const branchBaseConfigKey = (branch: string) => `branch.${branch}.t3-merge-base` * CLI's key, which branches cut before then still carry instead. */ const legacyBranchBaseConfigKey = (branch: string) => `branch.${branch}.gh-merge-base`; +// Differently named upstreams are bases, not publish targets; pushing HEAD there would write features to shared branches. +const isAliasOfUpstreamHead = (branch: string, upstreamBranch: string, upstreamRef: string) => + branch === upstreamBranch || + (branch.endsWith(`/${upstreamBranch}`) && upstreamRef.endsWith(`/${branch}`)); const gitProcesses = Semaphore.makeUnsafe(8); const backgroundGitProcesses = Semaphore.makeUnsafe(2); +// The fetch before `git worktree add` downloads everything the remote gained since +// the last fetch; on busy repositories that alone outlasts the 30s default. +const FETCH_REMOTE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5)); +const WORKTREE_INDEX_REFRESH_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5)); const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5)); const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; +const REF_SNAPSHOT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000; const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000; @@ -76,7 +94,15 @@ const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000; const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap. const REVIEW_UNTRACKED_MAX_FILES = 5_000; +// git diff reads every untracked byte (~5 ms/MB), so larger untracked input stays out of the review index. +const REVIEW_UNTRACKED_MAX_BYTES = 256 * 1024 * 1024; +// The listing walks the whole untracked tree before the cap applies, so a folder whose listing +// failed (too many files, output limit, timeout) is not listed again on every status poll. +const UNTRACKED_TOTALS_RETRY_MIN_MS = 60_000; +const UNTRACKED_TOTALS_RETRY_MAX_MS = 30 * 60_000; const REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024; +// Git's ident clean step (convert.c ident_to_git): `$Id:` up to the next `$` on the same line. +const GIT_IDENT_KEYWORD = /\$Id:[^$\n]*\$/g; const REVIEW_BRANCH_COMMIT_LIMIT = 100; const REVIEW_BRANCH_SUBJECT_LIMIT = 300; const REVIEW_BRANCH_COMMIT_MAX_OUTPUT_BYTES = 128 * 1024; @@ -180,6 +206,7 @@ interface GitRepositoryPaths { } interface GitRefsSnapshot { + readonly defaultBranch: string | null; readonly localBranches: ReadonlyArray; readonly remoteBranches: ReadonlyArray; readonly hasPrimaryRemote: boolean; @@ -188,12 +215,12 @@ interface GitRefsSnapshot { interface ExecuteGitOptions { stdin?: string | undefined; timeoutMs?: number | null | undefined; - forceKillAfterMs?: number | undefined; allowNonZeroExit?: boolean | undefined; fallbackErrorDetail?: string | undefined; env?: NodeJS.ProcessEnv | undefined; maxOutputBytes?: number | undefined; appendTruncationMarker?: boolean | undefined; + keepLineCallbacksAfterTruncation?: boolean | undefined; progress?: GitVcsDriver.ExecuteGitProgress | undefined; writesSharedConfig?: boolean | undefined; } @@ -207,18 +234,41 @@ function parseBranchAb(value: string): { ahead: number; behind: number } { }; } +function rawChangeType(status: string): ReviewDiffChangeType { + switch (status[0]) { + case "A": + return "new"; + case "D": + return "deleted"; + case "R": + return status === "R100" ? "rename-pure" : "rename-changed"; + default: + return "change"; + } +} + +// Parses `--numstat -z`, optionally preceded by `--raw` records that carry each file's change type. function parseReviewNumstat(stdout: string): ReviewDiffFileStat[] { const fields = stdout.split("\0"); + const changeTypes = new Map(); const files: ReviewDiffFileStat[] = []; for (let index = 0; index < fields.length; index++) { const field = fields[index]!; + if (field.startsWith(":")) { + const status = field.slice(field.lastIndexOf(" ") + 1); + if (/^[RC]/.test(status)) index++; + changeTypes.set(fields[++index]!, rawChangeType(status)); + continue; + } const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(field); if (!match) continue; const previousPath = match[3] === "" ? fields[++index]! : null; const path = previousPath !== null ? fields[++index]! : match[3]!; + const changeType = changeTypes.get(path); files.push({ path, previousPath, + ...(changeType === undefined ? {} : { changeType }), additions: match[1] === "-" ? 0 : Number(match[1]), deletions: match[2] === "-" ? 0 : Number(match[2]), }); @@ -319,6 +369,14 @@ function splitNullSeparatedPaths(input: string, truncated: boolean): string[] { return parts.filter((value) => value.length > 0); } +// Parses "git version 2.24.3 (Apple Git-128)" or "git version 2.45.1.windows.1". +const gitSupportsPathspecFromFile = (versionOutput: string): boolean => { + const match = /^git version (\d+)\.(\d+)/.exec(versionOutput); + if (match === null) return false; + const major = Number(match[1]); + return major > 2 || (major === 2 && Number(match[2]) >= 25); +}; + export function splitNullSeparatedGitStdoutPaths( result: Pick, ): string[] { @@ -349,11 +407,10 @@ function sanitizeRemoteName(value: string): string { function parseRemoteFetchUrls(stdout: string): Map { const remotes = new Map(); - for (const line of stdout.split("\n")) { - const trimmed = line.trim(); - if (trimmed.length === 0) continue; + for (const line of stdout.split(/\r?\n/)) { + // Git uses a tab before the URL and one space before the direction; both can occur in URLs. // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. - const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed); + const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line); if (!match) continue; const [, remoteName = "", remoteUrl = "", direction = ""] = match; if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) { @@ -446,6 +503,8 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray 0 ? refName : null; + return refName.length > 0 && refName !== "HEAD" ? refName : null; } function isMissingGitCwdError(error: GitCommandError): boolean { @@ -562,8 +621,20 @@ function isMissingGitCwdError(error: GitCommandError): boolean { ); } -function isNonRepositoryGitStderr(stderr: string): boolean { - return stderr.toLowerCase().includes("not a git repository"); +// Git 2.56+ reports a `.git` gitfile pointing nowhere as "gitfile does not point to a valid +// repository"; older releases said "not a git repository". Both mean the cwd is not a repository. +const NON_REPOSITORY_STDERR_PHRASES = [ + "not a git repository", + "gitfile does not point to a valid repository", +] as const; + +export function isNonRepositoryGitStderr(stderr: string): boolean { + const normalized = stderr.toLowerCase(); + return NON_REPOSITORY_STDERR_PHRASES.some((phrase) => normalized.includes(phrase)); +} +const UNTRACKED_FILES_SHOWN_CONFIG_VALUES = new Set(["normal", "all", "true", "yes", "on", "1"]); +function untrackedFilesHiddenByConfig(value: string | null): boolean { + return value !== null && !UNTRACKED_FILES_SHOWN_CONFIG_VALUES.has(value.toLowerCase()); } function isUnbornHeadStderr(stderr: string): boolean { const normalized = stderr.toLowerCase(); @@ -949,9 +1020,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const { worktreesDir, worktreeCheckoutCacheDir } = yield* ServerConfig.ServerConfig; const isServerInternalPath = yield* makeIsServerInternalPath; const digest = yield* Digest.Digest; + const random = yield* SecureRandom.SecureRandom; const hostPlatform = yield* HostProcess.Platform; const serviceScope = yield* Effect.scope; - const statusFetches = new Map>(); + const automaticFetchInterval = yield* VcsAutomaticFetchInterval; + type StatusFetchState = { + phase: "queued" | "running" | "claimed"; + claimed: Deferred.Deferred; + finished: Deferred.Deferred; + }; + const statusFetches = new Map< + string, + { + state: StatusFetchState; + fiber: Fiber.Fiber; + } + >(); const statusFetchProcesses = yield* Semaphore.make(4); const executeRaw: GitVcsDriver.GitVcsDriver["Service"]["execute"] = Effect.fnUntraced( @@ -977,8 +1061,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), ), ); + const hostEnv = yield* HostProcess.Environment; const baseEnv = { - ...(yield* HostProcess.Environment), + ...hostEnv, + ...unsetInheritedRepositoryEnv(hostEnv, hostPlatform), // Concurrent status polls must not take index.lock to save refreshed indexes. GIT_OPTIONAL_LOCKS: "0", ...input.env, @@ -987,6 +1073,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const env = { ...baseEnv, ...explicitBareRepositoryEnv(baseEnv, hostPlatform) }; const spawnEnv = { ...env, ...windowsLongPathConfigEnv(hostPlatform, env) }; const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv }); + const spawnError = (cause: unknown) => + new GitCommandError({ + ...gitCommandContext(commandInput), + detail: "Failed to spawn Git process.", + cause, + }); // cmd wrappers truncate multiline commits; leave git.cmd handling to Node lookup. const executable = resolved.shell ? "git" : resolved.command; const child = yield* commandSpawner @@ -994,21 +1086,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ChildProcess.make(executable, commandInput.args, { cwd: commandInput.cwd, env: spawnEnv, - forceKillAfter: input.forceKillAfterMs, + // SIGTERM first lets git remove its lock files; SIGKILL ends one that ignores it. + forceKillAfter: "1 second", ...(runsGitWithoutConsole(hostPlatform, executable, commandInput.args) ? { detached: true, windowsHide: true } : {}), }), ) .pipe( - Effect.mapError( - (cause) => - new GitCommandError({ - ...gitCommandContext(commandInput), - detail: "Failed to spawn Git process.", - cause, - }), - ), + Effect.mapError(spawnError), + // Synchronous spawn throws (such as E2BIG) arrive as defects. + Effect.catchDefect((cause) => Effect.fail(spawnError(cause))), ); const [stdout, stderr, exitCode] = yield* Effect.all( @@ -1163,13 +1251,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ...(options.env !== undefined ? { env: options.env } : {}), allowNonZeroExit: true, ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), - ...(options.forceKillAfterMs !== undefined - ? { forceKillAfterMs: options.forceKillAfterMs } - : {}), ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), ...(options.appendTruncationMarker !== undefined ? { appendTruncationMarker: options.appendTruncationMarker } : {}), + ...(options.keepLineCallbacksAfterTruncation + ? { keepLineCallbacksAfterTruncation: true } + : {}), ...(options.progress ? { progress: options.progress } : {}), ...(options.writesSharedConfig ? { writesSharedConfig: true } : {}), }).pipe( @@ -1363,6 +1451,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "--quiet", "--no-tags", "--no-auto-gc", + // FETCH_HEAD is written without a lock; overlapping a user's `git pull` makes that pull fail. + "--no-write-fetch-head", "--", remoteName, ]; @@ -1372,15 +1462,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fiber = yield* Effect.uninterruptible( Effect.gen(function* () { const pending = statusFetches.get(key); - if (pending) return pending; + if (pending) return pending.fiber; + const claimed = yield* Deferred.make(); + const finished = yield* Deferred.make(); + const state: StatusFetchState = { phase: "queued", claimed, finished }; // Frequent poll deadlines and disconnected clients must not interrupt a // healthy writer. A separate safety limit prevents a hung transport from // occupying its worker slot indefinitely. - const started = yield* executeGit("GitVcsDriver.fetchRemoteForStatus", fetchCwd, args, { + const fetch = executeGit("GitVcsDriver.fetchRemoteForStatus", fetchCwd, args, { env: STATUS_UPSTREAM_REFRESH_ENV, fallbackErrorDetail: "Background Git fetch exited with a non-zero status.", timeoutMs: Duration.toMillis(STATUS_UPSTREAM_FETCH_TIMEOUT), - forceKillAfterMs: 1_000, }).pipe( Effect.asVoid, Effect.tap(() => @@ -1390,18 +1482,39 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), Effect.tapError(() => recordStatusRemoteRefreshFailure(key)), Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)), - statusFetchProcesses.withPermits(1), + ); + const started = yield* Effect.raceFirst( + Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + if (state.phase !== "queued") return false; + state.phase = "running"; + yield* restore(fetch); + return true; + }), + ).pipe(statusFetchProcesses.withPermits(1)), + Deferred.await(claimed).pipe(Effect.as(false)), + ).pipe( + Effect.flatMap((completed) => + completed + ? Effect.void + : Deferred.await(finished).pipe( + Effect.flatMap((succeeded) => + succeeded ? Effect.void : fetch.pipe(statusFetchProcesses.withPermits(1)), + ), + ), + ), Effect.onExit(() => Effect.sync(() => { - statusFetches.delete(key); + if (statusFetches.get(key)?.state === state) statusFetches.delete(key); }), ), Effect.forkIn(serviceScope, { startImmediately: false, uninterruptible: false }), ); - statusFetches.set(key, started); + statusFetches.set(key, { state, fiber: started }); return started; }), ); + yield* Effect.annotateCurrentSpan("statusFetch.joining", true); const result = yield* Fiber.join(fiber).pipe( Effect.timeoutOption(STATUS_UPSTREAM_REFRESH_TIMEOUT), ); @@ -1470,23 +1583,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : null; }); + const readCurrentBranch = (operation: string, cwd: string) => + executeGit(operation, cwd, ["symbolic-ref", "--quiet", "HEAD"], { + timeoutMs: 5_000, + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => (result.exitCode === 0 ? branchNameFromHeadRef(result.stdout) : null)), + ); + const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* ( cwd: string, ) { const gitCommonDir = yield* readGitCommonDir(cwd); if (gitCommonDir === null) return null; - const [worktreeRoot, currentBranchResult] = yield* Effect.all( + const [worktreeRoot, currentBranch] = yield* Effect.all( [ readWorktreeRoot(cwd), - executeGit( - "GitVcsDriver.resolveRepositoryPaths.currentBranch", - cwd, - ["symbolic-ref", "--quiet", "HEAD"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ), + readCurrentBranch("GitVcsDriver.resolveRepositoryPaths.currentBranch", cwd), ], { concurrency: 2 }, ); @@ -1498,8 +1611,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((physicalCwd) => path.relative(worktreeRoot, physicalCwd) === ""), Effect.orElseSucceed(() => undefined), ); - const currentBranch = - currentBranchResult.exitCode === 0 ? branchNameFromHeadRef(currentBranchResult.stdout) : null; return { gitCommonDir, @@ -1555,17 +1666,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const path = yield* Path.Path; const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; - return yield* executeGit( - "GitVcsDriver.statusDetails.defaultBranch", - fetchCwd, - ["--git-dir", gitCommonDir, "symbolic-ref", "refs/remotes/origin/HEAD"], - { allowNonZeroExit: true }, - ).pipe( - Effect.map((result) => { - if (result.exitCode !== 0) return null; - return parseDefaultBranchFromRemoteHeadRef(result.stdout, "origin"); - }), - ); + return yield* resolvePrimaryDefaultBranchName(fetchCwd, ["--git-dir", gitCommonDir]); }), { capacity: 2_048, @@ -1626,6 +1727,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); const statusRemoteRefreshFailures = new Map(); + const untrackedTotalsFailures = new Map< + string, + { + readonly roots: string; + readonly count: number; + readonly retryAt: number; + readonly detail: string; + } + >(); + // Keyed by cwd: the HEAD and merge base whose totals diff failed, retried after a backoff. + const branchTotalsDiffFailures = new Map< + string, + { + readonly key: string; + readonly count: number; + readonly retryAt: number; + readonly detail: string; + } + >(); const statusRemoteRefreshFailureKey = (cacheKey: StatusRemoteRefreshCacheKey) => `${cacheKey.gitCommonDir}\0${cacheKey.remoteName}`; const recordStatusRemoteRefreshFailure = Effect.fn( @@ -1664,9 +1784,42 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), }); + const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn( + "GitVcsDriver.readRefSnapshot", + )( + function* (cwd) { + const result = yield* executeGit( + "GitVcsDriver.readRefSnapshot", + cwd, + ["show-ref", "--head"], + { + allowNonZeroExit: true, + maxOutputBytes: REF_SNAPSHOT_MAX_OUTPUT_BYTES, + }, + ); + if (result.exitCode !== 0) return null; + const symbolicHead = yield* executeGit( + "GitVcsDriver.readRefSnapshot", + cwd, + ["symbolic-ref", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ); + // Exit 1 means detached HEAD; other failures require a full status read. + if (symbolicHead.exitCode !== 0 && symbolicHead.exitCode !== 1) return null; + // Deepening a shallow clone changes ancestry without moving refs. + const shallowPath = path.join(yield* resolveGitCommonDir(cwd), "shallow"); + const shallow = (yield* fileSystem.exists(shallowPath)) + ? yield* fileSystem.readFileString(shallowPath) + : ""; + return `${result.stdout}\0${symbolicHead.stdout}\0${shallow}`; + }, + Effect.orElseSucceed(() => null), + ); + const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( cwd: string, ) { + if (Duration.isZero(yield* automaticFetchInterval)) return; const headRef = yield* runGitStdout( "GitVcsDriver.refreshStatusUpstreamIfStale.headRef", cwd, @@ -1692,11 +1845,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolveDefaultBranchName = ( cwd: string, remoteName: string, + gitDirArgs: ReadonlyArray = [], ): Effect.Effect => executeGit( "GitVcsDriver.resolveDefaultBranchName", cwd, - ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], + // Unlike `symbolic-ref`, this fails when the remote deleted the branch HEAD points at. + [ + ...gitDirArgs, + "rev-parse", + "--verify", + "--quiet", + "--symbolic-full-name", + `refs/remotes/${remoteName}/HEAD`, + ], { allowNonZeroExit: true }, ).pipe( Effect.map((result) => { @@ -1730,8 +1892,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const originRemoteExists = (cwd: string): Effect.Effect => remoteExists({ cwd, remoteName: "origin" }); - const listRemoteNames = (cwd: string): Effect.Effect, GitCommandError> => - runGitStdout("GitVcsDriver.listRemoteNames", cwd, ["remote"]).pipe( + const listRemoteNames = ( + cwd: string, + gitDirArgs: ReadonlyArray = [], + ): Effect.Effect, GitCommandError> => + runGitStdout("GitVcsDriver.listRemoteNames", cwd, [...gitDirArgs, "remote"]).pipe( Effect.map(parseRemoteNamesInGitOrder), ); @@ -1754,6 +1919,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return firstRemote ?? null; }); + const resolvePrimaryDefaultBranchName = Effect.fn("GitVcsDriver.resolvePrimaryDefaultBranchName")( + function* (cwd: string, gitDirArgs: ReadonlyArray = []) { + const originDefault = yield* resolveDefaultBranchName(cwd, "origin", gitDirArgs); + if (originDefault !== null) return originDefault; + const remoteNames = yield* listRemoteNames(cwd, gitDirArgs); + const [firstRemote] = remoteNames; + return firstRemote === undefined || remoteNames.includes("origin") + ? null + : yield* resolveDefaultBranchName(cwd, firstRemote, gitDirArgs); + }, + ); + const resolvePrimaryRemoteName = (cwd: string) => findPrimaryRemoteName(cwd).pipe( Effect.filterOrFail( @@ -1770,7 +1947,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), ); - const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* ( + const resolveConfiguredPushRemoteName = Effect.fn("resolveConfiguredPushRemoteName")(function* ( cwd: string, refName: string, ) { @@ -1790,13 +1967,65 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["config", "--get", "remote.pushDefault"], true, ).pipe(Effect.map((stdout) => stdout.trim())); - if (pushDefaultRemote.length > 0) { - return pushDefaultRemote; + return pushDefaultRemote.length > 0 ? pushDefaultRemote : null; + }); + + const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* ( + cwd: string, + refName: string, + fallbackRemoteName: string | null = null, + ) { + const configuredRemote = yield* resolveConfiguredPushRemoteName(cwd, refName); + if (configuredRemote) { + return configuredRemote; + } + + if (fallbackRemoteName) { + return fallbackRemoteName; } return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null)); }); + const remoteRefContainsHead = (cwd: string, remoteRef: string) => + executeGit( + "GitVcsDriver.pushCurrentBranch.publishContainsHead", + cwd, + ["merge-base", "--is-ancestor", "HEAD", `refs/remotes/${remoteRef}`], + { allowNonZeroExit: true }, + ).pipe( + Effect.map((result) => result.exitCode === 0), + Effect.orElseSucceed(() => false), + ); + + // A fetch reads only the remote's first url, while a push writes every push URL (pushurl, else + // each url). A fetched ref is evidence of the push destination only when those are the same one. + const pushesOnlyToFetchUrl = Effect.fn("GitVcsDriver.pushesOnlyToFetchUrl")( + function* (cwd: string, remoteName: string) { + const [fetchUrl, pushUrls] = yield* Effect.all([ + runGitStdout("GitVcsDriver.pushesOnlyToFetchUrl.fetchUrl", cwd, [ + "remote", + "get-url", + "--", + remoteName, + ]), + runGitStdout("GitVcsDriver.pushesOnlyToFetchUrl.pushUrls", cwd, [ + "remote", + "get-url", + "--push", + "--all", + "--", + remoteName, + ]), + ]); + // Preserve whitespace in URLs and reject ambiguous multiline fetch URLs. + return ( + fetchUrl.endsWith("\n") && !fetchUrl.slice(0, -1).includes("\n") && pushUrls === fetchUrl + ); + }, + Effect.orElseSucceed(() => false), + ); + const ensureRemote: GitVcsDriver.GitVcsDriver["Service"]["ensureRemote"] = Effect.fn( "ensureRemote", )(function* (input) { @@ -2058,10 +2287,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* branch = branchNameFromHeadRef(branchResult.stdout); } const currentUpstreamRef = yield* readCurrentUpstreamRef(cwd); - let upstreamRef = - currentUpstreamRef === null - ? null - : (parseUpstreamRefByFirstSeparator(currentUpstreamRef)?.upstreamRef ?? null); + let upstreamRef = currentUpstreamRef; // Trimming a remote that starts with Unicode whitespace can leave a leading slash. if (currentUpstreamRef?.startsWith("/")) { upstreamRef = (yield* resolveCurrentUpstream(cwd, currentUpstreamRef))?.upstreamRef ?? null; @@ -2089,7 +2315,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); } - const defaultBranch = yield* resolveDefaultBranchName(cwd, "origin"); + const defaultBranch = yield* resolvePrimaryDefaultBranchName(cwd); const isDefaultBranch = branch !== null && (branch === defaultBranch || @@ -2121,11 +2347,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* options?: GitVcsDriver.GitLocalStatusOptions, ) { const includeDivergence = options?.includeDivergence !== false; + // Hidden untracked files could not be committed; `all` stays as configured. + const untrackedFilesHidden = untrackedFilesHiddenByConfig( + yield* readConfigValue(cwd, "status.showUntrackedFiles").pipe( + Effect.orElseSucceed(() => null), + ), + ); const statusArgs = [ "status", "--porcelain=2", "--branch", "-z", + ...(untrackedFilesHidden ? ["--untracked-files=normal"] : []), ...(includeDivergence ? [] : ["--no-ahead-behind"]), ]; const indexResult = yield* executeGitWithStableDiagnostics( @@ -2182,41 +2415,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error), }), ); + // Porcelain diff rewrites indexes despite GIT_OPTIONAL_LOCKS=0; plumbing with -M preserves rename detection. + const readNumstat = (ref: string) => + executeGitWithStableDiagnostics( + "GitVcsDriver.statusDetails.numstat", + cwd, + ["diff-index", "-M", "--numstat", "-z", ref, "--"], + { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + ); // diff-index does not read status output, so both spawn together; a non-repository discards it. const [statusResult, numstatResult, defaultBranch, hasPrimaryRemote] = yield* Effect.all( [ readStatus, - // Porcelain diff rewrites indexes despite GIT_OPTIONAL_LOCKS=0; plumbing with -M preserves rename detection. - executeGitWithStableDiagnostics( - "GitVcsDriver.statusDetails.numstat", - cwd, - ["diff-index", "-M", "--numstat", "-z", "HEAD", "--"], - { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, - ).pipe( + readNumstat("HEAD").pipe( + Effect.filterOrElse( + (result) => result.exitCode === 0 || !isUnbornHeadStderr(result.stderr), + () => Effect.flatMap(readEmptyTreeHash(cwd), readNumstat), + ), Effect.flatMap((result) => { if (result.exitCode === 0) return Effect.succeed(parseReviewNumstat(result.stdout)); - if (isUnbornHeadStderr(result.stderr)) { - return Effect.map( - Effect.all([ - runGitStdoutWithOptions( - "GitVcsDriver.statusDetails.numstat.unborn", - cwd, - ["diff-files", "--numstat", "-z"], - { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, - ), - runGitStdoutWithOptions( - "GitVcsDriver.statusDetails.numstat.unborn.staged", - cwd, - ["diff", "--cached", "--numstat", "-z"], - { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, - ), - ]), - ([unstagedStdout, stagedStdout]) => [ - ...parseReviewNumstat(stagedStdout), - ...parseReviewNumstat(unstagedStdout), - ], - ); - } return Effect.fail( new GitCommandError({ ...gitCommandContext({ @@ -2235,7 +2452,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), statusCacheKey ? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null)) - : resolveDefaultBranchName(cwd, "origin").pipe(Effect.orElseSucceed(() => null)), + : resolvePrimaryDefaultBranchName(cwd).pipe(Effect.orElseSucceed(() => null)), statusCacheKey ? Cache.get(primaryRemoteExistsCache, statusCacheKey).pipe( Effect.orElseSucceed(() => false), @@ -2273,6 +2490,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* let refName: string | null = null; let upstreamRef: string | null = null; + // Git omits branch.ab when the upstream ref is gone, e.g. deleted after its PR merged, + // and also for an unborn HEAD, which can still track a fetched upstream. + let upstreamRefExists = false; + let isUnbornHead = false; + let headOid: string | null = null; let aheadCount = 0; let behindCount = 0; let aheadOfDefaultCount = 0; @@ -2283,9 +2505,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const statusRecords = statusStdout.split("\0"); for (let index = 0; index < statusRecords.length; index++) { const line = statusRecords[index]!; + if (line === "# branch.oid (initial)") { + isUnbornHead = true; + continue; + } + if (line.startsWith("# branch.oid ")) { + headOid = line.slice("# branch.oid ".length).trim(); + continue; + } if (line.startsWith("# branch.head ")) { const value = line.slice("# branch.head ".length).trim(); - refName = value.startsWith("(") ? null : value; + // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. + refName = value === "(detached)" || value === "(unknown)" ? null : value; continue; } if (line.startsWith("# branch.upstream ")) { @@ -2293,11 +2524,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* upstreamRef = value.length > 0 ? value : null; continue; } - if (includeDivergence && line.startsWith("# branch.ab ")) { - const value = line.slice("# branch.ab ".length).trim(); - const parsed = parseBranchAb(value); - aheadCount = parsed.ahead; - behindCount = parsed.behind; + if (line.startsWith("# branch.ab ")) { + upstreamRefExists = true; + if (includeDivergence) { + const parsed = parseBranchAb(line.slice("# branch.ab ".length).trim()); + aheadCount = parsed.ahead; + behindCount = parsed.behind; + } continue; } if (line.length > 0 && !line.startsWith("#")) { @@ -2316,6 +2549,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } } + if (!upstreamRefExists && !isUnbornHead) upstreamRef = null; + const isDefaultBranch = refName !== null && (refName === defaultBranch || @@ -2333,6 +2568,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? readBranchChangeTotals(repositoryPaths?.worktreeRoot ?? cwd, refName, { knownOriginDefaultBranch: defaultBranch, untrackedRoots, + headOid, }).pipe(Effect.orElseSucceed(() => undefined)) : Effect.undefined, ], @@ -2440,6 +2676,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* })), ); + // git add takes --pathspec-from-file from Git 2.25; older Git keeps the argument form. + let pathspecFromFileSupported: boolean | undefined; + const supportsPathspecFromFile = Effect.fn("GitVcsDriver.supportsPathspecFromFile")(function* ( + cwd: string, + ) { + if (pathspecFromFileSupported !== undefined) return pathspecFromFileSupported; + const version = yield* executeGit("GitVcsDriver.version", cwd, ["version"]).pipe(Effect.option); + if (Option.isNone(version)) return false; + pathspecFromFileSupported = gitSupportsPathspecFromFile(version.value.stdout); + return pathspecFromFileSupported; + }); + const stageCommitChanges = Effect.fnUntraced(function* ( cwd: string, filePaths?: readonly string[], @@ -2448,6 +2696,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const config = env ? ["-c", "core.splitIndex=false", "-c", "splitIndex.sharedIndexExpire=never"] : []; + let preserveUnselectedConflicts = false; if (filePaths && filePaths.length > 0) { if (env) { const head = yield* executeGit( @@ -2464,43 +2713,188 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { env }, ); } else { - const mergeHeadPath = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ + const inProgressHeads = [ + { head: "MERGE_HEAD", operation: "merge" }, + { head: "CHERRY_PICK_HEAD", operation: "cherry-pick" }, + { head: "REVERT_HEAD", operation: "revert" }, + // A conflicted multi-commit `cherry-pick --no-commit` writes only the sequencer; reset + // would clear its unmerged entries, so `--continue` would walk past the conflict. + { head: "sequencer", operation: "cherry-pick or revert" }, + ] as const; + const headPaths = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ "rev-parse", - "--git-path", - "MERGE_HEAD", + ...inProgressHeads.flatMap(({ head }) => ["--git-path", head]), ]); - const isMerging = yield* fileSystem.exists(path.resolve(cwd, mergeHeadPath.trim())).pipe( + const resolvedHeadPaths = headPaths.trim().split("\n"); + // Reftable keeps CHERRY_PICK_HEAD and REVERT_HEAD as refs with no file under .git. A + // same-named branch resolves to its full name; an ambiguity warning would blank stdout. + const operationRefs = new Set(["CHERRY_PICK_HEAD", "REVERT_HEAD"]); + const isOperationRef = (head: string) => + runGitStdout( + "GitVcsDriver.commit.operationRef", + cwd, + [ + "-c", + "core.warnAmbiguousRefs=false", + "rev-parse", + "--verify", + "--quiet", + "--symbolic-full-name", + head, + ], + true, + ).pipe(Effect.map((ref) => ref.trim() === head)); + const inProgress = yield* Effect.findFirst(inProgressHeads, ({ head }, index) => + fileSystem.exists(path.resolve(cwd, resolvedHeadPaths[index] ?? "")).pipe( + Effect.filterOrElse( + (exists) => exists || !operationRefs.has(head), + () => isOperationRef(head), + ), + ), + ).pipe( Effect.mapError( (cause) => new GitCommandError({ operation: "GitVcsDriver.commit.mergeHead", command: "git commit", cwd, - detail: "Could not check whether a merge is in progress.", + detail: "Could not check whether a merge, cherry-pick or revert is in progress.", cause, }), ), ); - // Like git commit --only, reject partial merges before reset can discard their ancestry. - if (isMerging) { + // Like git commit --only, reject partial commits before reset can discard their state. + if (Option.isSome(inProgress)) { + const { operation } = inProgress.value; return yield* new GitCommandError({ operation: "GitVcsDriver.commit", command: "git commit", cwd, - detail: - "Cannot commit selected files during a merge. Commit all files to finish the merge.", + detail: `Cannot commit selected files during a ${operation}. Commit all files to finish the ${operation}.`, }); } - yield* runGit("GitVcsDriver.commit.reset", cwd, ["reset", "--quiet"]); + const selectedFiles = new Set(filePaths); + const unmergedPaths = yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.unmergedPaths", + cwd, + ["-c", "diff.relative=false", "diff", "--cached", "--name-only", "--diff-filter=U", "-z"], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + ); + // Reset drops every conflict stage, so keep the index while unselected files are conflicted. + preserveUnselectedConflicts = unmergedPaths + .split("\0") + .some((file) => file.length > 0 && !selectedFiles.has(file)); + if (!preserveUnselectedConflicts) { + yield* runGit("GitVcsDriver.commit.reset", cwd, ["reset", "--quiet"]); + } } + // Status paths are repository-relative, while cwd can be a subdirectory. + const pathspecs = filePaths.map((file) => `:(top,literal)${file}`); + const fromStdin = yield* supportsPathspecFromFile(cwd); yield* runGit( "GitVcsDriver.commit.addSelected", cwd, - // Status paths are repository-relative, while cwd can be a subdirectory. - [...config, "add", "-A", "--", ...filePaths.map((file) => `:(top,literal)${file}`)], - env ? { env } : {}, + fromStdin + ? [...config, "add", "-A", "--pathspec-from-file=-", "--pathspec-file-nul"] + : [...config, "add", "-A", "--", ...pathspecs], + { + ...(env ? { env } : {}), + ...(fromStdin ? { stdin: pathspecs.map((pathspec) => `${pathspec}\0`).join("") } : {}), + }, ); } else { + // add -A marks unmerged paths resolved, so refuse while one still has conflict markers. + const unmergedPaths = (yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.unmergedPaths", + cwd, + ["-c", "diff.relative=false", "diff", "--name-only", "--diff-filter=U", "-z"], + env ? { env } : {}, + )) + .split("\0") + .filter((file) => file.length > 0); + if (unmergedPaths.length > 0) { + const check = yield* executeGit( + "GitVcsDriver.commit.conflictMarkers", + cwd, + [ + "-c", + "diff.relative=false", + "diff", + "--check", + "--no-color", + "--", + ...unmergedPaths.map((file) => `:(top,literal)${file}`), + ], + { + ...(env ? { env } : {}), + allowNonZeroExit: true, + maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, + appendTruncationMarker: true, + }, + ); + const reports = check.stdout.split("\n"); + const conflicted: string[] = []; + let emptyTree: string | undefined; + for (const file of unmergedPaths) { + const markerLines = new Set( + reports.flatMap((line) => { + const match = line.startsWith(`${file}:`) + ? /^(\d+): leftover conflict marker$/.exec(line.slice(file.length + 1)) + : null; + return match ? [Number(match[1]) - 1] : []; + }), + ); + if (markerLines.size === 0) continue; + emptyTree ??= yield* readEmptyTreeHash(cwd); + // --check numbers lines after working-tree-encoding and clean filters; a diff from the + // empty tree prints that view. Read it in full so large resolved files can still commit. + const fileDiff = yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.conflictMarkers", + cwd, + [ + "-c", + "diff.relative=false", + "diff", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--text", + emptyTree, + "--", + `:(top,literal)${file}`, + ], + { ...(env ? { env } : {}), maxOutputBytes: Number.POSITIVE_INFINITY }, + ).pipe( + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "GitVcsDriver.commit.conflictMarkers", + command: "git commit", + cwd, + detail: `Could not check ${file} for conflict markers.`, + cause, + }), + ), + ); + const diffLines = fileDiff.split("\n"); + const lines = diffLines + .slice(diffLines.findIndex((line) => line.startsWith("@@")) + 1) + .filter((line) => line.startsWith("+")) + .map((line) => line.slice(1)); + // Git also reports a lone "=======", which is valid content such as a heading underline. + const reported = (marker: string) => + lines.some((line, index) => markerLines.has(index) && line.startsWith(marker)); + if (reported("<") && reported(">")) conflicted.push(file); + } + if (conflicted.length > 0) { + return yield* new GitCommandError({ + operation: "GitVcsDriver.commit", + command: "git commit", + cwd, + detail: `Cannot commit with unresolved merge conflicts in ${conflicted.join(", ")}. Resolve them, then commit.`, + }); + } + } yield* runGit( "GitVcsDriver.commit.addAll", cwd, @@ -2508,23 +2902,56 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* env ? { env } : {}, ); } + return preserveUnselectedConflicts && filePaths + ? filePaths.map((file) => `:(top,literal)${file}`) + : undefined; }); const prepareCommitContext: GitVcsDriver.GitVcsDriver["Service"]["prepareCommitContext"] = Effect.fn("prepareCommitContext")(function* (cwd, filePaths, options) { return yield* Effect.scoped( Effect.gen(function* () { - const indexValue = yield* runGitStdout( - "GitVcsDriver.prepareCommitContext.indexPath", + const [indexValue = "", objectsValue = ""] = (yield* runGitStdout( + "GitVcsDriver.prepareCommitContext.gitPaths", cwd, - ["rev-parse", "--git-path", "index"], - ); - const indexPath = path.resolve(cwd, indexValue.trim()); + ["rev-parse", "--git-path", "index", "--git-path", "objects"], + )).split("\n"); + // Git's relative paths use the physical cwd, even when the project uses a symlink. + const physicalCwd = yield* fileSystem.realPath(cwd); + const indexPath = path.resolve(physicalCwd, indexValue.trim()); const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-commit-index-", }); const tempIndexPath = path.join(directory, "index"); - const env = { GIT_INDEX_FILE: tempIndexPath } satisfies NodeJS.ProcessEnv; + // Staging writes blobs; put them in the temp directory so a draft leaves nothing behind. + // List every object directory Git resolved (nested and environment alternates) flat, + // since nesting the repository's objects one level deeper can pass Git's depth limit. + const objectDirectories = yield* runGitStdout( + "GitVcsDriver.prepareCommitContext.alternates", + cwd, + ["count-objects", "-v"], + ); + // Git prints an entry C-quoted when it needs quoting; quote the rest the same way, so a + // path holding the list separator stays one entry (Git 2.11.1+). + const quoted = (entry: string) => + entry.startsWith('"') ? entry : `"${entry.replace(/[\\"]/g, "\\$&")}"`; + const alternates = [ + path.resolve(physicalCwd, objectsValue.trim()), + ...objectDirectories + .split("\n") + .flatMap((line) => + line.startsWith("alternate: ") ? [line.slice("alternate: ".length)] : [], + ), + ]; + const tempObjectsPath = path.join(directory, "objects"); + yield* fileSystem.makeDirectory(tempObjectsPath); + const env = { + GIT_INDEX_FILE: tempIndexPath, + GIT_OBJECT_DIRECTORY: tempObjectsPath, + GIT_ALTERNATE_OBJECT_DIRECTORIES: alternates + .map(quoted) + .join(hostPlatform === "win32" ? ";" : ":"), + } satisfies NodeJS.ProcessEnv; const config = [ "-c", "core.splitIndex=false", @@ -2562,7 +2989,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { env, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ).pipe(Effect.map((stdout) => stdout.trim())); if (stagedSummary.length === 0) { - return null; + // Like git commit, a merge resolved to HEAD's tree still records its merge commit. + const mergeHeadPath = yield* runGitStdout( + "GitVcsDriver.prepareCommitContext.mergeHead", + cwd, + ["rev-parse", "--git-path", "MERGE_HEAD"], + ); + if (!(yield* fileSystem.exists(path.resolve(physicalCwd, mergeHeadPath.trim())))) { + return null; + } } // A user-supplied message needs change detection, but no patch for generation. @@ -2614,14 +3049,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* body, options?: GitVcsDriver.GitCommitOptions, ) { - if (options?.stage !== undefined) { - yield* stageCommitChanges(cwd, options.stage.filePaths); - } + const partialCommitPaths = + options?.stage !== undefined + ? yield* stageCommitChanges(cwd, options.stage.filePaths) + : undefined; const args = ["commit", "-m", subject]; const trimmedBody = body.trim(); if (trimmedBody.length > 0) { args.push("-m", trimmedBody); } + const onlyFromStdin = partialCommitPaths ? yield* supportsPathspecFromFile(cwd) : false; + const onlyPathspecArgs = onlyFromStdin + ? ["--pathspec-from-file=-", "--pathspec-file-nul"] + : ["--", ...(partialCommitPaths ?? [])]; + const onlyPathspecStdin = + partialCommitPaths && onlyFromStdin + ? { stdin: partialCommitPaths.map((pathspec) => `${pathspec}\0`).join("") } + : {}; + if (partialCommitPaths) { + args.push("--only", ...onlyPathspecArgs); + } const progress = options?.progress?.onOutputLine === undefined ? options?.progress @@ -2634,9 +3081,19 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; yield* executeGit("GitVcsDriver.commit.commit", cwd, args, { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, + ...onlyPathspecStdin, ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), ...(progress ? { progress } : {}), }).pipe(Effect.asVoid); + if (partialCommitPaths) { + // --only runs hooks on a temporary index, so a hook's `git add` never reaches the real one. + yield* runGit( + "GitVcsDriver.commit.syncSelectedIndex", + cwd, + ["reset", "--quiet", "HEAD", ...onlyPathspecArgs], + onlyPathspecStdin, + ); + } const commitSha = yield* runGitStdout("GitVcsDriver.commit.revParseHead", cwd, [ "rev-parse", "HEAD", @@ -2677,24 +3134,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* hasUpstream: boolean, ) { if (!hasUpstream) { - const remoteName = yield* resolvePushRemoteName(cwd, branch); + // A deleted upstream keeps its config: republish to it when it was this branch's own, + // otherwise it was the base, so keep that before publishing. + let goneUpstream: { remoteName: string; branchName: string } | null = null; + let goneBaseUpstream: { remoteName: string; branchName: string; upstreamRef: string } | null = + null; + const mergeRef = yield* readConfigValue(cwd, `branch.${branch}.merge`); + const mergeBranch = mergeRef?.startsWith("refs/heads/") + ? mergeRef.slice("refs/heads/".length) + : null; + const configuredRemoteName = yield* readConfigValue(cwd, `branch.${branch}.remote`); + if (mergeBranch && configuredRemoteName && configuredRemoteName !== ".") { + if (isAliasOfUpstreamHead(branch, mergeBranch, `${configuredRemoteName}/${mergeBranch}`)) { + goneUpstream = { remoteName: configuredRemoteName, branchName: mergeBranch }; + } else { + goneBaseUpstream = { + remoteName: configuredRemoteName, + branchName: mergeBranch, + upstreamRef: `${configuredRemoteName}/${mergeBranch}`, + }; + } + } + const remoteName = yield* resolvePushRemoteName(cwd, branch, goneUpstream?.remoteName); + if (!remoteName) return null; + // A gone local upstream still gets the full local name, as below. + const branchName = + goneUpstream?.branchName ?? + (configuredRemoteName === "." ? branch : yield* resolvePublishBranchName(cwd, branch)); + return { + remoteName, + branchName, + publishes: true, + upstream: goneBaseUpstream, + pushRemote: null, + }; + } + + if ((yield* readConfigValue(cwd, `branch.${branch}.remote`)) === ".") { + const localUpstream = yield* readCurrentUpstreamRef(cwd).pipe( + Effect.orElseSucceed(() => null), + ); + if (localUpstream === null) return null; + // A local upstream is a base; publish under the full local name so `origin/main` never lands on remote `main`. + const remoteName = yield* resolvePushRemoteName(cwd, branch).pipe( + Effect.orElseSucceed(() => null), + ); if (!remoteName) return null; - const branchName = yield* resolvePublishBranchName(cwd, branch); - return { remoteName, branchName, publishes: true, upstream: null }; + return { + remoteName, + branchName: branch, + publishes: true, + upstream: { remoteName: ".", branchName: localUpstream, upstreamRef: localUpstream }, + pushRemote: null, + }; } const upstream = yield* resolveCurrentUpstream(cwd).pipe(Effect.orElseSucceed(() => null)); if (!upstream) return null; - // Differently named upstreams are bases, not publish targets; pushing HEAD there would write features to shared branches. - const isAliasOfUpstreamHead = - branch === upstream.branchName || - (branch.endsWith(`/${upstream.branchName}`) && upstream.upstreamRef.endsWith(`/${branch}`)); - if (isAliasOfUpstreamHead) { + if (isAliasOfUpstreamHead(branch, upstream.branchName, upstream.upstreamRef)) { + // A fork workflow pushes to the configured push remote and keeps the upstream for pulls, as plain `git push` does. + const configuredPushRemote = yield* resolveConfiguredPushRemoteName(cwd, branch).pipe( + Effect.orElseSucceed(() => null), + ); + const pushRemote = + configuredPushRemote && configuredPushRemote !== upstream.remoteName + ? configuredPushRemote + : null; return { - remoteName: upstream.remoteName, + remoteName: pushRemote ?? upstream.remoteName, branchName: upstream.branchName, publishes: false, upstream, + pushRemote, }; } const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( @@ -2706,6 +3217,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* branchName, publishes: true, upstream, + pushRemote: null, }; }); @@ -2714,7 +3226,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* )(function* (cwd, current) { const destination = yield* resolvePushDestination(cwd, current.branch, current.hasUpstream); return destination - ? { remoteName: destination.remoteName, branchName: destination.branchName } + ? { + remoteName: destination.remoteName, + branchName: destination.branchName, + viaPushRemote: destination.pushRemote !== null, + } : null; }); @@ -2737,7 +3253,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { const publishBranch = yield* resolvePublishBranchName(cwd, branch); - yield* runGit( + yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, ["push", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`], @@ -2752,16 +3268,41 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; - if (hasNoLocalDelta && details.hasUpstream) { - return { - status: "skipped_up_to_date" as const, - branch, - ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), - }; - } - const destination = yield* resolvePushDestination(cwd, branch, details.hasUpstream); - if (hasNoLocalDelta) { + if (hasNoLocalDelta && details.hasUpstream) { + if (!destination?.pushRemote) { + // The tracking ref reflects the fetch URL, so it says nothing about a separate push URL. + if (!destination || (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) { + return { + status: "skipped_up_to_date" as const, + branch, + ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + }; + } + } else { + const { pushRemote, branchName } = destination; + const pushRemoteRef = `${pushRemote}/${branchName}`; + // The local ref can be stale when the branch was deleted or rewound elsewhere. + const pushRemoteHasHead = + (yield* pushesOnlyToFetchUrl(cwd, pushRemote)) && + (yield* fetchRemoteTrackingBranch({ + cwd, + remoteName: pushRemote, + remoteBranch: branchName, + }).pipe( + Effect.andThen(remoteRefContainsHead(cwd, pushRemoteRef)), + Effect.orElseSucceed(() => false), + )); + if (pushRemoteHasHead) { + return { + status: "skipped_up_to_date" as const, + branch, + upstreamBranch: pushRemoteRef, + pushRemote, + }; + } + } + } else if (hasNoLocalDelta) { const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( Effect.orElseSucceed(() => null), ); @@ -2774,21 +3315,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } // The configured diff base can contain HEAD while the publish branch is still behind. - const publishContainsHead = yield* executeGit( - "GitVcsDriver.pushCurrentBranch.publishContainsHead", - cwd, - [ - "merge-base", - "--is-ancestor", - "HEAD", - `refs/remotes/${destination.remoteName}/${destination.branchName}`, - ], - { allowNonZeroExit: true }, - ).pipe( - Effect.map((result) => result.exitCode === 0), - Effect.orElseSucceed(() => false), - ); - if (publishContainsHead) { + if ( + (yield* remoteRefContainsHead( + cwd, + `${destination.remoteName}/${destination.branchName}`, + )) && + (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName)) + ) { return { status: "skipped_up_to_date" as const, branch, @@ -2797,7 +3330,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } } - if (!details.hasUpstream && !destination) { + if ( + !destination && + (!details.hasUpstream || (yield* readConfigValue(cwd, `branch.${branch}.remote`)) === ".") + ) { return yield* new GitCommandError({ ...gitCommandContext({ operation: "GitVcsDriver.pushCurrentBranch", @@ -2821,11 +3357,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* writeConfigValue({ cwd, key: `branch.${branch}.t3-merge-base-ref`, - value: `refs/remotes/${upstream.upstreamRef}`, + value: + upstream.remoteName === "." + ? `refs/heads/${upstream.branchName}` + : `refs/remotes/${upstream.upstreamRef}`, }); } } - yield* runGit( + yield* executeGitWithStableDiagnostics( upstream ? "GitVcsDriver.pushCurrentBranch.pushOwnBranch" : "GitVcsDriver.pushCurrentBranch.pushWithUpstream", @@ -2842,7 +3381,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } if (destination?.upstream) { - yield* runGit( + yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushUpstream", cwd, ["push", "--", destination.remoteName, `HEAD:refs/heads/${destination.branchName}`], @@ -2851,12 +3390,19 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { status: "pushed" as const, branch, - upstreamBranch: destination.upstream.upstreamRef, + ...(destination.pushRemote + ? { + upstreamBranch: `${destination.remoteName}/${destination.branchName}`, + pushRemote: destination.pushRemote, + } + : { upstreamBranch: destination.upstream.upstreamRef }), setUpstream: false, }; } - yield* runGit("GitVcsDriver.pushCurrentBranch.push", cwd, ["push"], { timeoutMs: null }); + yield* executeGitWithStableDiagnostics("GitVcsDriver.pushCurrentBranch.push", cwd, ["push"], { + timeoutMs: null, + }); return { status: "pushed" as const, branch, @@ -2891,12 +3437,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } const remote = yield* readConfigValue(cwd, `branch.${refName}.remote`); + // The upstream-only retry leaves other remote-tracking refs stale, so a claimed status + // fetch must still run after it. + let fetchedUpstreamOnly = false; if (remote) { const gitCommonDir = yield* resolveGitCommonDir(cwd); const pending = statusFetches.get(`${gitCommonDir}\0${remote}`); // The status wait can finish while its fetch still owns reference locks. // Let our existing writer finish before starting the pull's fetch. - if (pending) yield* Fiber.await(pending); + if (pending) { + const claimed = yield* Effect.uninterruptible( + Effect.gen(function* () { + if (pending.state.phase !== "queued") return false; + pending.state.phase = "claimed"; + yield* Effect.addFinalizer((exit) => + Deferred.succeed( + pending.state.finished, + Exit.isSuccess(exit) && !fetchedUpstreamOnly, + ), + ); + yield* Deferred.succeed(pending.state.claimed, undefined); + return true; + }), + ); + if (!claimed) yield* Fiber.await(pending.fiber); + } } const beforeSha = yield* runGitStdout( "GitVcsDriver.pullCurrentBranch.beforeSha", @@ -2907,8 +3472,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // After a successful pull, HEAD before and after decides the result, so its output is not // needed. A large fast-forward's diffstat can exceed the output cap, which must not fail a // pull Git applied. + // A deadline would kill git mid-checkout (e.g. a slow LFS smudge) and strand a half-updated tree. const options = { - timeoutMs: 30_000, + timeoutMs: null, appendTruncationMarker: true, allowNonZeroExit: true, }; @@ -2949,6 +3515,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* currentSha === beforeSha ) { args = ["pull", "--ff-only", "--", remote, mergeRef]; + fetchedUpstreamOnly = true; result = yield* executeGitWithStableDiagnostics( "GitVcsDriver.pullCurrentBranch.pull", cwd, @@ -2977,11 +3544,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const refreshed = yield* readStatusDetailsLocal(cwd); return { - status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", + status: + beforeSha.length > 0 && beforeSha === afterSha + ? ("skipped_up_to_date" as const) + : ("pulled" as const), refName, upstreamRef: refreshed.upstreamRef, }; - }); + }, Effect.scoped); const readRangeContext: GitVcsDriver.GitVcsDriver["Service"]["readRangeContext"] = Effect.fn( "readRangeContext", @@ -3058,6 +3628,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const prepareReviewIndex = Effect.fn("prepareReviewIndex")(function* ( cwd: string, untrackedPaths: ReadonlyArray, + allowPartial: boolean, ) { const [stagedDeletionsStdout, indexValue] = yield* Effect.all( [ @@ -3085,8 +3656,42 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { concurrency: 2 }, ); const stagedDeletions = new Set(stagedDeletionsStdout.split("\0").filter(Boolean)); - const pathsToAdd = untrackedPaths.filter((relativePath) => !stagedDeletions.has(relativePath)); - if (pathsToAdd.length === 0) return undefined; + // Staged deletions never enter the index, so their worktree copies must not spend the budget. + // A nested repository (listed with a trailing slash) with no commits cannot be indexed: + // Git before 2.53 fails the add, and later versions accept it and then fail every diff. + const candidates = yield* Effect.filter( + untrackedPaths.filter((relativePath) => !stagedDeletions.has(relativePath)), + (relativePath) => + relativePath.endsWith("/") + ? executeGit( + "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.nestedRepositoryHead", + path.resolve(cwd, relativePath), + ["rev-parse", "--verify", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ).pipe(Effect.map((result) => result.exitCode !== 1)) + : Effect.succeed(true), + { concurrency: 16 }, + ); + const sizes = yield* Effect.forEach( + candidates, + (relativePath) => + fileSystem.lstat(path.resolve(cwd, relativePath)).pipe( + Effect.map((info) => (info.type === "File" ? Number(info.size) : 0)), + Effect.orElseSucceed(() => 0), + Effect.map((size) => ({ relativePath, size })), + ), + { concurrency: 16 }, + ); + // Smallest first, so which files fit does not depend on how their names sort. + const pathsToAdd: string[] = []; + let bytes = 0; + for (const { relativePath, size } of sizes.toSorted((left, right) => left.size - right.size)) { + bytes += size; + if (bytes > REVIEW_UNTRACKED_MAX_BYTES) break; + pathsToAdd.push(relativePath); + } + const omitted = pathsToAdd.length < candidates.length; + if (pathsToAdd.length === 0 || (omitted && !allowPartial)) return { env: undefined, omitted }; const indexPath = path.isAbsolute(indexValue.trim()) ? indexValue.trim() @@ -3139,7 +3744,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ], { env, stdin: `${pathsToAdd.join("\0")}\0` }, ); - return env; + return { env, omitted }; }); const readEmptyTreeHash = Effect.fn("readEmptyTreeHash")(function* (cwd: string) { @@ -3152,26 +3757,33 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return stdout.trim(); }); - const prepareUntrackedReviewIndex = Effect.fn("prepareUntrackedReviewIndex")(function* ( + const prepareUntrackedReviewIndexOrReason = Effect.fn("prepareUntrackedReviewIndex")(function* ( cwd: string, pathArgs: ReadonlyArray, - onlyPath?: string, + onlyPath: string | undefined, + allowPartial: boolean, ) { const untracked = yield* executeGit( "GitVcsDriver.review.listUntracked", cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathArgs], { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, - ).pipe(Effect.orElseSucceed(() => null)); - if (untracked === null) return null; + ).pipe( + Effect.catchTags({ + GitCommandError: (error) => + Effect.succeed({ unavailable: `Could not list untracked files: ${error.detail}` }), + }), + ); + if ("unavailable" in untracked) return untracked; // ls-files lists a nested repository with a trailing slash; its diff path has none. const paths = splitNullSeparatedGitStdoutPaths(untracked).filter( (candidate) => onlyPath === undefined || candidate === onlyPath || candidate === `${onlyPath}/`, ); - if (paths.length === 0) return { env: undefined }; - if (paths.length > REVIEW_UNTRACKED_MAX_FILES) return null; - const env = yield* prepareReviewIndex(cwd, paths).pipe( + if (paths.length === 0) return { env: undefined, omitted: false }; + if (paths.length > REVIEW_UNTRACKED_MAX_FILES) + return { unavailable: "Too many untracked files to count." }; + const index = yield* prepareReviewIndex(cwd, paths, allowPartial).pipe( Effect.catchTags({ PlatformError: (cause) => Effect.fail( @@ -3185,8 +3797,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), }), ); - return { env }; + if (index.omitted && !allowPartial) + return { unavailable: "Untracked files are too large to count." }; + return index; }); + const prepareUntrackedReviewIndex = ( + cwd: string, + pathArgs: ReadonlyArray, + onlyPath?: string, + ) => + prepareUntrackedReviewIndexOrReason(cwd, pathArgs, onlyPath, true).pipe( + Effect.map((result) => ("unavailable" in result ? null : result)), + ); const resolveReviewMergeBase = Effect.fn("resolveReviewMergeBase")(function* ( cwd: string, @@ -3241,6 +3863,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* options?: { readonly knownOriginDefaultBranch: string | null; readonly untrackedRoots: ReadonlyArray; + readonly headOid: string | null; }, ) { const resolved = yield* resolveReviewMergeBase( @@ -3254,34 +3877,107 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* branch === null || (yield* branchExists(cwd, branch)) ? resolved : { baseRef: null, mergeBase: "HEAD" }; + // A moved HEAD or merge base skips the backoff and diffs again. + const diffKey = options?.headOid ? `${options.headOid}\0${mergeBase}` : null; + const diffFailure = branchTotalsDiffFailures.get(cwd); + if ( + diffFailure !== undefined && + diffFailure.key === diffKey && + (yield* Clock.currentTimeMillis) < diffFailure.retryAt + ) { + return yield* new GitCommandError({ + operation: "GitVcsDriver.readBranchChangeTotals", + command: "git diff --numstat", + cwd, + detail: diffFailure.detail, + }); + } const roots = options?.untrackedRoots ?? []; // Bound pathspec matching work and stay below Windows' command-line limit. const pathspecs = roots.length <= 128 && roots.reduce((length, root) => length + root.length + 16, 0) < 8_000 ? roots.map((root) => `:(top,literal)${root}`) : []; - // Empty status can mean untracked files are hidden; retain the full scan. - const untracked = yield* prepareUntrackedReviewIndex(cwd, pathspecs); - if (untracked === null) { + // Changed untracked roots skip the backoff and scan again. + const rootsKey = roots.join("\0"); + const remembered = untrackedTotalsFailures.get(cwd); + if ( + remembered !== undefined && + remembered.roots === rootsKey && + (yield* Clock.currentTimeMillis) < remembered.retryAt + ) { + return yield* new GitCommandError({ + operation: "GitVcsDriver.readBranchChangeTotals", + command: "git ls-files", + cwd, + detail: remembered.detail, + }); + } + // Status always lists untracked files, so no roots means there are none to scan. + const untracked = + roots.length === 0 + ? { env: undefined, omitted: false } + : yield* prepareUntrackedReviewIndexOrReason(cwd, pathspecs, undefined, false); + if ("unavailable" in untracked) { + const count = remembered?.roots === rootsKey ? remembered.count + 1 : 1; + untrackedTotalsFailures.delete(cwd); + untrackedTotalsFailures.set(cwd, { + roots: rootsKey, + count, + retryAt: + (yield* Clock.currentTimeMillis) + + Math.min(UNTRACKED_TOTALS_RETRY_MIN_MS * 2 ** (count - 1), UNTRACKED_TOTALS_RETRY_MAX_MS), + detail: untracked.unavailable, + }); + if (untrackedTotalsFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) { + const oldestKey = untrackedTotalsFailures.keys().next().value; + if (oldestKey !== undefined) untrackedTotalsFailures.delete(oldestKey); + } return yield* new GitCommandError({ operation: "GitVcsDriver.readBranchChangeTotals", command: "git ls-files", cwd, - detail: "Too many untracked files to count.", + detail: untracked.unavailable, }); } + untrackedTotalsFailures.delete(cwd); const readNumstat = (ref: string) => executeGit( "GitVcsDriver.readBranchChangeTotals", cwd, - [...REVIEW_DIFF_ARGS, "--numstat", "-z", ref, "--"], + // Plumbing: porcelain diff refreshes and rewrites the real index, taking index.lock. + ["diff-index", "-M", "--numstat", "-z", ref, "--"], { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, env: untracked.env, }, ); - let result = yield* readNumstat(mergeBase); + let result = yield* readNumstat(mergeBase).pipe( + Effect.tapError((error) => + Effect.gen(function* () { + if (diffKey === null) return; + const count = diffFailure?.key === diffKey ? diffFailure.count + 1 : 1; + branchTotalsDiffFailures.delete(cwd); + branchTotalsDiffFailures.set(cwd, { + key: diffKey, + count, + retryAt: + (yield* Clock.currentTimeMillis) + + Math.min( + UNTRACKED_TOTALS_RETRY_MIN_MS * 2 ** (count - 1), + UNTRACKED_TOTALS_RETRY_MAX_MS, + ), + detail: error.detail, + }); + if (branchTotalsDiffFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) { + const oldestKey = branchTotalsDiffFailures.keys().next().value; + if (oldestKey !== undefined) branchTotalsDiffFailures.delete(oldestKey); + } + }), + ), + ); + branchTotalsDiffFailures.delete(cwd); if (result.exitCode !== 0 && mergeBase === "HEAD" && isUnbornHeadStderr(result.stderr)) { result = yield* readNumstat(yield* readEmptyTreeHash(cwd)); } @@ -3500,7 +4196,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const stat = yield* executeGit( "GitVcsDriver.getReviewDiffPreview.commitStat", cwd, - [...diffArgs, "--numstat", "-z", commit.parent, commit.sha, "--", ...pathArgs], + [...diffArgs, "--raw", "--numstat", "-z", commit.parent, commit.sha, "--", ...pathArgs], { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ); const files = parseReviewNumstat(stat.stdout); @@ -3550,7 +4246,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ref: string, env?: NodeJS.ProcessEnv, ) { - const args = [...diffArgs, "--numstat", "-z"]; + const args = [...diffArgs, "--raw", "--numstat", "-z"]; const result = yield* executeGit( "GitVcsDriver.getReviewDiffPreview.stat", cwd, @@ -3596,9 +4292,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () { const untracked = input.trackedOnly - ? { env: undefined } + ? { env: undefined, omitted: false } : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); - const metadataOnly = input.metadataOnly === true && !input.file && untracked !== null; + // Untracked files left out make the file list partial, so the bounded patch is sent instead. + const complete = untracked !== null && !untracked.omitted; + const metadataOnly = input.metadataOnly === true && !input.file && complete; const [dirty, base] = review.mergeBase === dirtyRef ? yield* readTrackedDiff(dirtyRef, untracked?.env, metadataOnly).pipe( @@ -3611,7 +4309,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ], { concurrency: 2 }, ); - if (untracked !== null) return [dirty, base] as const; + if (complete) return [dirty, base] as const; const incomplete = (ref: string | null, result: typeof dirty) => ref === null ? result : { ...result, files: undefined, stdoutTruncated: true }; return [incomplete(dirtyRef, dirty), incomplete(review.mergeBase, base)] as const; @@ -3769,7 +4467,43 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (bytes.includes(0)) { return yield* fileError("fs.readFile", `Cannot expand binary file '${input.newPath}'.`); } - return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); + const contents = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); + if (!contents.includes("$Id:")) return contents; + const collapsed = contents.replace(GIT_IDENT_KEYWORD, () => "$Id$"); + if (collapsed === contents) return contents; + // check-attr reports both boolean ident and literal ident=set as "set". + const attribute = yield* runGitStdout( + "GitVcsDriver.getReviewDiffFileContents.workingTree.ident", + repositoryRoot, + ["check-attr", "-z", "ident", "filter", "--", input.newPath], + ); + const attributes = attribute.split("\0"); + if (attributes[2] !== "set" || attributes[5] !== "unspecified") return contents; + + // Literal filter=unspecified is indistinguishable from an absent filter in check-attr. + const filters = yield* executeGit( + "GitVcsDriver.getReviewDiffFileContents.workingTree.filters", + repositoryRoot, + ["config", "--name-only", "--get-regexp", "^filter\\.unspecified\\."], + { allowNonZeroExit: true }, + ); + if (filters.exitCode !== 1 || filters.stdout.length > 0) return contents; + // Probe a nonoverlapping keyword so ident conversion runs once on the actual file. + const [canonicalHash, collapsedHash] = yield* Effect.all([ + runGitStdoutWithOptions( + "GitVcsDriver.getReviewDiffFileContents.workingTree.canonicalHash", + repositoryRoot, + ["hash-object", "--stdin", `--path=${input.newPath}`], + { stdin: "$Id: probe $" }, + ), + runGitStdoutWithOptions( + "GitVcsDriver.getReviewDiffFileContents.workingTree.collapsedHash", + repositoryRoot, + ["hash-object", "--stdin", `--path=${input.newPath}`], + { stdin: "$Id$" }, + ), + ]); + return canonicalHash === collapsedHash ? collapsed : contents; }); const getReviewDiffFileContents = Effect.fn("getReviewDiffFileContents")(function* ( @@ -3967,7 +4701,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* executeGit( "GitVcsDriver.listRefs.defaultRef", fetchCwd, - [...gitDirArgs, "symbolic-ref", "refs/remotes/origin/HEAD"], + [ + ...gitDirArgs, + "rev-parse", + "--verify", + "--quiet", + "--symbolic-full-name", + "refs/remotes/origin/HEAD", + ], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -3995,7 +4736,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const defaultBranch = defaultRefResult.exitCode === 0 - ? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "") + ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin") : null; const parsedWorktreeEntries = worktreeListResult.exitCode === 0 @@ -4070,6 +4811,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : left.ref.name.localeCompare(right.ref.name); return { + defaultBranch, localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), hasPrimaryRemote: remoteNames.length > 0, @@ -4198,22 +4940,51 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; } - const snapshot = yield* resolveListRefsSnapshot( - repositoryPaths.gitCommonDir, - input.refresh === true, + // Both caches outlive a checkout made outside T3 Code, so this checkout's branch is read + // on every call and replaces whatever the cached snapshot claims for it. + const [snapshot, currentBranch] = yield* Effect.all( + [ + resolveListRefsSnapshot(repositoryPaths.gitCommonDir, input.refresh === true), + readCurrentBranch("GitVcsDriver.listRefs.currentBranch", input.cwd).pipe( + Effect.orElseSucceed(() => repositoryPaths.currentBranch), + ), + ], + { concurrency: 2 }, ); - const hasCurrentWorktreeBranch = - repositoryPaths.worktreeRoot !== null && - snapshot.localBranches.some((ref) => ref.worktreePath === repositoryPaths.worktreeRoot); - const localBranches = snapshot.localBranches.map((ref) => ({ - ...ref, - worktreePath: - ref.worktreePath ?? - (ref.name === repositoryPaths.currentBranch ? repositoryPaths.worktreeRoot : null), - current: hasCurrentWorktreeBranch - ? ref.worktreePath === repositoryPaths.worktreeRoot - : ref.name === repositoryPaths.currentBranch, - })); + const { worktreeRoot } = repositoryPaths; + // The snapshot misses a branch created outside T3 Code until it refreshes. An unborn HEAD + // names a branch with no ref yet, so the ref must exist before it is listed. + const currentBranchUnlisted = + currentBranch !== null && !snapshot.localBranches.some((ref) => ref.name === currentBranch); + const unlistedCurrentBranch: ReadonlyArray = + currentBranchUnlisted && + (yield* branchExists(input.cwd, currentBranch).pipe(Effect.orElseSucceed(() => false))) + ? [ + { + name: currentBranch, + current: true, + isRemote: false, + isDefault: currentBranch === snapshot.defaultBranch, + worktreePath: worktreeRoot, + }, + ] + : []; + const listedBranches = snapshot.localBranches.map((ref) => { + const current = ref.name === currentBranch; + return { + ...ref, + worktreePath: + worktreeRoot === null + ? ref.worktreePath + : current + ? worktreeRoot + : ref.worktreePath === worktreeRoot + ? null + : ref.worktreePath, + current, + }; + }); + const localBranches = [...unlistedCurrentBranch, ...listedBranches]; const combinedBranches = input.includeMatchingRemoteRefs ? [...localBranches, ...snapshot.remoteBranches] : dedupeRemoteBranchesWithLocalMatches([...localBranches, ...snapshot.remoteBranches]); @@ -4247,6 +5018,86 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }, ); + // A checkout stamps most files in the second it writes the index, and Git re-reads every file + // stamped in the index's own second or later ("racily clean") on each status, diff and add. + // T3's own git calls never rewrite a worktree's index, so refresh it once. + const refreshNewWorktreeIndex = Effect.fn("refreshNewWorktreeIndex")(function* ( + worktreePath: string, + ) { + const indexPath = path.resolve( + worktreePath, + (yield* runGitStdout("GitVcsDriver.createWorktree.indexPath", worktreePath, [ + "rev-parse", + "--git-path", + "index", + ])).trim(), + ); + const indexSecond = fileSystem.stat(indexPath).pipe( + Effect.map(({ mtime }) => Option.map(mtime, (date) => Math.floor(date.getTime() / 1000))), + Effect.orElseSucceed(() => Option.none()), + ); + // Older Git (such as 2.30) skips the write when racy entries merely check out clean. + // A refresh re-reads every checked-out file, so allow five minutes outside shared permits. + const refresh = runGit( + "GitVcsDriver.createWorktree.refreshIndex", + worktreePath, + ["update-index", "-q", "--refresh", "--force-write-index"], + { timeoutMs: WORKTREE_INDEX_REFRESH_TIMEOUT_MS }, + ); + const checkoutSecond = yield* indexSecond; + yield* refresh; + const refreshedSecond = yield* indexSecond; + if ( + Option.isNone(checkoutSecond) || + Option.isNone(refreshedSecond) || + refreshedSecond.value > checkoutSecond.value + ) { + return; + } + // The refresh finished within the checkout's second, so its index is just as racy. Wait that + // second out (file timestamps can trail the clock by a kernel tick) and refresh again. Two + // seconds or more means this clock does not match the file timestamps, as on a share stamped + // by another machine, so it cannot say when that second ends. + const delay = (checkoutSecond.value + 1) * 1000 + 50 - (yield* Clock.currentTimeMillis); + if (delay >= 2_000) return; + if (delay > 0) yield* Effect.sleep(Duration.millis(delay)); + yield* refresh; + }); + + // Git writes the lock reason during registration, before checkout or user hooks can run. + const releaseWorktreeRegistration = Effect.fn("releaseWorktreeRegistration")(function* ( + cwd: string, + reason: string, + remove: boolean, + ) { + const commonDir = yield* readGitCommonDir(cwd); + if (commonDir === null) return; + const registrations = path.join(commonDir, "worktrees"); + const entries = yield* fileSystem.readDirectory(registrations).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed([]), + ), + ); + for (const entry of entries) { + const adminDir = path.join(registrations, entry); + const locked = yield* fileSystem + .readFileString(path.join(adminDir, "locked")) + .pipe(Effect.orElseSucceed(() => "")); + if (locked.replace(/\r?\n$/, "") !== reason) continue; + // gitdir can be relative to the registration with worktree.useRelativePaths enabled. + const gitdir = yield* fileSystem.readFileString(path.join(adminDir, "gitdir")); + const registered = path.dirname(path.resolve(adminDir, gitdir.replace(/\r?\n$/, ""))); + yield* runGit("GitVcsDriver.createWorktree.unlock", cwd, [ + "worktree", + "unlock", + "--", + registered, + ]); + if (remove) yield* removeWorktree({ cwd, path: registered, force: true }); + } + }); + const createWorktree: GitVcsDriver.GitVcsDriver["Service"]["createWorktree"] = Effect.fn( "createWorktree", )(function* (input, options) { @@ -4279,16 +5130,38 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (Buffer.byteLength(prefix + character) > 23) break; prefix += character; } - const directoryName = `${prefix}-${Hex.encode(hash).slice(0, 16)}`; - worktreePath = path.join(parentDir, repoName, directoryName); + const basePath = path.join(parentDir, repoName, `${prefix}-${Hex.encode(hash).slice(0, 16)}`); + // The name is stable per branch, so a folder left by an earlier worktree must not block it. + worktreePath = basePath; + for ( + let suffix = 2; + yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => false)); + suffix++ + ) { + worktreePath = `${basePath}-${suffix}`; + } } const newRefName = input.newRefName; + // Older Git still creates worktrees normally, but cannot prove ownership for cancellation. + const addHelp = newRefName + ? yield* executeGit( + "GitVcsDriver.createWorktree.capabilities", + input.cwd, + ["worktree", "add", "-h"], + { allowNonZeroExit: true }, + ) + : null; + const lockReason = + addHelp && `${addHelp.stdout}\n${addHelp.stderr}`.includes("--reason") + ? `t3-create-${yield* random.uuidV4()}` + : undefined; + if (newRefName) { // Kept apart from the checkout so the shared-config lock only covers the tracking write. yield* createBranchAt( "GitVcsDriver.createWorktree.createBranch", { cwd: input.cwd, branch: newRefName, startPoint: input.refName }, - "git worktree add failed", + "git branch failed", ); } const checkoutRef = newRefName ?? input.refName; @@ -4316,6 +5189,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* `checkout.workers=${checkoutWorkers}`, "worktree", "add", + ...(lockReason ? ["--lock", "--reason", lockReason] : []), "--", worktreePath, checkoutRef, @@ -4325,6 +5199,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // Large checkouts and post-checkout hooks can legitimately run for many // minutes; a fixed deadline kills them and leaves an orphaned worktree. timeoutMs: null, + // Hooks and filter drivers may print without bound; only progress lines are read. + appendTruncationMarker: true, + keepLineCallbacksAfterTruncation: true, ...(onCheckoutProgress ? { // Git only prints checkout progress when stderr is a tty or the @@ -4340,30 +5217,66 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : {}), }, ); + // Set inside the claim's uninterruptible region: a pending cancel still surfaces as it ends. + let claimed = false; + const onWorktreeClaimed = progress?.onWorktreeClaimed; yield* ( fastCheckout ? checkoutCache - .create({ cwd: input.cwd, worktreePath, refName: checkoutRef, checkoutWorkers }) + .create({ + cwd: input.cwd, + worktreePath, + refName: checkoutRef, + checkoutWorkers, + lockReason, + }) .pipe(Effect.flatMap((cloned) => (cloned ? Effect.void : stockCheckout))) : stockCheckout ).pipe( - Effect.onError(() => - newRefName - ? deleteLocalBranch({ cwd: input.cwd, refName: newRefName, force: true }).pipe( + Effect.andThen( + fastCheckout ? checkoutCache.schedule(worktreePath, cacheGeneration) : Effect.void, + ), + Effect.andThen( + onWorktreeClaimed + ? Effect.uninterruptible( + onWorktreeClaimed(worktreePath).pipe( + Effect.andThen( + Effect.sync(() => { + claimed = true; + }), + ), + ), + ) + : Effect.void, + ), + Effect.onError((cause) => + newRefName && !claimed + ? // A failed hook keeps its worktree, as Git does; only a cancel abandons it. + (Cause.hasInterrupts(cause) + ? lockReason + ? releaseWorktreeRegistration(input.cwd, lockReason, true) + : Effect.void + : Effect.void + ).pipe( + Effect.andThen( + deleteLocalBranch({ cwd: input.cwd, refName: newRefName, force: true }), + ), Effect.catch((cause) => - Effect.logWarning("could not remove the branch of a failed worktree", { cause }), + Effect.logWarning("could not clean up a failed worktree or its branch", { cause }), + ), + ) + : Effect.void, + ), + Effect.onExit(() => + lockReason + ? releaseWorktreeRegistration(input.cwd, lockReason, false).pipe( + Effect.catch((cause) => + Effect.logWarning("could not unlock a created worktree", { cause }), ), ) : Effect.void, ), ); - if (fastCheckout) { - yield* checkoutCache.schedule(worktreePath, cacheGeneration); - } - - if (progress?.onWorktreeClaimed) { - yield* progress.onWorktreeClaimed(worktreePath); - } // worktree add leaves submodules empty, potentially omitting project skills, tools or source. const hasSubmodules = yield* fileSystem @@ -4398,6 +5311,61 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* progress.onSubmodulesStarted(); } const onSubmoduleLine = progress?.onSubmoduleLine; + const updateSubmodules = (paths: readonly string[]) => + runGit( + "GitVcsDriver.createWorktree.updateSubmodules", + worktreePath, + [ + "submodule", + "update", + "--init", + ...(submoduleMode.value === "recursive" ? ["--recursive"] : []), + // Git reports transfer progress to a pipe only when forced. + ...(onSubmoduleLine ? ["--progress"] : []), + // A clone left by a failed update already has HEAD at the gitlink, so Git would skip it. + ...(paths.length > 0 ? ["--force", "--", ...paths] : []), + ], + { + // Cloning scales with remote size; let it finish or be cancelled, like worktree add. + timeoutMs: null, + ...(onSubmoduleLine + ? { + env: { LANGUAGE: "C" }, + progress: { onStdoutLine: onSubmoduleLine, onStderrLine: onSubmoduleLine }, + // Progress for many submodules can pass the output cap; truncate instead of failing. + appendTruncationMarker: true, + keepLineCallbacksAfterTruncation: true, + } + : {}), + }, + ); + // One failed clone stops Git before it checks out any submodule, leaving the cloned ones + // as empty working trees that read as modified; check those out on their own. + const checkOutClonedSubmodules = Effect.gen(function* () { + // Records are "submodule..path\n". + const submodulePaths = splitNullSeparatedPaths( + yield* runGitStdout("GitVcsDriver.createWorktree.listSubmodules", worktreePath, [ + "config", + "-z", + "--file", + ".gitmodules", + "--get-regexp", + "^submodule\\..*\\.path$", + ]), + false, + ).flatMap((record) => { + const newline = record.indexOf("\n"); + return newline === -1 ? [] : [record.slice(newline + 1)]; + }); + const clonedPaths = yield* Effect.filter(submodulePaths, (submodulePath) => + fileSystem + .exists(path.join(worktreePath, submodulePath, ".git")) + .pipe(Effect.orElseSucceed(() => false)), + ); + if (clonedPaths.length > 0) { + yield* updateSubmodules(clonedPaths); + } + }); // Registering submodule URLs writes the shared config; the clones that follow do not. yield* runGit( "GitVcsDriver.createWorktree.initSubmodules", @@ -4405,31 +5373,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["submodule", "init"], { writesSharedConfig: true }, ).pipe( - Effect.andThen( - runGit( - "GitVcsDriver.createWorktree.updateSubmodules", - worktreePath, - submoduleMode.value === "recursive" - ? ["submodule", "update", "--init", "--recursive"] - : ["submodule", "update", "--init"], - { - // Cloning scales with remote size; let it finish or be cancelled, like worktree add. - timeoutMs: null, - ...(onSubmoduleLine - ? { - env: { LANGUAGE: "C" }, - progress: { onStdoutLine: onSubmoduleLine, onStderrLine: onSubmoduleLine }, - } - : {}), - }, - ), - ), + Effect.andThen(updateSubmodules([])), Effect.matchEffect({ onFailure: (cause) => Effect.logWarning("worktree submodule checkout failed; submodules may be incomplete", { worktreePath, cause, }).pipe( + Effect.andThen( + checkOutClonedSubmodules.pipe( + Effect.catch((retryCause) => + Effect.logWarning("could not check out the submodules that did clone", { + worktreePath, + cause: retryCause, + }), + ), + ), + ), Effect.andThen( progress?.onSubmodulesFinished ? progress.onSubmodulesFinished({ ok: false, detail: cause.message }) @@ -4444,6 +5404,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); } + // Before the worktree is returned: a refresh holds index.lock, so running it in the + // background would race the setup script's and the agent's own git commands. + yield* refreshNewWorktreeIndex(worktreePath).pipe( + Effect.catch((cause) => + Effect.logWarning( + "worktree index refresh failed; Git keeps re-reading its files until the index is rewritten", + { worktreePath, cause }, + ), + ), + ); + if (newRefName && base) { yield* Effect.gen(function* () { yield* writeConfigValue({ @@ -4571,7 +5542,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? ["merge", "--ff-only", input.targetCommit] : ["reset", "--merge", input.targetCommit], { - timeoutMs: 30_000, + // Killing a slow checkout partway through strands a half-updated working tree. + timeoutMs: null, fallbackErrorDetail: "git failed to move the checkout onto the pull request head", }, ); @@ -4584,6 +5556,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const options = { env: STATUS_UPSTREAM_REFRESH_ENV, fallbackErrorDetail: `git fetch ${input.remoteName} failed`, + timeoutMs: FETCH_REMOTE_TIMEOUT_MS, }; // Another fetch in the same repository, such as the background status // poll, can win the race for a remote-tracking ref. The loser fails, but @@ -4709,7 +5682,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* remoteName: "origin", branchName: input.refName, }; - return remoteNames.includes(remoteName) ? { remoteName, branchName } : null; + // `/HEAD` is the remote's default-branch pointer, not a branch it can serve, and + // a revision expression such as `HEAD~1`, `@{-1}` or `:/text` is no branch name at all. + return remoteNames.includes(remoteName) && + branchName !== "HEAD" && + !branchName.startsWith("-") && + !/[\x00-\x20\x7f~^:?*[\\]|\.\.|@\{/.test(branchName) + ? { remoteName, branchName } + : null; }); const fetchWorktreeBaseCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchWorktreeBaseCommit"] = @@ -4772,19 +5752,51 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ]); }); - const setBranchUpstream: GitVcsDriver.GitVcsDriver["Service"]["setBranchUpstream"] = (input) => - executeGitWithStableDiagnostics( - "GitVcsDriver.setBranchUpstream", - input.cwd, - [ + const setBranchUpstream: GitVcsDriver.GitVcsDriver["Service"]["setBranchUpstream"] = Effect.fn( + "setBranchUpstream", + )( + function* (input) { + const args = [ "branch", "--set-upstream-to", - `${input.remoteName}/${input.remoteBranch}`, + `refs/remotes/${input.remoteName}/${input.remoteBranch}`, "--", input.branch, - ], - { writesSharedConfig: true }, - ).pipe(retryWhileConfigLocked, Effect.asVoid); + ]; + const result = yield* executeGitWithStableDiagnostics( + "GitVcsDriver.setBranchUpstream", + input.cwd, + args, + { allowNonZeroExit: true }, + ); + if (result.exitCode === 0) return; + // Git requires a configured fetch mapping even when the tracking ref already exists. The + // mapping is a glob because an exact source fails every later fetch once the branch is deleted. + if ( + /^fatal: cannot set up tracking information; starting point '.+' is not a branch$/m.test( + result.stderr, + ) + ) { + yield* executeGitWithStableDiagnostics( + "GitVcsDriver.setBranchUpstream.addFetchMapping", + input.cwd, + [ + "config", + "--add", + `remote.${input.remoteName}.fetch`, + `+refs/heads/${input.remoteBranch}*:refs/remotes/${input.remoteName}/${input.remoteBranch}*`, + ], + ).pipe(retryWhileConfigLocked); + } + yield* executeGitWithStableDiagnostics( + "GitVcsDriver.setBranchUpstream", + input.cwd, + args, + ).pipe(retryWhileConfigLocked); + }, + // Keep mapping detection and both writes under the same lock across sibling worktrees. + (effect, input) => withSharedConfigLock(input.cwd, effect), + ); /** * Unlinks links under `target` without following them and removes the @@ -4905,22 +5917,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (input.oldBranch === input.newBranch) { return { branch: input.newBranch }; } - const targetBranch = input.exactName - ? input.newBranch - : yield* resolveAvailableBranchName(input.cwd, input.newBranch); - - yield* executeGit( - "GitVcsDriver.renameBranch", + // Parallel launches often generate the same name; picking it under the lock that serializes + // the renames keeps a second launch from choosing a name the first is about to take. + return yield* withSharedConfigLock( input.cwd, - ["branch", "-m", "--", input.oldBranch, targetBranch], - { - timeoutMs: 10_000, - fallbackErrorDetail: "git branch rename failed", - writesSharedConfig: true, - }, - ); + Effect.gen(function* () { + const targetBranch = input.exactName + ? input.newBranch + : yield* resolveAvailableBranchName(input.cwd, input.newBranch); + + yield* executeGit( + "GitVcsDriver.renameBranch", + input.cwd, + ["branch", "-m", "--", input.oldBranch, targetBranch], + { + timeoutMs: 10_000, + fallbackErrorDetail: "git branch rename failed", + }, + ); - return { branch: targetBranch }; + return { branch: targetBranch }; + }), + ); }); const switchRef: GitVcsDriver.GitVcsDriver["Service"]["switchRef"] = Effect.fn("switchRef")( @@ -4954,7 +5972,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? yield* executeGit( "GitVcsDriver.switchRef.localTrackingBranch", input.cwd, - ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], + // `:short` prefixes a name a tag shares with `heads/`, so names are unambiguous here. + ["for-each-ref", "--format=%(refname:lstrip=2)\t%(upstream)", "refs/heads"], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -4962,7 +5981,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ).pipe( Effect.map((result) => result.exitCode === 0 - ? parseTrackingBranchByUpstreamRef(result.stdout, input.refName) + ? parseTrackingBranchByUpstreamRef(result.stdout, `refs/remotes/${input.refName}`) : null, ), ) @@ -4982,10 +6001,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ).pipe(Effect.map((result) => result.exitCode === 0)) : false; + const newTrackingBranch = + !localInputExists && remoteExists && !localTrackingBranch && !localTrackedBranchTargetExists + ? localTrackedBranchCandidate + : null; + const checkoutArgs = localInputExists ? ["checkout", input.refName] - : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists - ? ["checkout", input.refName] + : newTrackingBranch + ? ["checkout", newTrackingBranch] : remoteExists && !localTrackingBranch ? ["checkout", "--track", input.refName] : remoteExists && localTrackingBranch @@ -4994,16 +6018,46 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* refuseOptionLikeRefName("GitVcsDriver.switchRef", input.cwd, checkoutArgs.at(-1)); + // Created before the checkout so the shared-config lock is not held while files are written. + // Not rolled back on failure: Git may already have switched HEAD to it (post-checkout hooks). + if (newTrackingBranch) { + const startRef = `refs/remotes/${input.refName}`; + yield* executeGitWithStableDiagnostics( + "GitVcsDriver.switchRef.createTrackingBranch", + input.cwd, + ["branch", "--no-track", "--", newTrackingBranch, startRef], + { fallbackErrorDetail: "git branch create failed" }, + ); + // An untracked branch of this name would make every later switch to the remote detach. + yield* executeGitWithStableDiagnostics( + "GitVcsDriver.switchRef.trackRemote", + input.cwd, + ["branch", `--set-upstream-to=${startRef}`, "--", newTrackingBranch], + { writesSharedConfig: true }, + ).pipe( + retryWhileConfigLocked, + Effect.tapError(() => + executeGit( + "GitVcsDriver.switchRef.removeUntrackedBranch", + input.cwd, + ["update-ref", "-d", `refs/heads/${newTrackingBranch}`, startRef], + { allowNonZeroExit: true }, + ), + ), + ); + } + // A stale ref must not turn into a path checkout that discards local edits. yield* executeGitWithStableDiagnostics( "GitVcsDriver.switchRef.checkout", input.cwd, [...checkoutArgs, "--"], { - timeoutMs: 10_000, + // Killing a checkout midway (large or LFS repos) leaves a half-updated working tree. + timeoutMs: null, fallbackErrorDetail: "git checkout failed", - // Checking out a remote branch creates a local one that tracks it. - writesSharedConfig: !localInputExists, + // Creating a branch writes its upstream; Git also guesses a remote branch for a missing name. + writesSharedConfig: checkoutArgs[1] === "--track" || (!localInputExists && !remoteExists), }, ); @@ -5126,6 +6180,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* statusDetails, statusDetailsLocal, statusDetailsRemote, + readRefSnapshot, prepareCommitContext, commit: Effect.fnUntraced(function* (cwd, subject, body, options) { return yield* withListRefsInvalidation(cwd, commit(cwd, subject, body, options)); @@ -5215,6 +6270,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* withListRefsInvalidation(input.cwd, switchRef(input)); }), initRepo: initRepoWithListRefsInvalidation, + invalidateRefs: Effect.fn("GitVcsDriver.invalidateRefs")(function* (cwd) { + // First, so a cached "not a repository" cannot end the ref invalidation early. + const cacheKey = normalizeRepositoryPathsCacheKey(cwd); + yield* Cache.invalidate(repositoryPathsRefreshCache, cacheKey); + yield* Cache.invalidate(repositoryPathsCache, cacheKey); + return yield* withListRefsInvalidation(cwd, Effect.void); + }), listLocalBranchNames, listWorktreePaths, }); diff --git a/apps/server/src/vcs/VcsAutomaticFetchInterval.ts b/apps/server/src/vcs/VcsAutomaticFetchInterval.ts new file mode 100644 index 0000000000..0f2c900b3b --- /dev/null +++ b/apps/server/src/vcs/VcsAutomaticFetchInterval.ts @@ -0,0 +1,26 @@ +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL } from "@t3tools/contracts"; +import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; + +import * as ServerSettings from "../serverSettings.ts"; + +export class VcsAutomaticFetchInterval extends Context.Reference>( + "t3/vcs/VcsAutomaticFetchInterval", + { defaultValue: () => Effect.succeed(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) }, +) {} + +export const layer = Layer.effect( + VcsAutomaticFetchInterval, + Effect.gen(function* () { + const serverSettings = yield* ServerSettings.ServerSettingsService; + return serverSettings.getSettings.pipe( + Effect.map( + (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval, + ), + Effect.orElseSucceed(() => DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL), + ); + }), +); diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index b382922c5a..383db43025 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -14,6 +14,8 @@ import * as VcsProcess from "./VcsProcess.ts"; export interface VcsCaptureCheckpointInput { readonly cwd: string; readonly checkpointRef: CheckpointRef; + /** The checkpoint this one follows, so a turn that switched branches starts where it landed. */ + readonly previousCheckpointRef?: CheckpointRef; } export interface VcsRestoreCheckpointInput { diff --git a/apps/server/src/vcs/VcsDriverRegistry.test.ts b/apps/server/src/vcs/VcsDriverRegistry.test.ts index c13d44f2d8..6fee790bc4 100644 --- a/apps/server/src/vcs/VcsDriverRegistry.test.ts +++ b/apps/server/src/vcs/VcsDriverRegistry.test.ts @@ -6,6 +6,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import { ChildProcessSpawner } from "effect/process"; +import { VcsProcessExitError } from "@t3tools/contracts"; import * as VcsProcess from "./VcsProcess.ts"; import * as VcsProjectConfig from "./VcsProjectConfig.ts"; @@ -128,4 +129,53 @@ describe("VcsDriverRegistry", () => { }).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls))); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + const makeFailingLayer = (detectOutput: VcsProcess.VcsProcessOutput) => + Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + Layer.provide( + Layer.mock(VcsProjectConfig.VcsProjectConfig)({ + resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"), + }), + ), + Layer.provide( + Layer.mock(VcsProcess.VcsProcess)({ + run: (input) => + normalizeGitArgs(input.args).join(" ") === DETECT_COMMAND + ? Effect.succeed(detectOutput) + : Effect.fail( + new VcsProcessExitError({ + operation: input.operation, + command: "git", + cwd: input.cwd, + exitCode: 128, + detail: "fatal: bad config line 1 in file .git/config", + }), + ), + }), + ), + ); + + it.effect("reads only a failed work-tree probe as no repository", () => + Effect.gen(function* () { + const probeFailure = yield* VcsDriverRegistry.VcsDriverRegistry.pipe( + Effect.flatMap((registry) => registry.detect({ cwd: "/repo" })), + Effect.provide( + makeFailingLayer({ + ...processOutput(""), + exitCode: ChildProcessSpawner.ExitCode(128), + stderr: "fatal: bad config line 1 in file .git/config", + }), + ), + ); + assert.equal(probeFailure, null); + + // A newline in the root path makes detection ask for it again, and main surfaced that failure. + const fallbackFailure = yield* VcsDriverRegistry.VcsDriverRegistry.pipe( + Effect.flatMap((registry) => registry.detect({ cwd: "/repo" })), + Effect.provide(makeFailingLayer(processOutput("true\n/re\npo\n.git\n"))), + Effect.flip, + ); + assert.equal(fallbackFailure._tag, "VcsProcessExitError"); + }), + ); }); diff --git a/apps/server/src/vcs/VcsDriverRegistry.ts b/apps/server/src/vcs/VcsDriverRegistry.ts index d42cae5cc3..5bf7263ebe 100644 --- a/apps/server/src/vcs/VcsDriverRegistry.ts +++ b/apps/server/src/vcs/VcsDriverRegistry.ts @@ -85,7 +85,16 @@ export const make = Effect.gen(function* () { driver: VcsDriver.VcsDriver["Service"], cwd: string, ) { - const repository = yield* driver.detectRepository(cwd); + // Status, review and source control show a repository Git cannot read as none at all. + // Checkpoints need the failure, so CheckpointStore asks the driver directly. + const repository = yield* driver.detectRepository(cwd).pipe( + Effect.catchTags({ + VcsProcessExitError: (error) => + error.operation === GitVcsDriver.WORK_TREE_PROBE_OPERATION + ? Effect.succeed(null) + : Effect.fail(error), + }), + ); if (!repository) { return null; } diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.ts index b87dbf5e78..18eaebe6e0 100644 --- a/apps/server/src/vcs/VcsProcess.test.ts +++ b/apps/server/src/vcs/VcsProcess.test.ts @@ -92,7 +92,7 @@ describe("VcsProcess.run", () => { yield* fs.remove(lock); yield* git(restore); expect(yield* fs.readFileString(file)).toBe("before\n"); - }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(provideLive, Effect.provide(NodeServices.layer)), ); it.effect.each([ diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts index c379caf488..da2f988ce1 100644 --- a/apps/server/src/vcs/VcsProcess.ts +++ b/apps/server/src/vcs/VcsProcess.ts @@ -33,6 +33,7 @@ export interface VcsProcessInput { readonly spawnCwd?: string; readonly stdin?: string; readonly onStdoutChunk?: (chunk: Uint8Array) => void; + readonly onSpawn?: () => void; readonly env?: NodeJS.ProcessEnv; readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number; @@ -134,6 +135,29 @@ export const gitConfigEnv = ( export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => gitConfigEnv(env, "safe.bareRepository", "explicit", platform); +const REPOSITORY_SELECTORS = new Set([ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_COMMON_DIR", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", +]); + +/** + * Unsets repository selectors the server inherited, such as a Git hook's `GIT_DIR`, so Git finds + * the repository from cwd. Spread it before a command's own env, which may still set them. + */ +export const unsetInheritedRepositoryEnv = ( + inherited: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): NodeJS.ProcessEnv => + Object.fromEntries( + Object.keys(inherited) + .filter((name) => REPOSITORY_SELECTORS.has(platform === "win32" ? name.toUpperCase() : name)) + .map((name) => [name, undefined]), + ); + const classifyNonZeroExit = ( stderr: string, classifyFailure: VcsProcessInput["classifyFailure"], @@ -209,7 +233,11 @@ export const make = Effect.gen(function* () { ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}), ...(input.stdin !== undefined ? { stdin: input.stdin } : {}), ...(input.onStdoutChunk !== undefined ? { onStdoutChunk: input.onStdoutChunk } : {}), + ...(input.onSpawn !== undefined ? { onSpawn: input.onSpawn } : {}), env: { + ...(input.command === "git" + ? unsetInheritedRepositoryEnv(process.env, hostPlatform) + : {}), // Failures are read by English patterns; without LANG, macOS Git follows the system language. // LANGUAGE leaves LC_CTYPE, which hooks inherit, alone. ...(input.command === "git" ? { LANGUAGE: "C" } : {}), diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index ec4d4942d8..08fad4ae56 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -19,12 +19,16 @@ import * as TestClock from "effect/testing/TestClock"; import * as Tracer from "effect/Tracer"; import type { BackgroundScope, + VcsBranchStatus, VcsStatusLocalResult, VcsStatusRemoteResult, + VcsStatusResult, VcsStatusStreamEvent, } from "@t3tools/contracts"; import { GitCommandError, GitManagerError } from "@t3tools/contracts"; +import { applyGitStatusStreamEvent } from "@t3tools/shared/git"; +import * as VcsAutomaticFetchInterval from "./VcsAutomaticFetchInterval.ts"; import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; @@ -68,50 +72,87 @@ const remoteStatusWithPr: VcsStatusRemoteResult = { function layerTestFor(state: { currentLocalStatus: VcsStatusLocalResult; currentRemoteStatus: VcsStatusRemoteResult | null; + currentDivergence?: Pick; localStatusCalls: number; remoteStatusCalls: number; localInvalidationCalls: number; remoteInvalidationCalls: number; remoteStatusRefreshUpstreamValues?: Array; + localStatusBranchChanges?: Array; + refSnapshot?: string | null; remoteStatusError?: GitManagerError; backgroundWorkEnabled?: boolean; automaticFetchInterval?: Effect.Effect; - beforeRemoteStatus?: Effect.Effect; + beforeRemoteStatus?: Effect.Effect; beforeLocalStatus?: Effect.Effect; beforeCurrentBranch?: Effect.Effect; beforeInvalidate?: Effect.Effect; branchRead?: () => Effect.Effect; fileSystem?: FileSystem.FileSystem; pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"]; + headPath?: string; + headPathCalls?: number; + failLocalStatus?: boolean; + onLocalStatusFailure?: Effect.Effect; }) { return VcsStatusBroadcaster.layer.pipe( Layer.provideMerge( state.fileSystem - ? Layer.succeed(FileSystem.FileSystem, state.fileSystem) + ? Layer.merge(Layer.succeed(FileSystem.FileSystem, state.fileSystem), Path.layer) : NodeServices.layer, ), Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)), Layer.provide( Layer.succeed( - VcsStatusBroadcaster.VcsAutomaticFetchInterval, + VcsAutomaticFetchInterval.VcsAutomaticFetchInterval, state.automaticFetchInterval ?? Effect.succeed(Duration.seconds(30)), ), ), Layer.provide( Layer.mock(GitWorkflowService.GitWorkflowService)({ - localStatus: () => + localStatus: (_input, options) => Effect.suspend(() => { state.localStatusCalls += 1; + const includeBranchChanges = options?.includeBranchChanges !== false; + state.localStatusBranchChanges?.push(includeBranchChanges); + const { branchChanges: _branchChanges, ...withoutBranchChanges } = + state.currentLocalStatus; + if (state.failLocalStatus) { + return (state.onLocalStatusFailure ?? Effect.void).pipe( + Effect.andThen( + Effect.fail( + new GitManagerError({ + operation: "VcsStatusBroadcaster.test", + cwd: "/repo", + detail: "index.lock is held", + }), + ), + ), + ); + } return (state.beforeLocalStatus ?? Effect.void).pipe( - Effect.as(state.currentLocalStatus), + Effect.as(includeBranchChanges ? state.currentLocalStatus : withoutBranchChanges), ); }), + repositoryRoot: () => Effect.sync(() => (state.currentLocalStatus.isRepo ? "/repo" : null)), currentBranch: () => state.branchRead ? state.branchRead() : (state.beforeCurrentBranch ?? Effect.void).pipe( Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), ), + readRefSnapshot: () => + Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), + upstreamDivergence: () => + Effect.sync(() => + state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null + ? { + refName: state.currentLocalStatus.refName, + aheadCount: (state.currentDivergence ?? state.currentRemoteStatus).aheadCount, + behindCount: (state.currentDivergence ?? state.currentRemoteStatus).behindCount, + } + : null, + ), remoteStatus: (_input, options) => Effect.suspend(() => { return (state.beforeRemoteStatus ?? Effect.void).pipe( @@ -141,6 +182,11 @@ function layerTestFor(state: { state.remoteInvalidationCalls += 1; }), ...(state.pullCurrentBranch ? { pullCurrentBranch: state.pullCurrentBranch } : {}), + headPath: () => + Effect.sync(() => { + state.headPathCalls = (state.headPathCalls ?? 0) + 1; + return state.headPath ?? null; + }), }), ), ); @@ -213,7 +259,7 @@ describe("VcsStatusBroadcaster", () => { yield* broadcaster.refreshLocalStatus("/repo"); assert.strictEqual(state.localStatusCalls, 3); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect( @@ -233,14 +279,17 @@ describe("VcsStatusBroadcaster", () => { return Effect.gen(function* () { const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" })); - assert.deepEqual(yield* branches, [{ refName: baseLocalStatus.refName }]); + assert.deepEqual(yield* branches, [{ refName: baseLocalStatus.refName, isRepo: true }]); assert.equal(state.localStatusCalls, 0); state.currentLocalStatus = { ...baseLocalStatus, refName: "external" }; yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); - assert.deepEqual(yield* branches, [{ refName: "external" }]); + assert.deepEqual(yield* branches, [{ refName: "external", isRepo: true }]); state.currentLocalStatus = { ...baseLocalStatus, refName: null }; yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); - assert.deepEqual(yield* branches, [{ refName: null }]); + assert.deepEqual(yield* branches, [{ refName: null, isRepo: true }]); + state.currentLocalStatus = { ...baseLocalStatus, isRepo: false, refName: null }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual(yield* branches, [{ refName: null, isRepo: false }]); assert.equal(state.localStatusCalls, 0); const detailScope = yield* Scope.make(); const details = yield* Stream.toPull( @@ -265,7 +314,7 @@ describe("VcsStatusBroadcaster", () => { assert.deepEqual(yield* details, [ { _tag: "localUpdated", local: state.currentLocalStatus }, ]); - assert.deepEqual(yield* branches, [{ refName: "changed" }]); + assert.deepEqual(yield* branches, [{ refName: "changed", isRepo: true }]); const secondScope = yield* Scope.make(); const secondDetails = yield* Stream.toPull( broadcaster.streamStatus({ cwd: "/alias", includeRemote: false }), @@ -303,12 +352,86 @@ describe("VcsStatusBroadcaster", () => { assert.deepEqual(yield* reopened, [ { _tag: "localUpdated", local: state.currentLocalStatus }, ]); - assert.deepEqual(yield* branches, [{ refName: null }]); + assert.deepEqual(yield* branches, [{ refName: null, isRepo: false }]); assert.equal(state.remoteStatusCalls, 0); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }, ); + it.effect("publishes the new branch before pending detailed status completes", () => { + const state = newState(); + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" })); + yield* branches; + const reading = yield* Deferred.make(); + const resume = yield* Deferred.make(); + state.beforeLocalStatus = Deferred.succeed(reading, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + ); + const details = yield* Stream.runHead( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + ).pipe(Effect.forkScoped); + yield* Deferred.await(reading); + state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" }; + const update = yield* branches.pipe(Effect.forkScoped({ startImmediately: true })); + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual( + update.pollUnsafe(), + Exit.succeed([{ refName: "feature/next", isRepo: true }]), + ); + state.beforeLocalStatus = Effect.void; + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(details); + yield* broadcaster.getStatus({ cwd: "/repo" }); + state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/latest" }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual(yield* branches, [{ refName: "feature/latest", isRepo: true }]); + }).pipe(Effect.provide(layerTestFor(state))); + }); + + it.effect("invalidates totals for a refresh arriving after detailed demand closes", () => { + const state = newState(); + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const detailScope = yield* Scope.make(); + const details = yield* Stream.toPull( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + ).pipe(Scope.provide(detailScope)); + yield* details; + const reading = yield* Deferred.make(); + const resume = yield* Deferred.make(); + state.currentLocalStatus = { + ...baseLocalStatus, + refName: "feature/next", + workingTree: { files: [], insertions: 1, deletions: 0 }, + }; + state.beforeLocalStatus = Deferred.succeed(reading, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + ); + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + yield* Deferred.await(reading); + yield* Scope.close(detailScope, Exit.void); + state.currentLocalStatus = { + ...state.currentLocalStatus, + workingTree: { files: [], insertions: 2, deletions: 0 }, + }; + const trailing = yield* broadcaster + .refreshBranchStatus({ cwd: "/repo" }) + .pipe(Effect.forkScoped({ startImmediately: true })); + state.beforeLocalStatus = Effect.void; + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(trailing); + const reopened = yield* Stream.runHead( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + ); + assert.deepEqual( + reopened, + Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }), + ); + }).pipe(Effect.provide(layerTestFor(state))); + }); + it.effect("upgrades an in-flight branch refresh when detailed demand arrives", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, @@ -342,7 +465,7 @@ describe("VcsStatusBroadcaster", () => { yield* Fiber.join(detailsFiber), Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }), ); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("publishes terminal branch switches and validates cached status reads", () => { @@ -499,6 +622,48 @@ describe("VcsStatusBroadcaster", () => { }, ); + it.effect.each([0, 2])( + "refreshes merge divergence while a lookup ends with %s commits behind", + (behindAfterLookup) => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: { ...baseRemoteStatus, aheadCount: 2, behindCount: 3 }, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + backgroundWorkEnabled: false, + }; + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + ); + const lookup = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped); + yield* Deferred.await(started); + state.currentRemoteStatus = { ...baseRemoteStatus, aheadCount: 4, behindCount: 0 }; + yield* broadcaster.refreshLocalStatus("/repo"); + const status = yield* broadcaster.getStatus({ cwd: "/repo" }); + assert.equal(status.aheadCount, 4); + assert.equal(status.behindCount, 0); + assert.equal(state.remoteStatusCalls, 1); + state.currentDivergence = { aheadCount: 4, behindCount: behindAfterLookup }; + state.currentRemoteStatus = + behindAfterLookup > 0 + ? { ...baseRemoteStatus, ...state.currentDivergence } + : { ...baseRemoteStatus, aheadCount: 2, behindCount: 3 }; + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(lookup); + const afterLookup = yield* broadcaster.getStatus({ cwd: "/repo" }); + assert.equal(afterLookup.aheadCount, 4); + assert.equal(afterLookup.behindCount, behindAfterLookup); + }).pipe(Effect.provide(layerTestFor(state))); + }, + ); + it.effect("a local-only refresh after a branch switch leaves the PR refresh able to read", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, @@ -591,6 +756,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(localStatus), currentBranch: () => Effect.succeed(localStatus.refName), + readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.succeed(remoteStatus), invalidateLocalStatus: () => Effect.void, invalidateRemoteStatus: () => Effect.void, @@ -687,6 +853,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { remoteReads += 1; @@ -718,7 +885,7 @@ describe("VcsStatusBroadcaster", () => { assert.deepStrictEqual(refreshed, remoteStatusWithPr); const final = yield* broadcaster.getStatus({ cwd: "/repo" }); assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr); - }).pipe(Effect.provide(layer), Effect.scoped); + }).pipe(Effect.provide(layer)); }); it.effect("an initial status read cannot overwrite an explicit refresh", () => { @@ -733,6 +900,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { remoteReads += 1; @@ -762,7 +930,7 @@ describe("VcsStatusBroadcaster", () => { (yield* broadcaster.getStatus({ cwd: "/repo" })).pr, remoteStatusWithPr.pr, ); - }).pipe(Effect.provide(layer), Effect.scoped); + }).pipe(Effect.provide(layer)); }); it.effect("keeps the published local snapshot when a refresh remote read fails", () => { @@ -786,6 +954,7 @@ describe("VcsStatusBroadcaster", () => { return state.currentLocalStatus; }), currentBranch: () => Effect.succeed(state.currentLocalStatus.refName), + readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.suspend(() => { state.remoteStatusCalls += 1; @@ -912,6 +1081,49 @@ describe("VcsStatusBroadcaster", () => { }, ); + it.effect("publishes a checkout's branch before returning, ahead of the remote read", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + const subscribed = yield* Deferred.make(); + const localPublished = yield* Deferred.make(); + const remotePublished = yield* Deferred.make(); + yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe( + Stream.runForEach((event) => { + if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined); + if (event._tag === "localUpdated") return Deferred.succeed(localPublished, event.local); + return event.remote === null + ? Effect.void + : Deferred.succeed(remotePublished, event.remote); + }), + Effect.forkScoped, + ); + yield* Deferred.await(subscribed); + + const releaseRemote = yield* Deferred.make(); + state.beforeRemoteStatus = Deferred.await(releaseRemote); + state.currentLocalStatus = { ...baseLocalStatus, refName: "main" }; + state.currentRemoteStatus = remoteStatusWithPr; + yield* broadcaster.refreshAfterCheckout("/repo"); + + assert.equal((yield* Deferred.await(localPublished)).refName, "main"); + assert.isFalse(yield* Deferred.isDone(remotePublished)); + + yield* Deferred.succeed(releaseRemote, undefined); + assert.deepStrictEqual(yield* Deferred.await(remotePublished), remoteStatusWithPr); + assert.equal((yield* broadcaster.getStatus({ cwd: "/repo" })).pr?.number, 2978); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); + it.effect("a remote poll refreshes Changes totals when divergence counts stay the same", () => { const state: Parameters[0] = { currentLocalStatus: { @@ -948,6 +1160,116 @@ describe("VcsStatusBroadcaster", () => { yield* Deferred.await(polled); const status = yield* broadcaster.getStatus({ cwd: "/repo" }); assert.deepStrictEqual(status.branchChanges, state.currentLocalStatus.branchChanges); + }).pipe(Effect.provide(layerTestFor(state))); + }); + + it.effect("reads Changes totals only while a subscriber shows them", () => { + const branchChanges = { baseRef: "origin/main", insertions: 3, deletions: 1 }; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, branchChanges }, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + localStatusBranchChanges: [], + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const paletteEvents = yield* Queue.unbounded(); + yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe( + Stream.runForEach((event) => Queue.offer(paletteEvents, event)), + Effect.forkScoped, + ); + const paletteSnapshot = yield* Queue.take(paletteEvents); + assert.strictEqual(paletteSnapshot._tag, "snapshot"); + if (paletteSnapshot._tag === "snapshot") { + assert.isUndefined(paletteSnapshot.local.branchChanges); + } + yield* broadcaster.refreshLocalStatus("/repo"); + assert.deepStrictEqual(state.localStatusBranchChanges, [false, false]); + + const headerScope = yield* Scope.make(); + const headerEvents = yield* Queue.unbounded(); + yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach((event) => Queue.offer(headerEvents, event)), + Effect.forkIn(headerScope), + ); + const headerSnapshot = yield* Queue.take(headerEvents); + assert.strictEqual(headerSnapshot._tag, "snapshot"); + if (headerSnapshot._tag === "snapshot") { + assert.deepStrictEqual(headerSnapshot.local.branchChanges, branchChanges); + } + const paletteUpdate = yield* Queue.take(paletteEvents); + assert.strictEqual(paletteUpdate._tag, "localUpdated"); + if (paletteUpdate._tag === "localUpdated") { + assert.deepStrictEqual(paletteUpdate.local.branchChanges, branchChanges); + } + // The header's first remote poll also rereads local status. + while ((yield* Queue.take(headerEvents))._tag !== "remoteUpdated") {} + const turnEnd = yield* broadcaster.refreshLocalStatus("/repo"); + assert.deepStrictEqual(turnEnd.branchChanges, branchChanges); + + yield* Scope.close(headerScope, Exit.void); + yield* broadcaster.refreshLocalStatus("/repo"); + assert.deepStrictEqual(state.localStatusBranchChanges, [ + false, + false, + true, + true, + true, + false, + ]); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); + + it.effect("a light refresh that a header joins mid-read publishes Changes totals", () => { + const branchChanges = { baseRef: "origin/main", insertions: 3, deletions: 1 }; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, branchChanges }, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + localStatusBranchChanges: [], + fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }), + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribeHeader = Effect.fn("subscribeHeader")(function* (scope: Scope.Scope) { + const events = yield* Queue.unbounded(); + yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkIn(scope, { startImmediately: true }), + ); + return events; + }); + const firstHeader = yield* Scope.make(); + const firstEvents = yield* subscribeHeader(firstHeader); + while ((yield* Queue.take(firstEvents))._tag !== "remoteUpdated") {} + yield* Scope.close(firstHeader, Exit.void); + + const readStarted = yield* Deferred.make(); + const finishRead = yield* Deferred.make(); + state.beforeLocalStatus = Deferred.succeed(readStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishRead)), + ); + const turnEnd = yield* broadcaster.refreshLocalStatus("/repo").pipe(Effect.forkScoped); + yield* Deferred.await(readStarted); + // Starting immediately registers the header's demand before it waits behind the read. + const secondEvents = yield* subscribeHeader(yield* Scope.make()); + yield* Deferred.succeed(finishRead, undefined); + const snapshot = yield* Queue.take(secondEvents); + assert.strictEqual(snapshot._tag, "snapshot"); + if (snapshot._tag === "snapshot") { + assert.deepStrictEqual(snapshot.local.branchChanges, branchChanges); + } + + assert.deepStrictEqual((yield* Fiber.join(turnEnd)).branchChanges, branchChanges); + assert.deepStrictEqual(state.localStatusBranchChanges?.slice(-2), [false, true]); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); }); @@ -960,6 +1282,7 @@ describe("VcsStatusBroadcaster", () => { branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 }, }; let cachedLocal: VcsStatusLocalResult | undefined; + let refSnapshot = "before"; const readLocalStatus = () => Effect.sync(() => (cachedLocal ??= local)); const layerTest = VcsStatusBroadcaster.layer.pipe( Layer.provideMerge(NodeServices.layer), @@ -977,6 +1300,7 @@ describe("VcsStatusBroadcaster", () => { }), currentBranch: () => Effect.succeed(baseLocalStatus.refName), invalidateRemoteStatus: () => Effect.void, + readRefSnapshot: () => Effect.sync(() => refSnapshot), remoteStatus: () => Deferred.succeed(fetchStarted, undefined).pipe( Effect.andThen(Deferred.await(finishFetch)), @@ -995,6 +1319,7 @@ describe("VcsStatusBroadcaster", () => { ...baseLocalStatus, branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 }, }; + refSnapshot = "after"; yield* Deferred.succeed(finishFetch, undefined); const status = yield* Fiber.join(refresh); assert.deepStrictEqual(status.branchChanges, local.branchChanges); @@ -1002,6 +1327,59 @@ describe("VcsStatusBroadcaster", () => { }); }); + it.effect("an explicit refresh re-reads local totals only after refs moved", () => { + const totals = (insertions: number): VcsStatusLocalResult => ({ + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions, deletions: 0 }, + }); + const state: Parameters[0] = { + currentLocalStatus: totals(745), + currentRemoteStatus: remoteStatusWithPr, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribed = yield* Deferred.make(); + const events = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe( + Stream.tap((event) => + event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void, + ), + Stream.filter((event) => event._tag !== "snapshot"), + Stream.take(4), + Stream.runCollect, + Effect.forkScoped, + ); + yield* Deferred.await(subscribed); + + state.localStatusCalls = 0; + yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 1); + + state.localStatusCalls = 0; + state.currentRemoteStatus = baseRemoteStatus; + state.beforeRemoteStatus = Effect.sync(() => { + state.currentLocalStatus = totals(0); + state.refSnapshot = "moved"; + }); + const moved = yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 2); + assert.deepStrictEqual(moved.branchChanges, totals(0).branchChanges); + assert.deepStrictEqual( + [...(yield* Fiber.join(events))].map((event) => event._tag), + // The first refresh adds the totals this palette-style subscription skipped. + ["localUpdated", "remoteUpdated", "remoteUpdated", "localUpdated"], + ); + + state.localStatusCalls = 0; + state.refSnapshot = null; + yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 2); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); + it.effect("publishes local status while an earlier lookup holds the remote lock", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, @@ -1048,7 +1426,7 @@ describe("VcsStatusBroadcaster", () => { const status = yield* Fiber.join(refresh); assert.isTrue(status.hasWorkingTreeChanges); assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("publishes local changes before a remote error and propagates that error", () => { @@ -1110,7 +1488,7 @@ describe("VcsStatusBroadcaster", () => { assert.isTrue(cached.hasWorkingTreeChanges); assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr); assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)( @@ -1196,7 +1574,7 @@ describe("VcsStatusBroadcaster", () => { assert.isNull(status.pr); assert.equal(status.aheadCount, 0); assert.equal(status.behindCount, 0); - }).pipe(Effect.provide(layerTest), Effect.scoped); + }).pipe(Effect.provide(layerTest)); }, ); @@ -1246,9 +1624,349 @@ describe("VcsStatusBroadcaster", () => { assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr); assert.equal(cached.aheadCount, 2); assert.equal(state.remoteStatusCalls, 2); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); + it.effect("a terminal checkout publishes the new branch without waiting for a poll", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" }); + const headPath = path.join(gitDir, "HEAD"); + yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); + const state = { + currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" }, + currentRemoteStatus: remoteStatusWithPr as VcsStatusRemoteResult | null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + remoteStatusRefreshUpstreamValues: [] as Array, + headPath, + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + const clientStates: Array = []; + const subscribed = yield* Deferred.make(); + const checkedOut = yield* Deferred.make(); + yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => + Effect.gen(function* () { + const next = applyGitStatusStreamEvent(clientStates.at(-1) ?? null, event); + clientStates.push(next); + yield* Deferred.succeed(subscribed, undefined); + // The refresh ends with the new branch's remote, after its local update. + if (event._tag === "remoteUpdated" && event.remote && next.refName === "repro") { + yield* Deferred.succeed(checkedOut, undefined); + } + }), + ).pipe(Effect.forkScoped); + yield* Deferred.await(subscribed); + + // What `git switch -c repro` does to HEAD, with the test clock never advanced. + state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "repro" }; + state.currentRemoteStatus = { ...baseRemoteStatus, hasUpstream: false }; + const lockPath = path.join(gitDir, "HEAD.lock"); + yield* fs.writeFileString(lockPath, "ref: refs/heads/repro\n"); + yield* fs.rename(lockPath, headPath); + yield* Deferred.await(checkedOut); + + assert.deepStrictEqual( + clientStates.filter((status) => status.refName === "repro").map((status) => status.pr), + [null, null], + ); + // A checkout must not trigger a network fetch. + assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues.slice(1), [false]); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("a terminal checkout updates branch-only subscribers without full status", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" }); + const headPath = path.join(gitDir, "HEAD"); + yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); + const state = { + currentLocalStatus: { ...baseLocalStatus, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath, + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" })); + assert.deepEqual(yield* branches, [{ refName: "main", isRepo: true }]); + + state.currentLocalStatus = { ...baseLocalStatus, refName: "repro" }; + const lockPath = path.join(gitDir, "HEAD.lock"); + yield* fs.writeFileString(lockPath, "ref: refs/heads/repro\n"); + yield* fs.rename(lockPath, headPath); + + assert.deepEqual(yield* branches, [{ refName: "repro", isRepo: true }]); + assert.equal(state.localStatusCalls, 0); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("a terminal checkout updates the branch before pending detailed status completes", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" }); + const headPath = path.join(gitDir, "HEAD"); + yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath, + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" })); + yield* branches; + const details = yield* Stream.toPull( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + ); + yield* details; + + const resume = yield* Deferred.make(); + state.beforeLocalStatus = Deferred.await(resume); + state.currentLocalStatus = { ...baseLocalStatus, refName: "repro" }; + const lockPath = path.join(gitDir, "HEAD.lock"); + yield* fs.writeFileString(lockPath, "ref: refs/heads/repro\n"); + yield* fs.rename(lockPath, headPath); + + assert.deepEqual(yield* branches, [{ refName: "repro", isRepo: true }]); + state.currentLocalStatus = { ...baseLocalStatus, refName: "second" }; + yield* fs.writeFileString(lockPath, "ref: refs/heads/second\n"); + yield* fs.rename(lockPath, headPath); + assert.deepEqual(yield* branches, [{ refName: "second", isRepo: true }]); + yield* Deferred.succeed(resume, undefined); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("a checkout read that fails while index.lock is held retries until it succeeds", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const headPath = "/repo/.git/HEAD"; + const failed = yield* Deferred.make(); + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath, + fileSystem: FileSystem.makeNoop({ + realPath: (target) => Effect.succeed(target), + exists: () => Effect.succeed(true), + watch: (_target, options) => + Stream.fromQueue(events).pipe(Stream.onStart(Effect.sync(() => options?.onReady?.()))), + }), + failLocalStatus: false, + onLocalStatusFailure: Deferred.succeed(failed, undefined).pipe(Effect.asVoid), + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribed = yield* Deferred.make(); + const checkedOut = yield* Deferred.make(); + let clientState: VcsStatusResult | null = null; + yield* Stream.runForEach( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + (event) => + Effect.gen(function* () { + clientState = applyGitStatusStreamEvent(clientState, event); + yield* Deferred.succeed(subscribed, undefined); + if (clientState.refName === "repro") yield* Deferred.succeed(checkedOut, undefined); + }), + ).pipe(Effect.forkScoped); + yield* Deferred.await(subscribed); + + // A terminal commit holds index.lock across the checkout, so the HEAD event's read fails. + state.failLocalStatus = true; + state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "repro" }; + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); + yield* Deferred.await(failed); + const failedCalls = state.localStatusCalls; + + // Removing index.lock moves no HEAD, and no remote poll runs for this subscriber. + state.failLocalStatus = false; + yield* TestClock.adjust(Duration.seconds(30)); + yield* Deferred.await(checkedOut); + assert.strictEqual(state.localStatusCalls, failedCalls + 1); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }), + ); + + it.effect("subscribers share one HEAD watch that ends with the last of them", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" }); + const headPath = path.join(gitDir, "HEAD"); + yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus as VcsStatusRemoteResult | null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath, + headPathCalls: 0, + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribe = Effect.gen(function* () { + const received = yield* Deferred.make(); + const fiber = yield* Stream.runForEach( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + () => Deferred.succeed(received, undefined), + ).pipe(Effect.forkScoped); + yield* Deferred.await(received); + return fiber; + }); + + const first = yield* subscribe; + const second = yield* subscribe; + assert.strictEqual(state.headPathCalls, 1); + + yield* Fiber.interrupt(first); + yield* Fiber.interrupt(second); + yield* subscribe; + assert.strictEqual(state.headPathCalls, 2); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("a HEAD watch that ended restarts for the next subscriber and keeps earlier ones", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" }); + const headPath = path.join(gitDir, "HEAD"); + yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPathCalls: 0, + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribe = Effect.gen(function* () { + const subscribed = yield* Deferred.make(); + const refs = new Map>(); + const sawRef = (refName: string) => { + const existing = refs.get(refName); + if (existing) return existing; + const created = Deferred.makeUnsafe(); + refs.set(refName, created); + return created; + }; + let clientState: VcsStatusResult | null = null; + const fiber = yield* Stream.runForEach( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + (event) => + Effect.gen(function* () { + clientState = applyGitStatusStreamEvent(clientState, event); + yield* Deferred.succeed(subscribed, undefined); + yield* Deferred.succeed(sawRef(clientState.refName ?? ""), undefined); + }), + ).pipe(Effect.forkScoped); + yield* Deferred.await(subscribed); + return { fiber, sawRef }; + }); + const checkout = (refName: string) => + Effect.gen(function* () { + state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName }; + const lockPath = path.join(gitDir, "HEAD.lock"); + yield* fs.writeFileString(lockPath, `ref: refs/heads/${refName}\n`); + yield* fs.rename(lockPath, headPath); + }); + + // The repository has no HEAD yet, so the first watch ends at once. + const first = yield* subscribe; + state.headPath = headPath; + const second = yield* subscribe; + assert.strictEqual(state.headPathCalls, 2); + + yield* checkout("one"); + yield* Deferred.await(first.sawRef("one")); + yield* Deferred.await(second.sawRef("one")); + + // The replacement belongs to both subscribers, so the second leaving keeps it. + yield* Fiber.interrupt(second.fiber); + yield* checkout("two"); + yield* Deferred.await(first.sawRef("two")); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("a HEAD watch ends when its git directory is removed", () => + Effect.gen(function* () { + const gitDir = "/repo/.git/worktrees/feature"; + const events = yield* Queue.unbounded(); + const closed = yield* Deferred.make(); + let gitDirExists = true; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath: `${gitDir}/HEAD`, + fileSystem: FileSystem.makeNoop({ + realPath: (target) => Effect.succeed(target), + exists: (target) => Effect.succeed(target !== gitDir || gitDirExists), + watch: (_target, options) => + Stream.fromQueue(events).pipe( + Stream.onStart(Effect.sync(() => options?.onReady?.())), + Stream.ensuring(Deferred.succeed(closed, undefined)), + ), + }), + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" })); + assert.deepEqual(yield* branches, [{ refName: "main", isRepo: true }]); + + // Every checkout removes HEAD.lock, which leaves the watch running. + state.currentLocalStatus = { ...baseLocalStatus, refName: "other" }; + yield* Queue.offer(events, { _tag: "Remove", path: "HEAD.lock" }); + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); + assert.deepEqual(yield* branches, [{ refName: "other", isRepo: true }]); + + // `git worktree remove` deletes the watched directory; Windows keeps reporting it. + gitDirExists = false; + yield* Queue.offer(events, { _tag: "Remove", path: gitDir }); + yield* Deferred.await(closed); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }), + ); + it.effect("releases remote demand while passive observers remain", () => { const state = { currentLocalStatus: baseLocalStatus, @@ -1345,6 +2063,92 @@ describe("VcsStatusBroadcaster", () => { assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted))); }).pipe(Effect.provide(layerTest)); }); + + it.effect("refreshes requested during a refresh share one follow-up refresh", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const fetchStarted = yield* Deferred.make(); + const finishFetch = yield* Deferred.make(); + state.beforeRemoteStatus = Deferred.succeed(fetchStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishFetch)), + ); + const first = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped); + yield* Deferred.await(fetchStarted); + // Every read after the first sees a PR, so a caller that reused the + // first refresh would get a status from before its own request. + state.beforeRemoteStatus = Effect.sync(() => { + state.currentRemoteStatus = remoteStatusWithPr; + }); + const later = yield* Effect.all( + [broadcaster.refreshStatus("/repo"), broadcaster.refreshStatus("/repo")], + { concurrency: "unbounded" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(finishFetch, undefined); + + assert.isNull((yield* Fiber.join(first)).pr); + const [second, third] = yield* Fiber.join(later); + assert.deepStrictEqual(second.pr, remoteStatusWithPr.pr); + assert.deepStrictEqual(third.pr, remoteStatusWithPr.pr); + assert.equal(state.remoteStatusCalls, 2); + + yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.remoteStatusCalls, 3); + }).pipe(Effect.provide(layerTestFor(state))); + }); + + it.effect("a failed refresh releases interrupted waiters and runs the shared follow-up", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: remoteStatusWithPr, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.andThen( + Effect.fail( + new GitManagerError({ + operation: "VcsStatusBroadcaster.test", + cwd: "/repo", + detail: "remote status failed", + }), + ), + ), + ); + const first = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit, Effect.forkScoped); + yield* Deferred.await(started); + const interrupted = yield* broadcaster + .refreshStatus("/repo") + .pipe(Effect.forkScoped({ startImmediately: true })); + const remaining = yield* broadcaster + .refreshStatus("/repo") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Fiber.interrupt(interrupted); + state.beforeRemoteStatus = Effect.void; + yield* Deferred.succeed(release, undefined); + assert.isTrue(Exit.isFailure(yield* Fiber.join(first))); + assert.deepStrictEqual((yield* Fiber.join(remaining)).pr, remoteStatusWithPr.pr); + assert.equal(state.remoteStatusCalls, 1); + yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.remoteStatusCalls, 2); + }).pipe(Effect.provide(layerTestFor(state))); + }); }); const newState = (): Parameters[0] => ({ @@ -1386,7 +2190,7 @@ it.effect("detail join during invalidation must get fresh totals", () => { yield* Fiber.join(snapshotFiber), Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }), ); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("serializes branch reads with detailed refresh publication", () => { const state = newState(); @@ -1409,10 +2213,12 @@ it.effect("serializes branch reads with detailed refresh publication", () => { yield* Fiber.join(older); yield* Fiber.join(newer); state.branchRead = () => Effect.succeed("new"); - const result = yield* b.getStatus({ cwd: "/repo" }); - assert.equal(result.refName, "new"); + const result = yield* b + .streamStatus({ cwd: "/repo", includeRemote: false }) + .pipe(Stream.runHead, Effect.flatMap(Effect.fromOption)); + assert.equal(result._tag === "snapshot" && result.local.refName, "new"); assert.equal(state.localStatusCalls, 1); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("publishes overlapping branch reads in checkout order", () => { @@ -1439,8 +2245,11 @@ it.effect("publishes overlapping branch reads in checkout order", () => { yield* Deferred.succeed(resume, undefined); yield* Fiber.join(older); yield* Fiber.join(newer); - assert.deepEqual(yield* branches, [{ refName: "old" }, { refName: "new" }]); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + assert.deepEqual(yield* branches, [ + { refName: "old", isRepo: true }, + { refName: "new", isRepo: true }, + ]); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("does not replay older queued branches after a new subscriber snapshot", () => { @@ -1449,7 +2258,7 @@ it.effect("does not replay older queued branches after a new subscriber snapshot const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const entered = yield* Deferred.make(); const resume = yield* Deferred.make(); - const values = yield* Queue.unbounded<{ readonly refName: string | null }>(); + const values = yield* Queue.unbounded(); let reads = 0; state.branchRead = () => ++reads === 1 @@ -1468,10 +2277,10 @@ it.effect("does not replay older queued branches after a new subscriber snapshot ); yield* Deferred.succeed(resume, undefined); yield* Fiber.join(older); - assert.deepEqual(yield* Queue.take(values), { refName: "new" }); + assert.deepEqual(yield* Queue.take(values), { refName: "new", isRepo: true }); state.branchRead = () => Effect.succeed("latest"); yield* b.refreshBranchStatus({ cwd: "/repo" }); - assert.deepEqual(yield* Queue.take(values), { refName: "latest" }); + assert.deepEqual(yield* Queue.take(values), { refName: "latest", isRepo: true }); yield* Fiber.join(subscriber); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 1868d34181..b691b9d297 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -1,11 +1,13 @@ import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; +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 FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; @@ -23,7 +25,6 @@ import type { VcsStatusSubscriptionInput, } from "@t3tools/contracts"; import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL } from "@t3tools/contracts"; -import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import { mergeGitStatusParts } from "@t3tools/shared/git"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -32,10 +33,17 @@ import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ServerSettings from "../serverSettings.ts"; +import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30); const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15); const MAX_FAILURE_DIAGNOSTIC_VALUES = 8; +// A held index.lock fails the read, and its removal moves no HEAD to trigger another. +const CHECKOUT_REFRESH_RETRY = Schedule.exponential(Duration.seconds(1)).pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.seconds(30))), + ), +); const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128; function boundedDiagnosticValue(value: string): string { @@ -135,35 +143,27 @@ interface CachedRemoteStatus extends CachedValue { readonly branch: string | null; } +interface CachedLocalStatus extends CachedValue { + readonly includesBranchChanges: boolean; +} + interface CachedVcsStatus { - readonly local: CachedValue | null; + readonly local: CachedLocalStatus | null; readonly remote: CachedRemoteStatus | null; } +interface ActiveHeadWatcher { + readonly fiber: Fiber.Fiber; + readonly ready: Deferred.Deferred; + readonly subscriberCount: number; +} + interface ActiveRemotePoller { readonly fiber: Fiber.Fiber; readonly subscriberCount: number; readonly demandCwds: Ref.Ref>; } -export class VcsAutomaticFetchInterval extends Context.Reference>( - "t3/vcs/VcsAutomaticFetchInterval", - { defaultValue: () => Effect.succeed(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) }, -) {} - -export const layerAutomaticFetchInterval = Layer.effect( - VcsAutomaticFetchInterval, - Effect.gen(function* () { - const serverSettings = yield* ServerSettings.ServerSettingsService; - return serverSettings.getSettings.pipe( - Effect.map( - (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval, - ), - Effect.orElseSucceed(() => DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL), - ); - }), -); - export class VcsAutoPullPolicy extends Context.Reference<{ readonly isEnabled: (cwd: string) => Effect.Effect; }>("t3/vcs/VcsAutoPullPolicy", { @@ -222,6 +222,11 @@ export class VcsStatusBroadcaster extends Context.Service< readonly refreshLocalStatus: ( cwd: string, ) => Effect.Effect; + /** + * For a checkout someone is waiting on. Returns once the new branch is published, so the + * caller's reply does not outrun it, and finishes the slower remote read in the background. + */ + readonly refreshAfterCheckout: (cwd: string) => Effect.Effect; readonly refreshStatus: ( cwd: string, options?: { readonly localOnly?: boolean }, @@ -252,6 +257,7 @@ export const make = Effect.gen(function* () { const workflow = yield* GitWorkflowService.GitWorkflowService; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const changesPubSub = yield* Effect.acquireRelease( PubSub.unbounded(), (pubsub) => PubSub.shutdown(pubsub), @@ -260,6 +266,7 @@ export const make = Effect.gen(function* () { PubSub.unbounded<{ readonly cwd: string; readonly refName: string | null; + readonly isRepo: boolean; readonly revision: number; }>(), (pubsub) => PubSub.shutdown(pubsub), @@ -270,17 +277,30 @@ export const make = Effect.gen(function* () { const detailedSubscribers = new Map(); const branches = new Map< string, - { readonly refName: string | null; readonly revision: number } + { + readonly refName: string | null; + readonly isRepo: boolean; + readonly revision: number; + readonly observation: number; + } >(); let branchRevision = 0; + // A slow detailed read must not replace a newer HEAD-only observation. + let branchObservation = 0; const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* ( cwd: string, - refName: string | null, + { refName, isRepo }: { readonly refName: string | null; readonly isRepo: boolean }, + observation: number, ) { - if (branches.get(cwd)?.refName === refName) return; + const previous = branches.get(cwd); + if (previous && previous.observation > observation) return; + if (previous?.refName === refName && previous.isRepo === isRepo) { + branches.set(cwd, { ...previous, observation }); + return; + } const revision = ++branchRevision; - branches.set(cwd, { refName, revision }); - yield* PubSub.publish(branchChangesPubSub, { cwd, refName, revision }); + branches.set(cwd, { refName, isRepo, revision, observation }); + yield* PubSub.publish(branchChangesPubSub, { cwd, refName, isRepo, revision }); }); const localRefreshLocks = yield* KeyedLock.make(); const cacheRef = yield* Ref.make(new Map()); @@ -291,6 +311,7 @@ export const make = Effect.gen(function* () { const withRemoteWriteLock = (cwd: string, effect: Effect.Effect) => remoteWriteLocks.withLock(cwd, effect); const pollersRef = yield* SynchronizedRef.make(new Map()); + const headWatchersRef = yield* SynchronizedRef.make(new Map()); const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* ( cwd: string, @@ -298,9 +319,51 @@ export const make = Effect.gen(function* () { return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null)); }); + // Only full subscribers and direct reads show Changes totals. Command palette rows subscribe + // without remote status and skip them, which halves the git processes a burst of rows spawns. + const branchChangesDemand = new Map(); + const wantsBranchChanges = (cwd: string) => branchChangesDemand.has(cwd); + const acquireBranchChangesDemand = (cwd: string) => + Effect.acquireRelease( + Effect.sync(() => { + branchChangesDemand.set(cwd, (branchChangesDemand.get(cwd) ?? 0) + 1); + }), + () => + Effect.sync(() => { + const count = (branchChangesDemand.get(cwd) ?? 1) - 1; + if (count > 0) branchChangesDemand.set(cwd, count); + else branchChangesDemand.delete(cwd); + }), + ); + + const readLocalStatus = Effect.fn("VcsStatusBroadcaster.readLocalStatus")(function* ( + cwd: string, + ) { + const includeBranchChanges = wantsBranchChanges(cwd); + const local = yield* workflow.localStatus({ cwd }, { includeBranchChanges }); + // A subscriber that shows totals arrived during the read and must not receive it without them. + if (!includeBranchChanges && wantsBranchChanges(cwd)) { + return { + local: yield* workflow.localStatus({ cwd }, { includeBranchChanges: true }), + includesBranchChanges: true, + }; + } + return { local, includesBranchChanges: includeBranchChanges }; + }); + const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")( - function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) { - const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local }; + function* ( + cwd: string, + read: { readonly local: VcsStatusLocalResult; readonly includesBranchChanges: boolean }, + observation: number, + options?: { publish?: boolean }, + ) { + const { local, includesBranchChanges } = read; + const nextLocal = { + fingerprint: fingerprintStatusPart(local), + value: local, + includesBranchChanges, + }; const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => { const previous = cache.get(cwd) ?? { local: null, remote: null }; const remote = previous.remote?.branch === local.refName ? previous.remote : null; @@ -309,7 +372,7 @@ export const make = Effect.gen(function* () { new Map(cache).set(cwd, { local: nextLocal, remote }), ] as const; }); - yield* publishBranch(cwd, local.refName); + yield* publishBranch(cwd, local, observation); if (options?.publish && remoteCleared) { yield* PubSub.publish(changesPubSub, { cwd, @@ -348,21 +411,22 @@ export const make = Effect.gen(function* () { const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* ( cwd: string, + options?: { publish?: boolean }, ) { - const local = yield* workflow.localStatus({ cwd }); - return yield* updateCachedLocalStatus(cwd, local); + const observation = ++branchObservation; + return yield* updateCachedLocalStatus(cwd, yield* readLocalStatus(cwd), observation, options); }); const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")( function* (cwd: string) { const cached = yield* getCachedStatus(cwd); if (cached?.local) { - const branch = yield* workflow.currentBranch(cwd); - if (branch === cached.local.value.refName) return cached.local.value; + if (cached.local.includesBranchChanges || !wantsBranchChanges(cwd)) { + const branch = yield* workflow.currentBranch(cwd); + if (branch === cached.local.value.refName) return cached.local.value; + } yield* workflow.invalidateLocalStatus(cwd); - return yield* updateCachedLocalStatus(cwd, yield* workflow.localStatus({ cwd }), { - publish: true, - }); + return yield* loadLocalStatus(cwd, { publish: true }); } return yield* loadLocalStatus(cwd); }, @@ -385,6 +449,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.getStatus", )(function* (input) { const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); + yield* acquireBranchChangesDemand(cwd); yield* getOrLoadLocalStatus(cwd); const cached = yield* getCachedStatus(cwd); if (cached?.local && cached.remote) { @@ -401,14 +466,18 @@ export const make = Effect.gen(function* () { return mergeGitStatusParts(parts.local, parts.remote); }), ); - }); + }, Effect.scoped); // A refresh that started after a request saw every change that request could mean, so queued // callers share it instead of each running git status again. const localRefreshRequests = new Map(); const localRefreshResults = new Map< string, - { readonly startedAt: number; readonly local: VcsStatusLocalResult } + { + readonly startedAt: number; + readonly local: VcsStatusLocalResult; + readonly includesBranchChanges: boolean; + } >(); const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")( function* (cwd: string) { @@ -418,12 +487,19 @@ export const make = Effect.gen(function* () { cwd, Effect.gen(function* () { const shared = localRefreshResults.get(cwd); - if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local; + if ( + shared !== undefined && + shared.startedAt >= requestedAt && + (shared.includesBranchChanges || !wantsBranchChanges(cwd)) + ) { + return shared.local; + } const startedAt = localRefreshRequests.get(cwd) ?? requestedAt; yield* workflow.invalidateLocalStatus(cwd); - const local = yield* workflow.localStatus({ cwd }); - localRefreshResults.set(cwd, { startedAt, local }); - return yield* updateCachedLocalStatus(cwd, local, { publish: true }); + const observation = ++branchObservation; + const read = yield* readLocalStatus(cwd); + localRefreshResults.set(cwd, { startedAt, ...read }); + return yield* updateCachedLocalStatus(cwd, read, observation, { publish: true }); }), ); }, @@ -433,7 +509,30 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.refreshLocalStatus", )(function* (rawCwd) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); - return yield* refreshLocalStatusCore(cwd); + const local = yield* refreshLocalStatusCore(cwd); + const cached = yield* getCachedStatus(cwd); + // Divergence is local Git data; a slow forge lookup must not delay turn-end updates. + if (cached?.remote?.value?.hasUpstream) { + const divergence = yield* workflow.upstreamDivergence(cwd); + const latest = yield* getCachedStatus(cwd); + if (divergence && latest?.remote?.value && latest.remote.branch === divergence.refName) { + const value = { + ...latest.remote.value, + aheadCount: divergence.aheadCount, + behindCount: divergence.behindCount, + }; + yield* updateCachedRemoteStatus( + cwd, + { + branch: divergence.refName, + value, + fingerprint: fingerprintStatusPart(value), + }, + { publish: true }, + ); + } + } + return local; }); const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* ( @@ -443,7 +542,18 @@ export const make = Effect.gen(function* () { const branch = yield* workflow.currentBranch(cwd); // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch. yield* workflow.invalidateRemoteStatus(cwd); - const value = yield* workflow.remoteStatus({ cwd }, options); + const previousRemote = (yield* getCachedStatus(cwd))?.remote; + const remote = yield* workflow.remoteStatus({ cwd }, options); + const latest = yield* getCachedStatus(cwd); + // An overlapping turn refresh and fetch can both move divergence during the forge lookup. + const refreshed = + remote?.hasUpstream && latest?.remote !== previousRemote && latest?.remote?.branch === branch + ? yield* workflow.upstreamDivergence(cwd) + : null; + const value = + remote && refreshed?.refName === branch + ? { ...remote, aheadCount: refreshed.aheadCount, behindCount: refreshed.behindCount } + : remote; const currentBranch = yield* workflow.currentBranch(cwd); const cached = yield* getCachedStatus(cwd); if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) { @@ -533,33 +643,63 @@ export const make = Effect.gen(function* () { ); }); + const refreshRemoteAndLocalTotals = Effect.fn("VcsStatusBroadcaster.refreshRemoteAndLocalTotals")( + function* (cwd: string, policyCwd: string, refsBeforeLocalRead: string | null) { + return yield* withRemoteWriteLock( + cwd, + Effect.gen(function* () { + const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval); + // Bump the PR lookup epoch after earlier remote writers have finished. + yield* workflow.invalidateStatus(cwd); + const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream }); + // Without a fetch, the cached behind count cannot justify an automatic pull. + const pulled = refreshUpstream + ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd]) + : null; + if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); + yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); + // A fetch, ours or not, can move the base used for local Changes totals. + if ( + refsBeforeLocalRead === null || + (yield* workflow.readRefSnapshot(cwd)) !== refsBeforeLocalRead + ) { + yield* refreshLocalStatusCore(cwd); + } + const parts = yield* getStatusParts(cwd); + return mergeGitStatusParts(parts.local, parts.remote); + }), + ); + }, + ); + const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn( "VcsStatusBroadcaster.refreshStatus", )(function* (rawCwd, options) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); + yield* acquireBranchChangesDemand(cwd); + const refsBeforeLocalRead = options?.localOnly ? null : yield* workflow.readRefSnapshot(cwd); yield* refreshLocalStatusCore(cwd); if (options?.localOnly) { // Never cache a remote here: readers take `value: null` as "read and found no PR". const parts = yield* getStatusParts(cwd); return mergeGitStatusParts(parts.local, parts.remote); } - return yield* withRemoteWriteLock( - cwd, - Effect.gen(function* () { - const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval); - // Bump the PR lookup epoch after earlier remote writers have finished. - yield* workflow.invalidateStatus(cwd); - const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream }); - // Fetch can move the base used for local Changes totals. - yield* refreshLocalStatusCore(cwd); - // Without a fetch, the cached behind count cannot justify an automatic pull. - const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null; - if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); - yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); - const parts = yield* getStatusParts(cwd); - return mergeGitStatusParts(parts.local, parts.remote); - }), + return yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); + }, Effect.scoped); + + const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( + "VcsStatusBroadcaster.refreshAfterCheckout", + )(function* (rawCwd) { + const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); + const localDone = yield* Deferred.make(); + // Owned by the broadcaster so a client disconnecting mid-switch still leaves status correct. + yield* refreshLocalStatusCore(cwd).pipe( + Effect.ensuring(Deferred.succeed(localDone, undefined)), + Effect.andThen(refreshRemoteAndLocalTotals(cwd, rawCwd, null)), + Effect.ignoreCause({ log: true }), + Effect.forkIn(broadcasterScope), ); + yield* Deferred.await(localDone); }); const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] = @@ -747,6 +887,212 @@ export const make = Effect.gen(function* () { } }); + // A request made during a refresh needs a read that starts after it, so overlapping requests + // share one follow-up. Keyed by raw cwd because auto-pull policy depends on it. + // Missing means idle; null means running with no follow-up queued. + type SharedRefresh = Deferred.Deferred; + const queuedRefreshesRef = yield* Ref.make(new Map()); + + const runQueuedRefreshes = Effect.fn("VcsStatusBroadcaster.runQueuedRefreshes")(function* ( + rawCwd: string, + first: SharedRefresh, + ) { + let next: SharedRefresh | null = first; + while (next !== null) { + yield* Deferred.into(refreshStatus(rawCwd), next); + next = yield* Ref.modify(queuedRefreshesRef, (queued) => { + const followUp = queued.get(rawCwd) ?? null; + const nextQueued = new Map(queued); + if (followUp === null) { + nextQueued.delete(rawCwd); + } else { + nextQueued.set(rawCwd, null); + } + return [followUp, nextQueued] as const; + }); + } + }); + + const shareQueuedRefreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn( + "VcsStatusBroadcaster.shareQueuedRefreshStatus", + )(function* (rawCwd, options) { + if (options?.localOnly) return yield* refreshStatus(rawCwd, options); + const requested = yield* Deferred.make(); + // Registering and forking together keeps an interrupt from leaving an entry with no worker. + const shared = yield* Effect.uninterruptible( + Effect.gen(function* () { + const followUp = yield* Ref.modify( + queuedRefreshesRef, + (queued): readonly [SharedRefresh | undefined, Map] => { + if (!queued.has(rawCwd)) return [undefined, new Map(queued).set(rawCwd, null)]; + const followUp = queued.get(rawCwd) ?? requested; + return [followUp, new Map(queued).set(rawCwd, followUp)]; + }, + ); + if (followUp !== undefined) return followUp; + // The broadcaster scope owns the work, so one caller's interrupt does not cancel it for the rest. + yield* runQueuedRefreshes(rawCwd, requested).pipe(Effect.forkIn(broadcasterScope)); + return requested; + }), + ); + return yield* Deferred.await(shared); + }); + + const readHeadBranch = Effect.fn("VcsStatusBroadcaster.readHeadBranch")(function* (cwd: string) { + const observation = ++branchObservation; + const refName = yield* workflow.currentBranch(cwd); + // A null branch is a detached HEAD or a checkout that is gone, such as a removed worktree. + const isRepo = refName !== null || (yield* workflow.repositoryRoot(cwd)) !== null; + return { observation, refName, isRepo }; + }); + + // Keep cache invalidation serialized with detailed reads and refreshes. + const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")( + (cwd: string) => + localRefreshLocks.withLock( + cwd, + Effect.gen(function* () { + if (detailedSubscribers.has(cwd)) { + const local = yield* getOrLoadLocalStatusUnlocked(cwd); + return ( + branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 } + ); + } + const { observation, refName, isRepo } = yield* readHeadBranch(cwd); + // HEAD cannot certify working-tree totals, even when it has not moved. + localRefreshResults.delete(cwd); + yield* workflow.invalidateLocalStatus(cwd); + yield* Ref.update(cacheRef, (cache) => { + const previous = cache.get(cwd); + return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache; + }); + if (detailedSubscribers.has(cwd)) { + const local = yield* loadLocalStatus(cwd, { publish: true }); + return ( + branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 } + ); + } + yield* publishBranch(cwd, { refName, isRepo }, observation); + return branches.get(cwd) ?? { refName, isRepo, revision: 0 }; + }), + ), + ); + + // A checkout outside T3 Code, such as `git switch` in the terminal, calls no refresh RPC. + // Rereading remote too, without a fetch, sends the new branch with its own PR and counts. + const publishCheckedOutRef = Effect.fn("VcsStatusBroadcaster.publishCheckedOutRef")(function* ( + cwd: string, + ) { + if (!detailedSubscribers.has(cwd)) return yield* refreshBranchStatusCore(cwd); + const { observation, refName, isRepo } = yield* readHeadBranch(cwd); + yield* publishBranch(cwd, { refName, isRepo }, observation); + }); + + const reconcileCheckedOutRef = Effect.fn("VcsStatusBroadcaster.reconcileCheckedOutRef")( + function* (cwd: string) { + if (!detailedSubscribers.has(cwd)) return; + if ((yield* getCachedStatus(cwd))?.remote) { + yield* refreshRemoteStatus(cwd, { refreshUpstream: false }); + } else { + yield* refreshLocalStatusCore(cwd); + } + }, + ); + + const retryCheckedOutRef = (cwd: string, refresh: Effect.Effect) => + refresh.pipe( + Effect.retry(CHECKOUT_REFRESH_RETRY), + Effect.catchCause((cause) => + Effect.logWarning("VCS checked-out ref refresh failed", { + cwdLength: cwd.length, + ...remoteRefreshFailureDiagnostics(cause), + }), + ), + ); + + // Runs for the subscription lifetime, so tracing would leave a span open indefinitely. + const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred) { + const headPath = yield* workflow.headPath(cwd); + if (headPath === null) return; + const headDirectory = path.dirname(headPath); + // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose. + yield* fs + .watch(headDirectory, { + onReady: () => Deferred.doneUnsafe(ready, Exit.void), + }) + .pipe( + // On Windows a watch outlives its deleted directory and reports it ~150k times a second. + Stream.takeUntilEffect((event) => + event._tag === "Remove" + ? fs.exists(headDirectory).pipe(Effect.map((exists) => !exists)) + : Effect.succeed(false), + ), + Stream.filter((event) => path.basename(event.path) === "HEAD"), + // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh. + Stream.buffer({ capacity: 1, strategy: "sliding" }), + Stream.mapEffect(() => retryCheckedOutRef(cwd, publishCheckedOutRef(cwd))), + // Detailed status waits behind its own reads; the branch keeps up on the stage above. + Stream.buffer({ capacity: 1, strategy: "sliding" }), + Stream.runForEach(() => retryCheckedOutRef(cwd, reconcileCheckedOutRef(cwd))), + ); + }); + + const retainHeadWatcher = Effect.fn("VcsStatusBroadcaster.retainHeadWatcher")(function* ( + cwd: string, + ) { + const ready = yield* SynchronizedRef.modifyEffect(headWatchersRef, (activeWatchers) => { + const existing = activeWatchers.get(cwd); + if (existing && existing.fiber.pollUnsafe() === undefined) { + const nextWatchers = new Map(activeWatchers).set(cwd, { + ...existing, + subscriberCount: existing.subscriberCount + 1, + }); + return Effect.succeed([existing.ready, nextWatchers] as const); + } + // A watch that ended, say before the repository existed, restarts for everyone holding it. + return Effect.gen(function* () { + const ready = yield* Deferred.make(); + const fiber = yield* watchHead(cwd, ready).pipe( + Effect.catchCause((cause) => + Effect.logWarning("VCS HEAD watch failed", { + cwdLength: cwd.length, + ...remoteRefreshFailureDiagnostics(cause), + }), + ), + // Subscribers wait for the watch, so one that cannot start must not hold them. + Effect.ensuring(Deferred.succeed(ready, undefined)), + Effect.forkIn(broadcasterScope), + ); + const nextWatchers = new Map(activeWatchers).set(cwd, { + fiber, + ready, + subscriberCount: (existing?.subscriberCount ?? 0) + 1, + }); + return [ready, nextWatchers] as const; + }); + }); + yield* Deferred.await(ready); + }); + + const releaseHeadWatcher = Effect.fn("VcsStatusBroadcaster.releaseHeadWatcher")(function* ( + cwd: string, + ) { + const watcherToInterrupt = yield* SynchronizedRef.modify(headWatchersRef, (activeWatchers) => { + const existing = activeWatchers.get(cwd); + if (!existing) return [null, activeWatchers] as const; + const nextWatchers = new Map(activeWatchers); + if (existing.subscriberCount > 1) { + nextWatchers.set(cwd, { ...existing, subscriberCount: existing.subscriberCount - 1 }); + return [null, nextWatchers] as const; + } + nextWatchers.delete(cwd); + return [existing.fiber, nextWatchers] as const; + }); + if (watcherToInterrupt) { + yield* Fiber.interrupt(watcherToInterrupt).pipe(Effect.ignore); + } + }); + const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) => Stream.unwrap( Effect.gen(function* () { @@ -763,7 +1109,10 @@ export const make = Effect.gen(function* () { else detailedSubscribers.set(cwd, remaining); }), ); + if (input.includeRemote !== false) yield* acquireBranchChangesDemand(cwd); const subscription = yield* PubSub.subscribe(changesPubSub); + // Watch before reading so a checkout in between still publishes. + yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd)); const initialLocal = yield* getOrLoadLocalStatus(cwd); const cachedStatus = yield* getCachedStatus(cwd); const initialRemote = cachedStatus?.remote?.value ?? null; @@ -793,42 +1142,26 @@ export const make = Effect.gen(function* () { }), ); - // Serialize branch publication and cache invalidation with detailed reads and refreshes. - const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")( - (cwd: string) => - localRefreshLocks.withLock( - cwd, - Effect.gen(function* () { - if (detailedSubscribers.has(cwd)) { - const local = yield* getOrLoadLocalStatusUnlocked(cwd); - return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 }; - } - const refName = yield* workflow.currentBranch(cwd); - // HEAD cannot certify working-tree totals, even when it has not moved. - localRefreshResults.delete(cwd); - yield* workflow.invalidateLocalStatus(cwd); - yield* Ref.update(cacheRef, (cache) => { - const previous = cache.get(cwd); - return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache; - }); - if (detailedSubscribers.has(cwd)) { - const local = yield* workflow.localStatus({ cwd }); - yield* updateCachedLocalStatus(cwd, local, { publish: true }); - return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 }; - } - yield* publishBranch(cwd, refName); - return { refName, revision: branches.get(cwd)?.revision ?? 0 }; - }), - ), - ); - const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn( "VcsStatusBroadcaster.refreshBranchStatus", )(function* (input) { - const { refName } = yield* refreshBranchStatusCore( - yield* withFileSystem(normalizeCwd(input.cwd)), + const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); + if (!detailedSubscribers.has(cwd)) { + const { refName, isRepo } = yield* refreshBranchStatusCore(cwd); + return { refName, isRepo }; + } + const { observation, refName, isRepo } = yield* readHeadBranch(cwd); + yield* publishBranch(cwd, { refName, isRepo }, observation); + yield* refreshBranchStatusCore(cwd).pipe( + Effect.catchCause((cause) => + Effect.logWarning("VCS branch refresh failed", { + cwdLength: cwd.length, + ...remoteRefreshFailureDiagnostics(cause), + }), + ), + Effect.forkIn(broadcasterScope), ); - return { refName }; + return { refName, isRepo }; }); const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) => @@ -836,14 +1169,19 @@ export const make = Effect.gen(function* () { Effect.gen(function* () { const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); const subscription = yield* PubSub.subscribe(branchChangesPubSub); + yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd)); const branch = yield* refreshBranchStatusCore(cwd); return Stream.concat( - Stream.make({ refName: branch.refName }), + Stream.make({ refName: branch.refName, isRepo: branch.isRepo }), Stream.fromSubscription(subscription).pipe( Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision), - Stream.map(({ refName }) => ({ refName })), + Stream.map(({ refName, isRepo }) => ({ refName, isRepo })), ), - ).pipe(Stream.changesWith((left, right) => left.refName === right.refName)); + ).pipe( + Stream.changesWith( + (left, right) => left.refName === right.refName && left.isRepo === right.isRepo, + ), + ); }), ); @@ -855,7 +1193,8 @@ export const make = Effect.gen(function* () { ), getStatus, refreshLocalStatus, - refreshStatus, + refreshAfterCheckout, + refreshStatus: shareQueuedRefreshStatus, refreshPullRequestStatus, streamStatus, }); diff --git a/apps/server/src/vcs/checkpointUntrackedBlobs.ts b/apps/server/src/vcs/checkpointUntrackedBlobs.ts new file mode 100644 index 0000000000..675dba0121 --- /dev/null +++ b/apps/server/src/vcs/checkpointUntrackedBlobs.ts @@ -0,0 +1,456 @@ +// @effect-diagnostics nodeBuiltinImport:off - Comparing a file with its last capture needs bigint lstat, which FileSystem lacks. +import * as NodeFSP from "node:fs/promises"; + +import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; + +import type * as VcsDriver from "./VcsDriver.ts"; +import * as VcsProcess from "./VcsProcess.ts"; + +/** An untracked file's blob from the last capture, with everything that decided its content. */ +interface UntrackedBlob { + readonly path: string; + readonly mode: string; + readonly oid: string; + readonly size: bigint; + readonly stat: string; + readonly attributes: string; +} + +interface Snapshot { + readonly topLevel: string; + readonly head: string; + readonly config: string; + readonly blobs: ReadonlyArray; + /** Files hashed without a reading of their conversion state from before staging. */ + readonly pending: ReadonlyArray; +} + +/** The conversion state read before staging; a blob is remembered only if it reads the same after. */ +interface ConversionState { + readonly config: string; + readonly attributes: ReadonlyMap; +} + +export const NOTHING: { + readonly reused: ReadonlyArray; + readonly before: ConversionState | undefined; +} = { reused: [], before: undefined }; + +// Every attribute convert_to_git reads; a blob is reused only while all of them are unchanged. +const CONVERSION_ATTRIBUTES = [ + "text", + "eol", + "crlf", + "ident", + "working-tree-encoding", + "filter", +] as const; +const MAX_BLOBS = 20_000; +// Below this, hashing the files costs less than the Git processes that check them. +const MIN_TOTAL_BYTES = 16n * 1024n * 1024n; +// A capture that staged faster than this and reused nothing has nothing worth another Git process. +const MIN_STAGING_MS = 100; +// A file must have been left alone for this long before the capture, so an edit that lands +// while Git hashes it cannot hide inside one timestamp tick (two seconds on FAT). +const SETTLED_MS = 3_000; +const MAX_WORKSPACES = 64; +const STAT_BATCH = 512; +const LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; + +const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; + +const lstatAll = (root: string, paths: ReadonlyArray) => + Effect.promise(async () => { + const stats: Array< + { stat: string; size: bigint; changedNs: bigint; regular: boolean } | undefined + > = []; + for (let start = 0; start < paths.length; start += STAT_BATCH) { + const batch = await Promise.all( + paths.slice(start, start + STAT_BATCH).map((entryPath) => + NodeFSP.lstat(`${root}/${entryPath}`, { bigint: true }).then( + (stat) => ({ + stat: `${stat.dev}:${stat.ino}:${stat.mode}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`, + size: stat.size, + changedNs: stat.mtimeNs > stat.ctimeNs ? stat.mtimeNs : stat.ctimeNs, + regular: stat.isFile(), + }), + () => undefined, + ), + ), + ); + stats.push(...batch); + } + return stats; + }); + +/** + * Lets a capture skip rehashing untracked files that have not changed since the last capture of + * the same workspace. A blob is reused only when a fresh `git add` would produce the same one: + * same file stat, same conversion attributes and config, still not ignored, still not tracked. + */ +export const make = ( + execute: VcsDriver.VcsDriver["Service"]["execute"], + fileSystem: FileSystem.FileSystem, +) => { + const snapshots = new Map(); + + // Worktree files only: an index copy of a deleted .gitattributes applies or not by staging order. + const readAttributes = Effect.fn("GitVcsDriver.checkpoints.readConversionAttributes")(function* ( + topLevel: string, + env: NodeJS.ProcessEnv, + paths: ReadonlyArray, + ) { + if (paths.length === 0) return []; + const stdin = `${paths.join("\0")}\0`; + const result = yield* execute({ + operation, + cwd: topLevel, + args: ["check-attr", "-z", "--stdin", ...CONVERSION_ATTRIBUTES], + stdin, + env: { ...env, GIT_INDEX_FILE: `${env.GIT_INDEX_FILE}.none` }, + maxOutputBytes: + CONVERSION_ATTRIBUTES.length * (Buffer.byteLength(stdin) + paths.length * 256), + outputMode: "error", + }); + // Records are " NUL NUL NUL", one per attribute, in input order. + const fields = result.stdout.split("\0"); + return paths.map((entryPath, index) => { + const values: string[] = []; + for (let attribute = 0; attribute < CONVERSION_ATTRIBUTES.length; attribute++) { + const field = (index * CONVERSION_ATTRIBUTES.length + attribute) * 3; + if (fields[field] !== entryPath || fields[field + 2] === undefined) return undefined; + values.push(fields[field + 2]!); + } + return values.join("\0"); + }); + }); + + // Config that changes the blob or mode `git add` records for an unchanged file. + const readConfig = (cwd: string) => + execute({ + operation, + cwd, + args: [ + "config", + "--null", + "--get-regexp", + "^(core\\.(autocrlf|eol|filemode)|filter\\.(unspecified|unset)\\..*)$", + ], + allowNonZeroExit: true, + }).pipe(Effect.map((result) => `${result.exitCode}\0${result.stdout}`)); + + /** + * Finds directories whose .gitattributes may have changed while Git hashed: a present file + * touched since just before the capture, or a missing one in a directory touched since then. + * Reading attributes before and after staging cannot see a change that was undone in between. + */ + const changingAttributeDirectories = Effect.fnUntraced(function* ( + topLevel: string, + paths: ReadonlyArray, + settledNs: bigint, + ) { + const directories = new Set(paths.length === 0 ? [] : [""]); + for (const entryPath of paths) { + for ( + let end = entryPath.lastIndexOf("/"); + end > 0 && !directories.has(entryPath.slice(0, end + 1)); + end = entryPath.lastIndexOf("/", end - 1) + ) { + directories.add(entryPath.slice(0, end + 1)); + } + } + const list = [...directories]; + const [files, parents] = yield* Effect.all([ + lstatAll( + topLevel, + list.map((directory) => `${directory}.gitattributes`), + ), + lstatAll(topLevel, list), + ]); + const changing = new Set( + list.filter((_, index) => { + const changedNs = (files[index] ?? parents[index])?.changedNs; + return changedNs === undefined || changedNs >= settledNs; + }), + ); + return (entryPath: string) => { + if (changing.has("")) return true; + for ( + let end = entryPath.lastIndexOf("/"); + end > 0; + end = entryPath.lastIndexOf("/", end - 1) + ) { + if (changing.has(entryPath.slice(0, end + 1))) return true; + } + return false; + }; + }); + + /** + * Adds the still-valid blobs to the scratch index, flagged so `git add` does not read their + * files. The index must hold exactly HEAD's paths. Returns the blobs it added, and the + * conversion state of every file this capture may remember, read before any of them is hashed. + */ + const reuse = Effect.fn("GitVcsDriver.checkpoints.reuseUntrackedBlobs")( + function* (input: { + readonly cwd: string; + readonly topLevel: string; + readonly head: string; + readonly env: NodeJS.ProcessEnv; + readonly indexConfig: ReadonlyArray; + }) { + const snapshot = snapshots.get(input.cwd); + // A capture that fails after this point hashes everything once more, then remembers again. + snapshots.delete(input.cwd); + if (snapshot === undefined || snapshot.topLevel !== input.topLevel) return NOTHING; + let blobs = snapshot.blobs; + if (snapshot.head !== input.head) { + // A path HEAD now tracks, or one below a path it changed, is no longer untracked. + const moved = yield* execute({ + operation, + cwd: input.cwd, + args: ["diff-tree", "-r", "-z", "--name-only", "--no-renames", snapshot.head, input.head], + maxOutputBytes: LIST_MAX_OUTPUT_BYTES, + outputMode: "error", + }); + const changed = new Set(moved.stdout.split("\0")); + blobs = blobs.filter((blob) => { + for (let end = blob.path.length; end > 0; end = blob.path.lastIndexOf("/", end - 1)) { + if (changed.has(blob.path.slice(0, end))) return false; + } + return true; + }); + } + const stats = yield* lstatAll( + input.topLevel, + blobs.map((blob) => blob.path), + ); + blobs = blobs.filter((blob, index) => stats[index]?.stat === blob.stat); + // Git stages a directory that became a repository as one gitlink, not as its files. + const directories = new Set(); + for (const blob of blobs) { + for ( + let end = blob.path.lastIndexOf("/"); + end > 0 && !directories.has(blob.path.slice(0, end)); + end = blob.path.lastIndexOf("/", end - 1) + ) { + directories.add(blob.path.slice(0, end)); + } + } + const directoryList = [...directories]; + const repositories = yield* lstatAll( + input.topLevel, + directoryList.map((directory) => `${directory}/.git`), + ); + const nested = directoryList.filter((_, index) => repositories[index] !== undefined); + if (nested.length > 0) { + blobs = blobs.filter( + (blob) => !nested.some((directory) => blob.path.startsWith(`${directory}/`)), + ); + } + const paths = [...blobs.map((blob) => blob.path), ...snapshot.pending]; + if (paths.length === 0) return NOTHING; + const unchecked = Effect.succeed({ exitCode: 1, stdout: "" }); + const stdin = `${blobs.map((blob) => `${blob.path}\0`).join("")}`; + const [config, attributes, ignored, objects] = yield* Effect.all( + [ + readConfig(input.cwd), + readAttributes(input.topLevel, input.env, paths), + // Without --no-index this reports only untracked paths, which these are in this index. + blobs.length === 0 + ? unchecked + : execute({ + operation, + cwd: input.topLevel, + args: [...input.indexConfig, "check-ignore", "-z", "--stdin"], + stdin, + env: input.env, + allowNonZeroExit: true, + maxOutputBytes: Buffer.byteLength(stdin), + outputMode: "error", + }), + // Blobs of deleted checkpoints can be pruned while this process still remembers them. + blobs.length === 0 + ? unchecked + : execute({ + operation, + cwd: input.cwd, + args: ["cat-file", "--batch-check=%(objectname) %(objecttype)"], + stdin: `${[...new Set(blobs.map((blob) => blob.oid))].join("\n")}\n`, + maxOutputBytes: blobs.length * 128, + outputMode: "error", + }), + ], + { concurrency: "unbounded" }, + ); + const before: ConversionState = { + config, + attributes: new Map(paths.map((entryPath, index) => [entryPath, attributes[index]])), + }; + if (config !== snapshot.config || ignored.exitCode > 1) return { reused: [], before }; + const ignoredPaths = new Set(ignored.stdout.split("\0")); + const present = new Set(objects.stdout.split("\n")); + blobs = blobs.filter( + (blob, index) => + attributes[index] === blob.attributes && + !ignoredPaths.has(blob.path) && + present.has(`${blob.oid} blob`), + ); + if (blobs.length === 0) return { reused: [], before }; + + const indexFile = input.env.GIT_INDEX_FILE!; + const { mtime } = yield* fileSystem.stat(indexFile); + if (Option.isNone(mtime)) return { reused: [], before }; + yield* execute({ + operation, + cwd: input.cwd, + // core.ignorestat marks the new entries assume-unchanged, so git add trusts them as they are. + args: [ + ...input.indexConfig, + "-c", + "core.ignorestat=true", + "update-index", + "-z", + "--index-info", + ], + stdin: blobs.map((blob) => `${blob.mode} ${blob.oid}\t${blob.path}\0`).join(""), + env: input.env, + }); + // Tracked entries are racy against the index's old timestamp, not this rewrite's. + const indexTime = Math.floor(mtime.value.getTime() / 1000); + yield* fileSystem.utimes(indexFile, indexTime, indexTime); + return { reused: blobs, before }; + }, + Effect.orElseSucceed(() => NOTHING), + ); + + /** Records the untracked files the published checkpoint `tree` holds, for the next capture. */ + const remember = Effect.fn("GitVcsDriver.checkpoints.rememberUntrackedBlobs")( + function* (input: { + readonly cwd: string; + readonly topLevel: string; + readonly head: string; + readonly tree: string; + readonly env: NodeJS.ProcessEnv; + readonly startedAt: number; + readonly stagingMs: number; + readonly reused: ReadonlyArray; + readonly before: ConversionState | undefined; + }) { + if (input.reused.length === 0 && input.stagingMs < MIN_STAGING_MS) return; + const listed = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "diff-tree", + "-r", + "-z", + "--raw", + "--no-abbrev", + "--no-renames", + "--diff-filter=AD", + input.head, + input.tree, + ], + maxOutputBytes: LIST_MAX_OUTPUT_BYTES, + outputMode: "error", + }); + const reused = new Map(input.reused.map((blob) => [blob.path, blob])); + const kept: UntrackedBlob[] = []; + const added: Array<{ path: string; mode: string; oid: string }> = []; + // Records are ": NUL NUL". + const fields = listed.stdout.split("\0"); + for (let field = 0; field + 1 < fields.length; field += 2) { + const [, mode = "", , oid = "", status] = fields[field]!.split(" "); + const entryPath = fields[field + 1]!; + if (status === "D") { + // Git may still apply a deleted .gitattributes from the index, depending on staging order. + if (entryPath === ".gitattributes" || entryPath.endsWith("/.gitattributes")) return; + continue; + } + // U+FFFD marks a name that is not UTF-8 and so cannot be addressed from here. + if ((mode !== "100644" && mode !== "100755") || entryPath.includes("\uFFFD")) continue; + const previous = reused.get(entryPath); + if (previous !== undefined && previous.oid === oid && previous.mode === mode) { + kept.push(previous); + } else { + added.push({ path: entryPath, mode, oid }); + } + } + const stats = yield* lstatAll( + input.topLevel, + added.map((entry) => entry.path), + ); + const settledNs = BigInt(input.startedAt - SETTLED_MS) * 1_000_000n; + const hashed = added.flatMap((entry, index) => { + const stat = stats[index]; + return stat !== undefined && stat.regular + ? [{ ...entry, size: stat.size, stat: stat.stat, settled: stat.changedNs < settledNs }] + : []; + }); + const largest = [...kept, ...hashed] + .sort((left, right) => (left.size < right.size ? 1 : left.size > right.size ? -1 : 0)) + .slice(0, MAX_BLOBS); + if (largest.reduce((total, blob) => total + blob.size, 0n) < MIN_TOTAL_BYTES) return; + + // Git hashed these under rules nobody recorded. Reading the rules now would pair the blob + // with whatever they have since become, so only a reading from before staging counts. + const before = input.before; + const candidates = largest.flatMap((blob) => + "settled" in blob && blob.settled && before?.attributes.get(blob.path) !== undefined + ? [blob] + : [], + ); + const candidatePaths = candidates.map((blob) => blob.path); + const [config, attributes, changing] = yield* Effect.all( + [ + readConfig(input.cwd), + readAttributes(input.topLevel, input.env, candidatePaths), + changingAttributeDirectories(input.topLevel, candidatePaths, settledNs), + ], + { concurrency: "unbounded" }, + ); + // check-attr prints a filter driver named "unspecified" or "unset" like no filter at all. + if (/\0filter\./.test(config)) return; + const sameConfig = before !== undefined && config === before.config; + const admitted = candidates.flatMap((blob, index): UntrackedBlob[] => { + const value = attributes[index]; + // A clean filter is a program whose output can depend on more than the file. + return sameConfig && + value !== undefined && + value === before.attributes.get(blob.path) && + /\0(?:unspecified|unset)$/.test(value) && + !changing(blob.path) + ? [ + { + path: blob.path, + mode: blob.mode, + oid: blob.oid, + size: blob.size, + stat: blob.stat, + attributes: value, + }, + ] + : []; + }); + // Reused blobs were checked against the earlier config; a different one now vouches for none. + const blobs = sameConfig + ? [...largest.flatMap((blob) => ("settled" in blob ? [] : [blob])), ...admitted] + : []; + const remembered = new Set(blobs.map((blob) => blob.path)); + snapshots.set(input.cwd, { + topLevel: input.topLevel, + head: input.head, + config, + blobs, + pending: largest.flatMap((blob) => (remembered.has(blob.path) ? [] : [blob.path])), + }); + if (snapshots.size > MAX_WORKSPACES) snapshots.delete(snapshots.keys().next().value!); + }, + (effect) => Effect.ignore(effect), + ); + + return { reuse, remember }; +}; diff --git a/apps/server/src/vcs/worktreeCheckoutCache.ts b/apps/server/src/vcs/worktreeCheckoutCache.ts index a72d6d859f..8a51189fe6 100644 --- a/apps/server/src/vcs/worktreeCheckoutCache.ts +++ b/apps/server/src/vcs/worktreeCheckoutCache.ts @@ -511,6 +511,7 @@ export const makeWorktreeCheckoutCache = Effect.fn("WorktreeCheckoutCache.make") readonly worktreePath: string; readonly refName: string; readonly checkoutWorkers: string; + readonly lockReason?: string | undefined; }) { if (!(yield* gitSupported)) return false; const worktreePath = path.resolve(input.cwd, input.worktreePath); @@ -613,13 +614,14 @@ export const makeWorktreeCheckoutCache = Effect.fn("WorktreeCheckoutCache.make") if (moved === null || (yield* fileSystem.exists(target.indexHook))) return null; return target; }); - const rollback = git("rollback", input.cwd, [ - "worktree", - "remove", - "--force", - "--", - worktreePath, - ]).pipe( + const rollback = ( + input.lockReason + ? git("unlockRollback", input.cwd, ["worktree", "unlock", "--", worktreePath]) + : Effect.void + ).pipe( + Effect.andThen( + git("rollback", input.cwd, ["worktree", "remove", "--force", "--", worktreePath]), + ), Effect.flatMap((removed) => removed === null ? Effect.logWarning("could not remove a partially created worktree", { worktreePath }) @@ -633,6 +635,7 @@ export const makeWorktreeCheckoutCache = Effect.fn("WorktreeCheckoutCache.make") "worktree", "add", "--no-checkout", + ...(input.lockReason ? ["--lock", "--reason", input.lockReason] : []), "--", worktreePath, input.refName, diff --git a/apps/server/src/vcs/worktreeRemoval.ts b/apps/server/src/vcs/worktreeRemoval.ts index f1140cdcc3..b48994873b 100644 --- a/apps/server/src/vcs/worktreeRemoval.ts +++ b/apps/server/src/vcs/worktreeRemoval.ts @@ -9,6 +9,42 @@ import type * as GitVcsDriver from "./GitVcsDriver.ts"; const INDEX_LIST_MAX_BYTES = 64 * 1024 * 1024; +/** + * git-annex replaces a linked worktree's `.git` file with a symlink to its admin + * directory, so its symlinks into `.git/annex` resolve. Git then refuses to remove it. + */ +const annexedAdminDir = Effect.fn("WorktreeRemoval.annexedAdminDir")( + function* (worktreePath: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const adminDir = path.resolve( + worktreePath, + yield* fileSystem.readLink(path.join(worktreePath, ".git")), + ); + const pointsBackTo = path.dirname( + path.resolve( + adminDir, + (yield* fileSystem.readFileString(path.join(adminDir, "gitdir"))).trim(), + ), + ); + return (yield* fileSystem.realPath(pointsBackTo)) === (yield* fileSystem.realPath(worktreePath)) + ? Option.some(adminDir) + : Option.none(); + }, + Effect.orElseSucceed(() => Option.none()), +); + +export const isLinkedWorktree = Effect.fn("WorktreeRemoval.isLinkedWorktree")(function* ( + worktreePath: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + return ( + (yield* fileSystem.stat(path.join(worktreePath, ".git"))).type === "File" || + Option.isSome(yield* annexedAdminDir(worktreePath)) + ); +}); + /** * Git for Windows before 2.54 follows NTFS junctions; newer Git leaves them behind. * On Windows, mirror Git's removal checks, then delete with Node's `rm`, which @@ -33,6 +69,39 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt // Git refuses to remove a worktree with untracked files unless forced, but // its check honors `status.showUntrackedFiles=no` and would delete them. const statusConfig = ["-c", "status.showUntrackedFiles=normal"]; + // Git's own refusals, worded the way it prints them. + const refuse = (message: string, cause?: unknown) => + new GitCommandError({ + operation: input.operation, + command: "git worktree remove", + cwd: input.cwd, + detail: `fatal: ${message}`, + ...(cause === undefined ? {} : { cause }), + }); + const annexed = yield* annexedAdminDir(worktreePath); + if (Option.isSome(annexed)) { + const adminDir = annexed.value; + const writeGitFile = fileSystem.writeFileString(gitFile, `gitdir: ${adminDir}\n`); + // A kept worktree's annexed files resolve only through the symlink; a gitdir + // file is the fallback when it cannot be recreated. + yield* Effect.addFinalizer(() => + fileSystem.exists(worktreePath).pipe( + Effect.flatMap((kept) => + kept + ? fileSystem.remove(gitFile, { force: true }).pipe( + Effect.andThen(fileSystem.symlink(adminDir, gitFile)), + Effect.catch(() => writeGitFile), + ) + : Effect.void, + ), + Effect.ignore, + ), + ); + yield* fileSystem.remove(gitFile).pipe( + Effect.andThen(writeGitFile), + Effect.mapError((cause) => refuse(`failed to replace '${gitFile}'`, cause)), + ); + } const linked = (yield* HostProcess.isWindows) && (yield* fileSystem.stat(gitFile).pipe( @@ -50,15 +119,6 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt ]); } - // Git's own refusals, worded the way it prints them. - const refuse = (message: string, cause?: unknown) => - new GitCommandError({ - operation: input.operation, - command: "git worktree remove", - cwd: input.cwd, - detail: `fatal: ${message}`, - ...(cause === undefined ? {} : { cause }), - }); const gitOutput = (cwd: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => input .execute({ @@ -153,4 +213,4 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt ); // The folder is gone, so Git only drops the worktree's metadata. return yield* input.run(["worktree", "remove", "--force", "--force", "--", worktreePath]); -}); +}, Effect.scoped); diff --git a/apps/server/src/workspace/IgnorePatterns.test.ts b/apps/server/src/workspace/IgnorePatterns.test.ts new file mode 100644 index 0000000000..f10345566e --- /dev/null +++ b/apps/server/src/workspace/IgnorePatterns.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { parseIgnoreFile } from "./IgnorePatterns.ts"; + +const decide = (contents: string, path: string, isFolder = false) => + parseIgnoreFile(contents).decide(path, isFolder); + +describe("parseIgnoreFile", () => { + it("lets the last matching pattern decide, including negations", () => { + expect(decide("*keep*\n!*keep*\n", "sub/keep-link.ts")).toBe("included"); + expect(decide("!*keep*\n*keep*\n", "sub/keep-link.ts")).toBe("ignored"); + expect(decide("# comment\n\nother\n", "keep.ts")).toBeUndefined(); + }); + + it("anchors patterns that contain a slash and matches bare names at any depth", () => { + expect(decide("link", "a/b/link")).toBe("ignored"); + expect(decide("/link", "a/link")).toBeUndefined(); + expect(decide("/link", "link")).toBe("ignored"); + expect(decide("a/link", "x/a/link")).toBeUndefined(); + expect(decide("a/*.ts", "a/b/c.ts")).toBeUndefined(); + expect(decide("link", "blink")).toBeUndefined(); + expect(decide("link", "a/blink")).toBeUndefined(); + }); + + it("supports globstars, classes, escapes, and folder-only patterns", () => { + expect(decide("**/gen/*.ts", "gen/a.ts")).toBe("ignored"); + expect(decide("a/**/b", "a/x/y/b")).toBe("ignored"); + expect(decide("a/**/b", "a/b")).toBe("ignored"); + expect(decide("foo/**/bar", "foo/xbar")).toBeUndefined(); + expect(decide("foo/**/bar", "foo/x/ybar")).toBeUndefined(); + expect(decide("out/**", "out/x/y")).toBe("ignored"); + expect(decide("link-[0-9]", "link-7")).toBe("ignored"); + expect(decide("link-[!0-9]", "link-7")).toBeUndefined(); + expect(decide("link-?", "link-/")).toBeUndefined(); + expect(decide("\\!bang\n\\#hash\nstar\\*", "!bang")).toBe("ignored"); + expect(decide("\\!bang\n\\#hash\nstar\\*", "#hash")).toBe("ignored"); + expect(decide("\\!bang\n\\#hash\nstar\\*", "starx")).toBeUndefined(); + expect(decide("dist/", "dist")).toBeUndefined(); + expect(decide("dist/", "dist", true)).toBe("ignored"); + }); + + it("matches adversarial patterns in linear time", () => { + // A backtracking regex takes seconds to reject this pair; the vitest timeout catches that. + const pattern = `${"a*".repeat(20)}b\n`; + expect(decide(pattern, `${"a".repeat(200)}c`)).toBeUndefined(); + expect(decide(pattern.repeat(50), `${"a".repeat(1_000)}c`)).toBeUndefined(); + expect(decide(pattern, `${"a".repeat(200)}b`)).toBe("ignored"); + }); + + it("parses unclosed classes in linear time", () => { + // Rescanning the rest of the line for each `[` stalls for over a minute here; linear takes ms. + expect(decide("[".repeat(30_000), "[".repeat(30_000))).toBe("ignored"); + expect(decide(`${"[".repeat(30_000)}]`, "x")).toBeUndefined(); + expect(decide("[a][", "a[")).toBe("ignored"); + }); +}); diff --git a/apps/server/src/workspace/IgnorePatterns.ts b/apps/server/src/workspace/IgnorePatterns.ts new file mode 100644 index 0000000000..1180b02316 --- /dev/null +++ b/apps/server/src/workspace/IgnorePatterns.ts @@ -0,0 +1,170 @@ +/** + * Gitignore-syntax matching for `.ignore` files, which git cannot evaluate for us. Patterns come + * from the repository, so each runs as an NFA over the path (O(pattern × path)): a backtracking + * regex stalls for seconds on `a*a*a*…b`. POSIX `[:class:]` names are not supported. + */ + +type Token = + | { readonly type: "char"; readonly char: string } + | { readonly type: "one" } + | { readonly type: "class"; readonly negated: boolean; readonly ranges: ReadonlyArray } + | { readonly type: "star" } + | { readonly type: "any" } + /** A leading or inner `**` segment: nothing, or anything ending in `/`. */ + | { readonly type: "folders" }; + +interface Pattern { + readonly tokens: ReadonlyArray; + readonly negated: boolean; + readonly folderOnly: boolean; +} + +export type IgnoreDecision = "ignored" | "included"; + +function parseClass(chars: ReadonlyArray, start: number) { + let index = start + 1; + const negated = chars[index] === "!" || chars[index] === "^"; + if (negated) index += 1; + const ranges: string[] = []; + for (let first = true; index < chars.length; first = false) { + let char = chars[index]!; + if (char === "]" && !first) + return { token: { type: "class", negated, ranges } as const, end: index }; + if (char === "\\" && index + 1 < chars.length) char = chars[++index]!; + if (chars[index + 1] === "-" && index + 2 < chars.length && chars[index + 2] !== "]") { + let last = chars[index + 2]!; + index += 2; + if (last === "\\" && index + 1 < chars.length) last = chars[++index]!; + ranges.push(char, last); + } else { + ranges.push(char, char); + } + index += 1; + } + return undefined; +} + +function parseLine(rawLine: string): Pattern | undefined { + let line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine; + // Trailing spaces are dropped unless escaped. + while (line.endsWith(" ") && !line.endsWith("\\ ")) line = line.slice(0, -1); + if (line === "" || line.startsWith("#")) return undefined; + const negated = line.startsWith("!"); + if (negated) line = line.slice(1); + else if (line.startsWith("\\!") || line.startsWith("\\#")) line = line.slice(1); + const folderOnly = line.endsWith("/") && !line.endsWith("\\/"); + if (folderOnly) line = line.slice(0, -1); + if (line === "") return undefined; + const anchored = line.slice(0, -1).includes("/"); + if (line.startsWith("/")) line = line.slice(1); + + const chars = Array.from(line); + const tokens: Token[] = anchored ? [] : [{ type: "folders" }]; + // A `[` that never closes leaves every later `[` unclosed too, so one failed scan settles them + // all; rescanning the suffix for each would make `[[[[…` quadratic. + let classesClose = true; + for (let index = 0; index < chars.length; index += 1) { + const char = chars[index]!; + if (char === "*" && chars[index + 1] === "*") { + const atSegmentStart = index === 0 || chars[index - 1] === "/"; + const next = chars[index + 2]; + if (atSegmentStart && next === "/") { + tokens.push({ type: "folders" }); + index += 2; + continue; + } + if (atSegmentStart && next === undefined) { + tokens.push({ type: "any" }); + index += 1; + continue; + } + } + if (char === "*") tokens.push({ type: "star" }); + else if (char === "?") tokens.push({ type: "one" }); + else if (char === "[") { + const parsed = classesClose ? parseClass(chars, index) : undefined; + if (!parsed) classesClose = false; + if (parsed) { + tokens.push(parsed.token); + index = parsed.end; + } else tokens.push({ type: "char", char }); + } else if (char === "\\" && index + 1 < chars.length) { + tokens.push({ type: "char", char: chars[++index]! }); + } else tokens.push({ type: "char", char }); + } + return { tokens, negated, folderOnly }; +} + +/** + * States are token positions. A `folders` token that has consumed part of a segment is `~position` + * instead: it may only finish after the next `/`, so an inner globstar never matches `xbar` as `bar`. + */ +function matches(tokens: ReadonlyArray, path: ReadonlyArray): boolean { + let states = new Set(); + const add = (set: Set, position: number) => { + // Wildcards also match nothing, so reaching one reaches the token after it. + for (; position <= tokens.length && !set.has(position); position += 1) { + set.add(position); + const type = tokens[position]?.type; + if (type !== "star" && type !== "any" && type !== "folders") return; + } + }; + add(states, 0); + for (const char of path) { + const next = new Set(); + for (const state of states) { + const position = state < 0 ? ~state : state; + const token = tokens[position]; + if (!token) continue; + switch (token.type) { + case "char": + if (token.char === char) add(next, position + 1); + break; + case "one": + if (char !== "/") add(next, position + 1); + break; + case "class": { + let inRange = false; + for (let index = 0; index < token.ranges.length && !inRange; index += 2) { + inRange = token.ranges[index]! <= char && char <= token.ranges[index + 1]!; + } + if (char !== "/" && inRange !== token.negated) add(next, position + 1); + break; + } + case "star": + if (char !== "/") add(next, position); + break; + case "any": + add(next, position); + break; + case "folders": + if (char === "/") add(next, position); + else next.add(~position); + break; + } + } + if (next.size === 0) return false; + states = next; + } + return states.has(tokens.length); +} + +export interface IgnoreFile { + /** The last pattern that matches decides; `undefined` when none does. */ + readonly decide: (relativePath: string, isFolder: boolean) => IgnoreDecision | undefined; +} + +export function parseIgnoreFile(contents: string): IgnoreFile { + const patterns = contents.split("\n").flatMap((line) => parseLine(line) ?? []); + return { + decide: (relativePath, isFolder) => { + const path = Array.from(relativePath); + for (let index = patterns.length - 1; index >= 0; index -= 1) { + const pattern = patterns[index]!; + if (pattern.folderOnly && !isFolder) continue; + if (matches(pattern.tokens, path)) return pattern.negated ? "included" : "ignored"; + } + return undefined; + }, + }; +} diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index b0633dac04..92d8bc882c 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -433,6 +433,20 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }); }), ); + + it.effect("finds ignored files that sort past the listing limit", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ git: true }); + yield* writeTextFile(cwd, ".gitignore", "*.secret\n"); + for (let index = 1; index <= 205; index += 1) { + yield* writeTextFile(cwd, `file-${String(index).padStart(3, "0")}.secret`, "s"); + } + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const listed = yield* workspaceEntries.listIgnoredFiles({ cwd, query: "file-205" }); + expect(listed.files).toContainEqual({ path: "file-205.secret", byteLength: 1 }); + }), + ); }); describe("search", () => { @@ -457,6 +471,34 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); + it.effect("matches glob metacharacters in the query literally", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-brackets-" }); + yield* writeTextFile(cwd, "src/app/game/[id]/index.tsx"); + yield* writeTextFile(cwd, "src/foo{bar}.ts"); + yield* writeTextFile(cwd, "src/main.ts"); + yield* writeTextFile(cwd, "src/notes.md"); + + const search = (query: string) => + searchWorkspaceEntries({ cwd, query, limit: 10 }).pipe( + Effect.map((result) => result.entries.map((entry) => entry.path)), + ); + + for (const query of ["game/[i", "game/[id]"]) { + expect(yield* search(query)).toContain("src/app/game/[id]/index.tsx"); + } + expect(yield* search("foo{bar}.ts")).toContain("src/foo{bar}.ts"); + expect((yield* search("*.{ts,tsx}")).toSorted()).toEqual([ + "src/app/game/[id]/index.tsx", + "src/foo{bar}.ts", + "src/main.ts", + ]); + expect((yield* search("*.{ts}")).toSorted()).toEqual(["src/foo{bar}.ts", "src/main.ts"]); + expect(yield* search("src/{main}.ts")).toEqual(["src/main.ts"]); + expect(yield* search("src/{foo{bar},notes}.md")).toEqual(["src/notes.md"]); + }), + ); + it.effect("excludes gitignored paths for git repositories", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true }); @@ -465,6 +507,11 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { yield* writeTextFile(cwd, "ignored.txt", "ignore me"); yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}"); + yield* writeTextFile(cwd, ".git/info/exclude", "info-excluded.txt\n"); + yield* writeTextFile(cwd, "info-excluded.txt", "ignore me"); + yield* writeTextFile(cwd, ".git/configured-excludes", "configured-excluded.txt\n"); + yield* git(cwd, ["config", "core.excludesFile", ".git/configured-excludes"]); + yield* writeTextFile(cwd, "configured-excluded.txt", "ignore me"); const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); const paths = result.entries.map((entry) => entry.path); @@ -472,6 +519,8 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect(paths).toContain("src"); expect(paths).toContain("src/keep.ts"); expect(paths).not.toContain("ignored.txt"); + expect(paths).not.toContain("info-excluded.txt"); + expect(paths).not.toContain("configured-excluded.txt"); expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false); }), @@ -496,6 +545,173 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); }), ); + + it.effect("indexes symlinked files and directories inside the workspace", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-" }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* fileSystem.symlink("src", path.join(cwd, "src-link")); + yield* fileSystem.symlink("src/index.ts", path.join(cwd, "index-link.ts")); + const symlinkEntries = [ + { kind: "directory", path: "src-link" }, + { kind: "file", path: "index-link.ts" }, + ]; + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entry of symlinkEntries) { + expect(searched.entries).toContainEqual(expect.objectContaining(entry)); + expect(listed.entries).toContainEqual(expect.objectContaining(entry)); + } + }), + ); + it.effect("skips symlinks that ignore rules hide or that leave the workspace", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const outside = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-outside-" }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* writeTextFile(cwd, ".ignore", "custom-link\n"); + yield* fileSystem.symlink("src", path.join(cwd, "custom-link")); + yield* fileSystem.symlink("src/index.ts", path.join(cwd, "tracked-link.ts")); + yield* fileSystem.symlink("src", path.join(cwd, "ignored-link")); + yield* fileSystem.symlink("src", path.join(cwd, "kept-link")); + yield* fileSystem.symlink(outside, path.join(cwd, "outside-link")); + yield* git(cwd, ["add", "tracked-link.ts"]); + yield* writeTextFile(cwd, ".gitignore", "tracked-link.ts\nignored-link\n"); + // A submodule path makes `git check-ignore` refuse the whole batch without --no-index. + const submodule = path.join(cwd, "vendor/sub"); + yield* writeTextFile(submodule, "a.ts", "export {};"); + yield* git(submodule, ["init"]); + yield* git(submodule, ["add", "a.ts"]); + yield* git(submodule, [ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit", + "-m", + "init", + ]); + yield* git(cwd, ["add", "vendor/sub"]); + yield* fileSystem.symlink("a.ts", path.join(submodule, "sublink.ts")); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).toContain("kept-link"); + expect(paths).toContain("vendor/sub/sublink.ts"); + expect(paths).not.toContain("custom-link"); + expect(paths).not.toContain("tracked-link.ts"); + expect(paths).not.toContain("ignored-link"); + expect(paths).not.toContain("outside-link"); + } + }), + ); + it.effect("lets the nearest .ignore rule decide a symlink, and git's rules still hide it", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, ".gitignore", "*keep*\n"); + yield* writeTextFile(cwd, ".ignore", "!*keep*\n*hide*\n"); + yield* writeTextFile(cwd, "sub/.ignore", "!*hide*\n"); + yield* writeTextFile(cwd, "keep-real.ts", "export {};"); + yield* writeTextFile(cwd, "sub/hide-real.ts", "export {};"); + yield* fileSystem.symlink("keep-real.ts", path.join(cwd, "keep-link.ts")); + yield* fileSystem.symlink("hide-real.ts", path.join(cwd, "sub/hide-link.ts")); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).toContain("sub/hide-link.ts"); + expect(paths).not.toContain("keep-link.ts"); + } + // The real files are shown or hidden by the same rules. + const listedPaths = listed.entries.map((entry) => entry.path); + expect(listedPaths).toContain("sub/hide-real.ts"); + expect(listedPaths).not.toContain("keep-real.ts"); + }), + ); + it.effect("matches .ignore rules against whole names and treats folder links as links", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* writeTextFile(cwd, ".gitignore", "blink\n"); + // `!link` must not re-include `blink`, and `folder-link/` does not apply to a link. + yield* writeTextFile(cwd, ".ignore", "!link\nfolder-link/\n"); + yield* fileSystem.symlink("src", path.join(cwd, "blink")); + yield* fileSystem.symlink("src", path.join(cwd, "folder-link")); + yield* writeTextFile(cwd, "sub/blink", "regular"); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).not.toContain("blink"); + expect(paths).not.toContain("sub/blink"); + expect(paths).toContain("folder-link"); + } + }), + ); + it.effect("finds a path inside a gitignored nested git worktree only by its exact path", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-worktree-", git: true }); + const env = { + ...process.env, + GIT_AUTHOR_NAME: "Test", + GIT_AUTHOR_EMAIL: "test@example.com", + GIT_COMMITTER_NAME: "Test", + GIT_COMMITTER_EMAIL: "test@example.com", + }; + yield* writeTextFile(cwd, ".gitignore", ".worktrees/\n"); + yield* git(cwd, ["add", ".gitignore"]); + yield* git(cwd, ["commit", "-m", "init"], env); + yield* git(cwd, ["worktree", "add", "-b", "x", ".worktrees/x"]); + yield* writeTextFile(cwd, ".worktrees/x/src/foo.py", "print(1)"); + const expected = [".worktrees/x/src/foo.py"]; + // Windows file names cannot contain a newline. + if ((yield* HostProcess.Platform) !== "win32") { + yield* git(cwd, ["worktree", "add", "--detach", ".worktrees/line\nname"]); + yield* writeTextFile(cwd, ".worktrees/line\nname/src/foo.py", "print(2)"); + expected.unshift(".worktrees/line\nname/src/foo.py"); + } + + const exact = yield* searchWorkspaceEntries({ + cwd, + query: "src/foo.py", + limit: 25, + kind: "file", + }); + expect(exact.entries.toSorted((a, b) => (a.path < b.path ? -1 : 1))).toEqual( + expected.map((path) => ({ path, kind: "file" })), + ); + + const partial = yield* searchWorkspaceEntries({ cwd, query: "src/fo", limit: 25 }); + for (const path of expected) { + expect(partial.entries.map((entry) => entry.path)).not.toContain(path); + } + }), + ); }); describe("searchContents", () => { @@ -534,6 +750,8 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { yield* writeTextFile(cwd, ".gitignore", "ignored.txt\n"); yield* writeTextFile(cwd, "src/keep.ts", "square\nSquare\n"); yield* writeTextFile(cwd, "ignored.txt", "Square\n"); + yield* writeTextFile(cwd, ".git/info/exclude", "info-excluded.txt\n"); + yield* writeTextFile(cwd, "info-excluded.txt", "Square\n"); const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; const result = yield* workspaceEntries.searchContents({ @@ -756,10 +974,17 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { if (created.ok) { const finder = created.value; finders += 1; - const scanFiles = finder.scanFiles.bind(finder); + // The synchronous rescan and grep wait on fff's picker lock on the event loop. finder.scanFiles = () => { + throw new Error("refresh must not rescan on the JS thread"); + }; + finder.grep = () => { + throw new Error("search must not grep on the JS thread"); + }; + const scanFilesAsync = finder.scanFilesAsync.bind(finder); + finder.scanFilesAsync = () => { rescans += 1; - return scanFiles(); + return scanFilesAsync(); }; const waitForIndexReady = finder.waitForIndexReady.bind(finder); finder.waitForIndexReady = (timeoutMs) => @@ -789,6 +1014,68 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect({ finders, rescans }).toEqual({ finders: 1, rescans: 1 }); }), ); + + it.effect("serves content search once a first scan that outlasted the wait finishes", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-slow-scan-" }); + yield* writeTextFile(cwd, "src/notes.ts", "const needle = 1;\n"); + // Real finders; only the initial wait and the progress it reads report a scan still running. + let scanning = true; + let finders = 0; + let settle = (): Promise => Promise.resolve(); + const createFinder = FileFinder.create.bind(FileFinder); + vi.spyOn(FileFinder, "create").mockImplementation((options) => { + const created = createFinder(options); + if (!created.ok) return created; + const finder = created.value; + finders += 1; + const waitForIndexReady = finder.waitForIndexReady.bind(finder); + settle = () => waitForIndexReady(15_000); + finder.waitForIndexReady = (timeoutMs) => + scanning ? Promise.resolve({ ok: true, value: false }) : waitForIndexReady(timeoutMs); + const getScanProgress = finder.getScanProgressAsync.bind(finder); + finder.getScanProgressAsync = async () => { + const progress = await getScanProgress(); + return scanning && progress.ok + ? { + ok: true, + value: { ...progress.value, isScanning: true, isWarmupComplete: false }, + } + : progress; + }; + return created; + }); + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searchNeedle = workspaceEntries + .searchContents({ + cwd, + query: "needle", + limit: 100, + caseSensitive: true, + wholeWord: false, + useRegex: false, + }) + .pipe( + Effect.map((result): unknown => result.matches.map((match) => match.path)), + Effect.catchTags({ + WorkspaceSearchIndexScanTimedOut: (error) => Effect.succeed(error._tag), + }), + ); + + const whileScanning = yield* Effect.all([searchNeedle, searchNeedle], { + concurrency: "unbounded", + }); + scanning = false; + yield* Effect.promise(() => settle()); + const afterScan = yield* searchNeedle; + + expect({ whileScanning, afterScan, finders }).toEqual({ + whileScanning: ["WorkspaceSearchIndexScanTimedOut", "WorkspaceSearchIndexScanTimedOut"], + afterScan: ["src/notes.ts"], + finders: 1, + }); + }), + ); }); describe("browse", () => { diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index 7b2a0aa0a7..ad1d2c2ae0 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -179,7 +179,6 @@ export const make = Effect.gen(function* () { function* ( cause: | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed - | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed, ) { yield* Effect.logWarning("Failed to refresh workspace search index", { @@ -197,7 +196,6 @@ export const make = Effect.gen(function* () { Effect.provide(workspaceSearchIndexes.get(indexKey)), Effect.catchTags({ WorkspaceSearchIndexCreateFailed: recoverRefreshFailure, - WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure, WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure, }), ); @@ -260,7 +258,7 @@ export const make = Effect.gen(function* () { const normalizedQuery = normalizeSearchQuery(input.query, { trimLeadingPattern: /^[@./]+/, }); - return yield* Effect.gen(function* () { + const result = yield* Effect.gen(function* () { const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex; return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly); }).pipe( @@ -270,9 +268,90 @@ export const make = Effect.gen(function* () { ), ), ); + if (input.kind === "directory" || input.imageOnly) return result; + const worktreeFiles = yield* findNestedWorktreeFiles( + normalizedCwd, + input.query, + result.entries, + ); + if (worktreeFiles.length === 0) return result; + const entries = [...worktreeFiles, ...result.entries]; + return { + entries: entries.slice(0, input.limit), + truncated: result.truncated || entries.length > input.limit, + }; }, ); + // The index skips gitignored folders, where agents often put worktrees (`.worktrees/x`). + // A path relative to such a worktree is found only when it names an existing file exactly. + const findNestedWorktreeFiles = Effect.fn("WorkspaceEntries.findNestedWorktreeFiles")(function* ( + cwd: string, + query: string, + indexed: ReadonlyArray, + ) { + const relativePath = query.trim().replaceAll("\\", "/"); + if ( + !relativePath.includes("/") || + relativePath.endsWith("/") || + path.isAbsolute(relativePath) || + isWindowsAbsolutePath(relativePath) || + relativePath.split("/").some((segment) => segment === "..") || + indexed.some( + (entry) => + entry.kind === "file" && + (entry.path === relativePath || entry.path.endsWith(`/${relativePath}`)), + ) + ) { + return []; + } + const listWorktrees = (args: ReadonlyArray) => + vcsProcess + .run({ + operation: "WorkspaceEntries.listWorktrees", + command: "git", + args: ["worktree", "list", "--porcelain", ...args], + cwd, + allowNonZeroExit: true, + timeoutMs: 5_000, + }) + .pipe( + Effect.map((result) => (result.exitCode === 0 ? result.stdout : undefined)), + Effect.orElseSucceed(() => undefined), + ); + // Only NUL framing keeps a newline in a worktree path. Pre-2.36 Git rejects `-z`. + const listed = + (yield* listWorktrees(["-z"])) ?? (yield* listWorktrees([]))?.replaceAll("\n", "\0"); + if (listed === undefined) return []; + const realCwd = yield* Effect.promise(() => NodeFSP.realpath(cwd).catch(() => cwd)); + const worktreeRoots = listed.split("\0\0").flatMap((record) => { + const fields = record.split("\0"); + const worktree = fields.find((field) => field.startsWith("worktree ")); + // A `prunable` record's directory is gone; another checkout may now sit there. + if (worktree === undefined || fields.some((field) => field.startsWith("prunable"))) return []; + const root = worktree.slice("worktree ".length); + const relativeRoot = path.relative(realCwd, root); + return relativeRoot === "" || + relativeRoot === ".." || + relativeRoot.startsWith(`..${path.sep}`) || + path.isAbsolute(relativeRoot) + ? [] + : [relativeRoot.split(path.sep).join("/")]; + }); + const matches = yield* Effect.promise(() => + Promise.all( + worktreeRoots.map(async (relativeRoot) => { + const candidate = `${relativeRoot}/${relativePath}`; + const stat = await NodeFSP.stat(path.join(realCwd, candidate)).catch(() => null); + return stat?.isFile() ? candidate : null; + }), + ), + ); + return matches + .filter((candidate) => candidate !== null) + .map((candidate): ProjectEntry => ({ path: candidate, kind: "file" })); + }); + const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn( "WorkspaceEntries.searchContents", )(function* (input) { @@ -502,9 +581,13 @@ export const make = Effect.gen(function* () { }) .pipe(Effect.orElseSucceed(() => undefined)); if (!result || result.exitCode !== 0) return { files: [], truncated: false }; + // Filter before the cap so files sorting past it stay reachable by search. + const query = input.query?.toLowerCase() ?? ""; const paths = result.stdout .split("\0") - .filter((entry) => entry.length > 0 && !entry.endsWith("/")) + .filter( + (entry) => entry.length > 0 && !entry.endsWith("/") && entry.toLowerCase().includes(query), + ) .toSorted(); const files = yield* Effect.promise(() => Promise.all( diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index 3306e420b3..bc22117ba7 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -12,6 +12,7 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; +import { makeFakeWslHost } from "../testUtils/fakeWsl.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as KnownWorkspaces from "./KnownWorkspaces.ts"; @@ -43,6 +44,11 @@ const injectShortReads = Effect.fn("injectShortReads")(function* (target: string yield* Effect.addFinalizer(() => Effect.sync(() => open.mockImplementation(native.open))); }); +const whitespaceFilePaths = + HostProcess.Platform.defaultValue() === "win32" + ? [" report.txt"] + : [" report.txt", "report.txt ", "\treport.txt\t", " "]; + const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-"; const layerKnownWorkspacesTest = Layer.mock(KnownWorkspaces.KnownWorkspaces)({ assertContains: (cwd) => @@ -91,6 +97,14 @@ const writeTextFile = Effect.fn("writeTextFile")(function* ( yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); }); +const makeWslHost = Effect.gen(function* () { + const { mountRoot, underWsl } = yield* makeFakeWslHost; + const service = yield* underWsl( + WorkspaceFileSystem.make.pipe(Effect.provide(layerKnownWorkspacesTest)), + ); + return { mountRoot, service, underWsl }; +}); + it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (it) => { describe("getMetadata", () => { it.effect( @@ -176,6 +190,31 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i expect(statted).toEqual([]); }), ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "reports a Windows drive path under WSL as the file it maps to", + () => + Effect.gen(function* () { + const { mountRoot, service, underWsl } = yield* makeWslHost; + yield* writeTextFile(mountRoot, "c/Users/me/Documents/notes.md", "# Notes\n"); + + const { entries } = yield* underWsl( + service.getMetadata({ + paths: [ + "C:\\Users\\me\\Documents\\notes.md", + "C:/Users/me/Documents/notes.md", + "C:/Users/me/Documents/notes\u0000.md", + ], + }), + ); + + expect(entries).toEqual([ + { kind: "file", byteLength: 8 }, + { kind: "file", byteLength: 8 }, + null, + ]); + }), + ); }); describe("readFile", () => { @@ -196,6 +235,26 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i byteLength: 26, truncated: false, }); + + const bomContents = "\uFEFFexport const answer = 42;\n"; + yield* writeTextFile(cwd, "bom.ts", bomContents); + const bomRead = yield* workspaceFileSystem.readFile({ cwd, relativePath: "bom.ts" }); + yield* workspaceFileSystem.writeFile({ + cwd, + relativePath: "bom.ts", + contents: bomRead.contents.replace("42", "43"), + }); + const fs = yield* FileSystem.FileSystem; + const saved = yield* fs.readFile(`${cwd}/bom.ts`); + expect([...saved]).toEqual([...new TextEncoder().encode(bomContents.replace("42", "43"))]); + + yield* writeTextFile(cwd, "report.txt", "ordinary file"); + for (const relativePath of whitespaceFilePaths) { + yield* writeTextFile(cwd, relativePath, "whitespace file"); + const read = yield* workspaceFileSystem.readFile({ cwd, relativePath }); + expect(read.contents).toBe("whitespace file"); + expect(read.relativePath).toBe(relativePath); + } }), ); @@ -250,28 +309,38 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i byteLength: 9, truncated: false, }); + + for (const relativePath of whitespaceFilePaths) { + yield* writeTextFile(outsideDir, relativePath, "whitespace file"); + const requestedPath = path.join(outsideDir, relativePath); + const read = yield* workspaceFileSystem.readFile({ cwd, relativePath: requestedPath }); + expect(read.contents).toBe("whitespace file"); + expect(read.relativePath).toBe(requestedPath); + } }), ); - it.effect("reads ~/ paths from the server home outside the workspace", () => - Effect.gen(function* () { - const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; - const cwd = yield* makeTempDir; - const home = yield* makeTempDir; - yield* writeTextFile(home, ".claude/CLAUDE.md", "# Notes\n"); - yield* writeTextFile(cwd, "~/.claude/CLAUDE.md", "Workspace decoy\n"); - - const result = yield* workspaceFileSystem - .readFile({ cwd, relativePath: "~/.claude/CLAUDE.md" }) - .pipe(Effect.provideService(HostProcess.HomeDirectory, home)); - - expect(result).toEqual({ - relativePath: "~/.claude/CLAUDE.md", - contents: "# Notes\n", - byteLength: 8, - truncated: false, - }); - }), + it.effect.each(["~/.claude/CLAUDE.md", "~\\.claude/CLAUDE.md"])( + "reads %s from the server home outside the workspace", + (relativePath) => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; + const cwd = yield* makeTempDir; + const home = yield* makeTempDir; + yield* writeTextFile(home, ".claude/CLAUDE.md", "# Notes\n"); + yield* writeTextFile(cwd, "~/.claude/CLAUDE.md", "Workspace decoy\n"); + + const result = yield* workspaceFileSystem + .readFile({ cwd, relativePath }) + .pipe(Effect.provideService(HostProcess.HomeDirectory, home)); + + expect(result).toEqual({ + relativePath, + contents: "# Notes\n", + byteLength: 8, + truncated: false, + }); + }), ); it.effect("does not read server state files", () => @@ -290,6 +359,14 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i const error = yield* workspaceFileSystem.readFile(input).pipe(Effect.flip); expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError); } + const metadata = yield* workspaceFileSystem.getMetadata({ + paths: [ + path.join(config.secretsDir, "example.bin"), + path.join(config.stateDir, "statev2.sqlite"), + config.stateDir, + ], + }); + expect(metadata.entries).toEqual([null, null, { kind: "directory" }]); }), ); @@ -322,6 +399,24 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i }), ); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "reads a Windows drive path under WSL from where wslpath mounts it", + () => + Effect.gen(function* () { + const { mountRoot, service, underWsl } = yield* makeWslHost; + const cwd = yield* makeTempDir; + yield* writeTextFile(mountRoot, "c/Users/me/Documents/notes.md", "# Notes\n"); + + for (const relativePath of [ + "C:\\Users\\me\\Documents\\notes.md", + "C:/Users/me/Documents/notes.md", + ]) { + const result = yield* underWsl(service.readFile({ cwd, relativePath })); + expect(result).toMatchObject({ contents: "# Notes\n", truncated: false }); + } + }), + ); + it.effect("refuses a network path outside the workspace", () => Effect.gen(function* () { const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; @@ -449,14 +544,17 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i }), ); - it.effect("rejects binary files without leaking their contents into the error", () => + it.effect.each([ + { name: "a NUL byte", bytes: [0x61, 0, 0x62] }, + { name: "invalid UTF-8", bytes: [0x63, 0x61, 0x66, 0xe9] }, + ])("rejects files with $name without leaking their contents", ({ bytes }) => Effect.gen(function* () { const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const cwd = yield* makeTempDir; const absolutePath = path.join(cwd, "asset.bin"); - yield* fileSystem.writeFile(absolutePath, Uint8Array.from([0x61, 0, 0x62])); + yield* fileSystem.writeFile(absolutePath, Uint8Array.from(bytes)); const error = yield* workspaceFileSystem .readFile({ cwd, relativePath: "asset.bin" }) @@ -552,6 +650,21 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i expect(yield* fileSystem.readFileString(path.join(cwd, "src/main.ts"))).toBe( "export const edited = true;\n", ); + + yield* writeTextFile(cwd, "report.txt", "ordinary file"); + for (const relativePath of whitespaceFilePaths) { + yield* writeTextFile(cwd, relativePath, "whitespace file"); + const written = yield* workspaceFileSystem.writeFile({ + cwd, + relativePath, + contents: "edited", + }); + expect(yield* fileSystem.readFileString(path.join(cwd, "report.txt"))).toBe( + "ordinary file", + ); + expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("edited"); + expect(written.relativePath).toBe(relativePath); + } }).pipe( Effect.provide( Layer.fresh(WorkspaceFileSystem.layer).pipe( @@ -574,17 +687,13 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; - const error = yield* workspaceFileSystem - .writeFile({ - cwd, - relativePath: "../escape.md", - contents: "# nope\n", - }) - .pipe(Effect.flip); + for (const relativePath of ["../escape.md", "../escape.md ", " folder/../../escape.md"]) { + const error = yield* workspaceFileSystem + .writeFile({ cwd, relativePath, contents: "# nope\n" }) + .pipe(Effect.flip); - expect(error.message).toContain( - "Workspace file path must be relative to the project root: ../escape.md", - ); + expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError); + } const escapedPath = path.resolve(cwd, "..", "escape.md"); const escapedStat = yield* fileSystem diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts index 489fedc2dc..494472e4ce 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.ts @@ -19,6 +19,7 @@ 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 ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as Schema from "effect/Schema"; import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts"; @@ -26,6 +27,7 @@ import * as KnownWorkspaces from "./KnownWorkspaces.ts"; import * as WorkspaceEntries from "./WorkspaceEntries.ts"; import * as WorkspacePaths from "./WorkspacePaths.ts"; import { fileHeaderMimeType } from "./fileHeaderMimeType.ts"; +import { toWslDrivePath } from "./wslDrivePath.ts"; const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024; @@ -133,6 +135,27 @@ export class WorkspaceFileSystem extends Context.Service< } >()("t3/workspace/WorkspaceFileSystem") {} +const UTF8_BOM = "\uFEFF"; + +async function startsWithUtf8Bom(filePath: string): Promise { + const handle = await NodeFSP.open( + filePath, + // O_NONBLOCK keeps a FIFO with no writer from hanging the save. + NodeFS.constants.O_RDONLY | + (NodeFS.constants.O_NOFOLLOW ?? 0) | + (NodeFS.constants.O_NONBLOCK ?? 0), + ).catch(() => null); + if (!handle) return false; + try { + const { bytesRead, buffer } = await handle.read(Buffer.alloc(3), 0, 3, 0); + return bytesRead === 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf; + } catch { + return false; + } finally { + await handle.close(); + } +} + /** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -141,14 +164,24 @@ export const make = Effect.gen(function* () { const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces; const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; const isServerInternalPath = yield* makeIsServerInternalPath; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + const toHostPath = (requestedPath: string) => + toWslDrivePath(requestedPath).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) { - const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory); + const expandedPath = expandHomePath( + yield* toHostPath(requestedPath), + yield* HostProcess.HomeDirectory, + ); // Chips ask as soon as an agent's message renders, and touching a network // path makes Windows sign in to its host with the user's NTLM credentials. if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null; const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option); - if (stat._tag === "None") return null; + // Server state files answer like missing paths, as readFile refuses them. + if (stat._tag === "None" || (yield* isServerInternalPath(expandedPath))) return null; if (stat.value.type === "Directory") return { kind: "directory" } as const; if (stat.value.type !== "File") return { kind: "other" } as const; let mimeType: string | undefined; @@ -226,10 +259,11 @@ export const make = Effect.gen(function* () { const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* ( input: ProjectReadFileInput, ) { - const requestedPath = input.relativePath.trim(); - const hostPath = requestedPath.startsWith("~/") - ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory) - : requestedPath; + const requestedPath = input.relativePath; + const hostPath = + requestedPath.startsWith("~/") || requestedPath.startsWith("~\\") + ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory) + : yield* toHostPath(requestedPath); if ( isNetworkPath(hostPath) && !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd)) @@ -423,22 +457,22 @@ export const make = Effect.gen(function* () { offset += bytesRead; } const fileBytes = buffer.subarray(0, offset); - if (fileBytes.includes(0)) { - return yield* new WorkspaceBinaryFileError({ + const truncated = stat.size > PROJECT_READ_FILE_MAX_BYTES; + const binaryFileError = () => + new WorkspaceBinaryFileError({ workspaceRoot: input.cwd, relativePath: input.relativePath, resolvedPath: realTargetPath, }); - } - - const truncated = stat.size > PROJECT_READ_FILE_MAX_BYTES; - return { - relativePath: target.relativePath, - // Streaming decode drops a character the byte limit split, instead of ending in U+FFFD. - contents: new TextDecoder("utf-8").decode(fileBytes, { stream: truncated }), - byteLength: stat.size, - truncated, - }; + if (fileBytes.includes(0)) return yield* binaryFileError(); + // Fatal decoding rejects invalid UTF-8, since U+FFFD contents would corrupt the file on save. + // Streaming decode drops a character the byte limit split, instead of rejecting it. + const contents = yield* Effect.try({ + try: () => + new TextDecoder("utf-8", { fatal: true }).decode(fileBytes, { stream: truncated }), + catch: binaryFileError, + }); + return { relativePath: target.relativePath, contents, byteLength: stat.size, truncated }; }), (handle) => handle === null @@ -549,6 +583,12 @@ export const make = Effect.gen(function* () { const replacesFile = yield* fileSystem .exists(realTargetPath) .pipe(Effect.orElseSucceed(() => false)); + // readFile decodes the BOM away, so an editor save would otherwise drop it from the file. + const keepsBom = + replacesFile && + !input.contents.startsWith(UTF8_BOM) && + (yield* Effect.promise(() => startsWithUtf8Bom(realTargetPath))); + const contents = keepsBom ? UTF8_BOM + input.contents : input.contents; yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe( Effect.mapError( @@ -566,7 +606,7 @@ export const make = Effect.gen(function* () { yield* Effect.tryPromise({ // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW. try: () => - NodeFSP.writeFile(realTargetPath, input.contents, { + NodeFSP.writeFile(realTargetPath, contents, { flag: NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | diff --git a/apps/server/src/workspace/WorkspacePaths.ts b/apps/server/src/workspace/WorkspacePaths.ts index ea183ed43e..e630643c71 100644 --- a/apps/server/src/workspace/WorkspacePaths.ts +++ b/apps/server/src/workspace/WorkspacePaths.ts @@ -175,15 +175,14 @@ const make = Effect.gen(function* () { const resolveRelativePathWithinRoot: WorkspacePaths["Service"]["resolveRelativePathWithinRoot"] = Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) { - const normalizedInputPath = input.relativePath.trim(); - if (path.isAbsolute(normalizedInputPath)) { + if (path.isAbsolute(input.relativePath)) { return yield* new WorkspacePathOutsideRootError({ workspaceRoot: input.workspaceRoot, relativePath: input.relativePath, }); } - const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath); + const absolutePath = path.resolve(input.workspaceRoot, input.relativePath); // Only the host separator becomes `/`: on POSIX `\` is a file name character. const relativeToRoot = path .relative(input.workspaceRoot, absolutePath) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 2c41e4ed0b..8c42fcf52a 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -4,13 +4,27 @@ import { type GrepCursor, type GrepOptions, type GrepResult, + type WatchEvent, } from "@ff-labs/fff-node"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { afterEach, expect, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { PROJECT_FAVICON_EXTENSIONS, isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import { ChildProcessSpawner } from "effect/process"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts"; +const testLayer = VcsProcess.layer.pipe(Layer.provideMerge(NodeServices.layer)); + afterEach(() => { vi.restoreAllMocks(); }); @@ -28,17 +42,122 @@ function fileItem(relativePath: string): FileItem { }; } -it.effect("filters image searches before applying the result limit", () => +it.live("image searches match the image subset of a file search without fetching every file", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const vcsProcess = yield* VcsProcess.VcsProcess; + const writeFiles = Effect.fn(function* (root: string, relativePaths: ReadonlyArray) { + for (const relativePath of relativePaths) { + yield* fileSystem.makeDirectory(path.dirname(path.join(root, relativePath)), { + recursive: true, + }); + yield* fileSystem.writeFileString(path.join(root, relativePath), ""); + yield* fileSystem.utimes(path.join(root, relativePath), 0, 0); + } + }); + + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-image-search-" }); + yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd }); + yield* fileSystem.writeFileString(path.join(cwd, ".git/info/exclude"), "hidden/\n"); + yield* writeFiles(cwd, [ + ...Array.from({ length: 220 }, (_, index) => `assets/source-${index}.ts`), + ...PROJECT_FAVICON_EXTENSIONS.flatMap((extension) => [ + `assets/logo${extension}`, + `other/logo${extension.toUpperCase()}`, + ]), + "assets/logo.ts", + "assets/logotype.png", + "assetss/logotype.png", + "assets/images/logo.PNG", + "assets/foo{bar}.png", + "assets/[id].png", + "hidden/logo.png", + ]); + + const fileSearch = vi.spyOn(FileFinder.prototype, "fileSearchAsync"); + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + yield* searchIndex.search("", 200, undefined, true); + const nativeResult = yield* Effect.promise( + (): ReturnType => fileSearch.mock.results[0]?.value, + ); + if (!nativeResult.ok) return yield* Effect.die(nativeResult.error); + expect(nativeResult.value.items.length).toBeLessThanOrEqual(201); + + // The image glob must not change fff's parse of fuzzy paths, globs, negations or locations. + for (const query of [ + "", + "logo", + "lgo", + "*.png", + "!*.png", + "assets/**", + "!assets/", + "assets*/", + "/assets", + "assets/", + "logo:12", + "/assets/logotype.png", + "assets/images/", + "logo *.svg !other", + "foo{bar}.png", + "[id].png", + "*.{png,svg}", + "hidden/", + ]) { + const ordinary = yield* searchIndex.search(query, 1000, "file"); + const expected = ordinary.entries.filter((entry) => isProjectFaviconPath(entry.path)); + for (const limit of [1, 200]) { + const images = yield* searchIndex.search(query, limit, "directory", true); + expect(images, `query=${query} limit=${limit}`).toEqual({ + entries: expected.slice(0, limit), + truncated: expected.length > limit, + }); + } + } + + // Past 15,000 matches fff drops its filename fallback, which the image glob would otherwise + // reorder: "x/logo/logo.png" must keep its place relative to "a/xxlogo.png". + const largeCwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-image-rank-" }); + yield* writeFiles(largeCwd, [ + ...Array.from({ length: 14_998 }, (_, index) => `b/logo-${index}.png`), + "x/logo/source.ts", + "a/xxlogo.png", + "x/logo/logo.png", + ]); + const largeIndex = yield* WorkspaceSearchIndex.make(largeCwd); + const pairPaths = ["a/xxlogo.png", "x/logo/logo.png"]; + const ordinary = yield* largeIndex.search("logo", 20_000, "file"); + const images = yield* largeIndex.search("logo", 20_000, "file", true); + expect(images.entries).toHaveLength(15_000); + expect(images.entries.filter((entry) => pairPaths.includes(entry.path))).toEqual( + ordinary.entries.filter((entry) => pairPaths.includes(entry.path)), + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.effect("fetches past a first page of Git-ignored results", () => Effect.scoped( Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-ignored-" }); + const vcsProcess = yield* VcsProcess.VcsProcess; + yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd }); + yield* fs.writeFileString(path.join(cwd, ".git", "info", "exclude"), "hidden/\n"); + yield* fs.makeDirectory(path.join(cwd, "hidden")); + yield* fs.writeFileString(path.join(cwd, "hidden", "a.ts"), ""); + const items = [ - ...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)), - fileItem("public/icon.svg"), + fileItem("hidden/a.ts"), + fileItem("hidden/b.ts"), + fileItem("hidden/c.ts"), + fileItem("src/a.ts"), ]; - const fileSearch = vi.fn(() => ({ + const fileSearch = vi.fn(async (_query: string, options?: { pageSize?: number }) => ({ ok: true as const, value: { - items, + items: items.slice(0, options?.pageSize), scores: [], totalMatched: items.length, totalFiles: items.length, @@ -47,20 +166,51 @@ it.effect("filters image searches before applying the result limit", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - fileSearch, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: fileSearch, } as unknown as FileFinder; vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project"); - const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true); - const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true); + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const result = yield* searchIndex.search("a", 1, "file", false); - expect(resultWithoutKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]); - expect(resultWithDirectoryKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]); - expect(fileSearch).toHaveBeenCalledTimes(2); - expect(fileSearch).toHaveBeenCalledWith("", { pageSize: 25_002 }); + expect(result).toEqual({ entries: [{ kind: "file", path: "src/a.ts" }], truncated: false }); }), - ), + ).pipe(Effect.provide(testLayer)), +); + +// A backslash is a file name character on Linux and macOS, so only Windows may treat it as a separator. +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "keeps a backslash in a POSIX folder name as part of the search result path", + () => + Effect.scoped( + Effect.gen(function* () { + const items = [fileItem("dir\\one/report.txt")]; + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: vi.fn(async () => ({ + ok: true as const, + value: { items, scores: [], totalMatched: 1, totalFiles: 1 }, + })), + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); + + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project"); + const result = yield* searchIndex.search("report", 50, "file"); + + expect(result.entries).toEqual([{ kind: "file", path: "dir\\one/report.txt" }]); + }), + ).pipe(Effect.provide(testLayer)), ); it.effect("continues whole-word searches after a filtered grep page", () => @@ -99,7 +249,7 @@ it.effect("continues whole-word searches after a filtered grep page", () => filteredFileCount: 1, nextCursor: cursor, }); - const grep = vi.fn((_query: string, options?: GrepOptions) => + const grep = vi.fn(async (_query: string, options?: GrepOptions) => options?.cursor ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) } : { @@ -110,7 +260,12 @@ it.effect("continues whole-word searches after a filtered grep page", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - grep, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), + grepAsync: grep, } as unknown as FileFinder; vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); @@ -137,5 +292,459 @@ it.effect("continues whole-word searches after a filtered grep page", () => expect(grep).toHaveBeenCalledTimes(2); expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor); }), - ), + ).pipe(Effect.provide(testLayer)), +); + +it.live("answers content searches with git grep while a slow content index builds", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const vcsProcess = yield* VcsProcess.VcsProcess; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-" }); + yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd }); + yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored.txt\n"); + yield* fileSystem.makeDirectory(path.join(cwd, "src")); + yield* fileSystem.writeFileString( + path.join(cwd, "src/a.ts"), + "const Needle = 1;\r\nneedles(a.b);\nnone\n", + ); + yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "needle\n"); + // fff leaves out what `.ignore` excludes, so git results must leave it out too. + yield* fileSystem.writeFileString(path.join(cwd, ".ignore"), "out/\n"); + yield* fileSystem.makeDirectory(path.join(cwd, "out/deep"), { recursive: true }); + yield* fileSystem.writeFileString(path.join(cwd, "out/deep/g.txt"), "needle\n"); + + let isWarmupComplete = false; + const grep = vi.fn(async () => ({ + ok: true as const, + value: { + items: [], + totalMatched: 0, + totalFilesSearched: 0, + totalFiles: 0, + filteredFileCount: 0, + nextCursor: null, + } satisfies GrepResult, + })); + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })), + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false, isWarmupComplete }, + }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), + grepAsync: grep, + } as unknown as FileFinder; + const noPcreFinder = { + ...finder, + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create") + .mockReturnValueOnce({ ok: true, value: finder }) + .mockReturnValueOnce({ ok: true, value: noPcreFinder }) + .mockReturnValueOnce({ ok: true, value: noPcreFinder }) + .mockReturnValueOnce({ ok: true, value: noPcreFinder }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content"); + const search = (input: Partial[0]>) => + searchIndex.searchContents({ + query: "needle", + limit: 10, + caseSensitive: false, + wholeWord: false, + useRegex: false, + ...input, + }); + + expect(yield* search({})).toEqual({ + matches: [ + { + path: "src/a.ts", + lineNumber: 1, + lineContent: "const Needle = 1;", + matchRanges: [{ start: 6, end: 12 }], + }, + { + path: "src/a.ts", + lineNumber: 2, + lineContent: "needles(a.b);", + matchRanges: [{ start: 0, end: 6 }], + }, + ], + truncated: false, + }); + expect((yield* search({ caseSensitive: true, wholeWord: true })).matches).toEqual([]); + expect((yield* search({ query: "a.b" })).matches.map((match) => match.matchRanges)).toEqual([ + [{ start: 8, end: 11 }], + ]); + expect( + (yield* search({ query: "ne+dles?", useRegex: true })).matches.map( + (match) => match.matchRanges, + ), + ).toEqual([[{ start: 6, end: 12 }], [{ start: 0, end: 7 }]]); + expect( + (yield* search({ query: "[a-z]e", useRegex: true })).matches.map( + (match) => match.matchRanges, + ), + ).toEqual([ + [{ start: 4, end: 6 }], + [ + { start: 6, end: 8 }, + { start: 10, end: 12 }, + ], + [ + { start: 0, end: 2 }, + { start: 4, end: 6 }, + ], + [{ start: 2, end: 4 }], + ]); + const invalid = yield* search({ query: "a.b(", useRegex: true }); + expect(invalid.matches).toEqual([]); + expect(invalid.regexFallbackError).toBeDefined(); + expect(yield* search({ limit: 1 })).toMatchObject({ truncated: true }); + expect(grep).not.toHaveBeenCalled(); + + // When git cannot give regex results or their ranges, fff answers once ready instead. + const failingGitIndex = ( + failingArgument: string, + stderr: string, + output: { readonly exitCode: number; readonly stdout: string } = { + exitCode: 128, + stdout: "", + }, + ) => + WorkspaceSearchIndex.make(cwd, "content").pipe( + Effect.provideService( + VcsProcess.VcsProcess, + VcsProcess.VcsProcess.of({ + run: (input) => + input.args.includes(failingArgument) + ? Effect.succeed({ + exitCode: ChildProcessSpawner.ExitCode(output.exitCode), + stdout: output.stdout, + stderr, + stdoutTruncated: output.exitCode === 0, + stderrTruncated: false, + }) + : vcsProcess.run(input), + }), + ), + ); + const regexInput = { + query: "ne+dles?", + limit: 10, + caseSensitive: false, + wholeWord: true, + useRegex: true, + }; + const noPcreIndex = yield* failingGitIndex( + "-P", + "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE\n", + ); + expect((yield* noPcreIndex.searchContents(regexInput)).regexFallbackError).toBeUndefined(); + expect(grep).toHaveBeenCalledTimes(1); + const noRangesIndex = yield* failingGitIndex("-o", "fatal: unexpected failure\n"); + yield* noRangesIndex.searchContents(regexInput); + expect(grep).toHaveBeenCalledTimes(2); + // Ranges output cut off after line 1: line 2 is left out and the result says so. + const cutRangesIndex = yield* failingGitIndex("-o", "", { + exitCode: 0, + stdout: "src/a.ts\u00001\u00007\u0000Needle\nsrc/a.ts\u00002", + }); + expect(yield* cutRangesIndex.searchContents(regexInput)).toEqual({ + matches: [ + { + path: "src/a.ts", + lineNumber: 1, + lineContent: "const Needle = 1;", + matchRanges: [{ start: 6, end: 12 }], + }, + ], + truncated: true, + }); + + isWarmupComplete = true; + yield* search({}); + expect(grep).toHaveBeenCalledTimes(3); + expect(finder.destroy).not.toHaveBeenCalled(); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +function fakeSymlinkFinder( + directories: ReadonlyArray, + options: { + readonly indexed?: ReadonlyArray<{ + readonly path: string; + readonly kind: "file" | "directory"; + }>; + readonly watchFailures?: number; + } = {}, +) { + const watchers: Array<(events: ReadonlyArray) => void> = []; + let watchFailures = options.watchFailures ?? 0; + // fff's pageIndex is an offset into the results, not a page number. + const directorySearch = vi.fn( + async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => { + const offset = searchOptions?.pageIndex ?? 0; + const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100)); + return { + ok: true as const, + value: { + items: items.map((relativePath) => ({ relativePath })), + totalMatched: directories.length, + }, + }; + }, + ); + const indexedItems = (options.indexed ?? []).map((entry) => ({ + type: entry.kind, + item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) }, + })); + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + // fff's isScanning waits on the picker lock on the JS thread. + isScanning: () => { + throw new Error("isScanning must not run on the JS thread"); + }, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + // fff's watch waits on the picker lock on the JS thread. + watch: () => { + throw new Error("watch must not run on the JS thread"); + }, + watchAsync: async (callback: (events: ReadonlyArray) => void) => { + if (watchFailures > 0) { + watchFailures -= 1; + return { ok: false as const, error: "File system watcher is not ready" }; + } + watchers.push(callback); + return { ok: true as const, value: () => undefined }; + }, + directorySearchAsync: directorySearch, + fileSearchAsync: async () => { + const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : [])); + return { ok: true as const, value: { items, scores: [], totalMatched: items.length } }; + }, + mixedSearchAsync: async () => ({ + ok: true as const, + value: { items: indexedItems, totalMatched: indexedItems.length }, + }), + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); + return { + directorySearch, + notifyWatchers: (events: ReadonlyArray) => + watchers.forEach((watcher) => watcher(events)), + }; +} + +const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) => + searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path))); + +it.effect("reads symlinks again after the watcher reports a change", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts")); + const { directorySearch, notifyWatchers } = fakeSymlinkFinder([]); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const concurrent = yield* Effect.all( + Array.from({ length: 8 }, () => listedPaths(searchIndex)), + { concurrency: "unbounded" }, + ); + yield* fileSystem.remove(path.join(cwd, "old-link.ts")); + yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts")); + const beforeNotice = yield* listedPaths(searchIndex); + // Editing a file cannot move a link, so it does not cost a rescan. + notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]); + const afterEdit = yield* listedPaths(searchIndex); + notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]); + const afterNotice = yield* listedPaths(searchIndex); + // fff reports a link replaced in place as modified. + yield* fileSystem.remove(path.join(cwd, "new-link.ts")); + yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts")); + notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]); + const afterReplace = yield* listedPaths(searchIndex); + + expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"])); + expect(beforeNotice).toEqual(["old-link.ts"]); + expect(afterEdit).toEqual(["old-link.ts"]); + expect(afterNotice).toEqual(["new-link.ts"]); + expect(afterReplace).toEqual([]); + expect(directorySearch).toHaveBeenCalledTimes(3); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("answers from the last symlink scan while a slow rescan runs", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts")); + const { notifyWatchers } = fakeSymlinkFinder([]); + // Holding git's ignore check open keeps the rescan from finishing. + const gate = yield* Deferred.make(); + let holdIgnoreChecks = false; + const vcsProcess = yield* VcsProcess.VcsProcess; + const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe( + Effect.provideService(VcsProcess.VcsProcess, { + ...vcsProcess, + run: (input) => + holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored" + ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input))) + : vcsProcess.run(input), + }), + ); + expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]); + + holdIgnoreChecks = true; + yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts")); + notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]); + const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex)); + yield* TestClock.adjust("1 second"); + expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]); + + yield* Deferred.succeed(gate, undefined); + expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("keeps symlinks once the watcher subscribes after starting late", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts")); + const { directorySearch } = fakeSymlinkFinder([], { watchFailures: 2 }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const scansAfterRound: number[] = []; + for (let round = 0; round < 5; round += 1) { + expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]); + expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]); + scansAfterRound.push(directorySearch.mock.calls.length); + yield* TestClock.adjust("1 minute"); + } + + // An unwatched scan serves reads only briefly; the third has a watcher and is kept. + expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect( + "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones", + () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" }); + yield* fileSystem.makeDirectory(path.join(cwd, "src")); + yield* fileSystem.symlink("src", path.join(cwd, "src-link")); + // A link the scan rejects stays out even when the watcher indexed it. + yield* fileSystem.symlink(outside, path.join(cwd, "outside-link")); + fakeSymlinkFinder([], { + indexed: [ + { path: "outside-link", kind: "file" }, + { path: "src-link", kind: "file" }, + { path: "link-file.ts", kind: "file" }, + ], + }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const searched = yield* searchIndex.search("link", 10); + const files = yield* searchIndex.search("link", 1, "file"); + const listed = yield* searchIndex.list(); + + expect(searched.entries).toEqual([ + { path: "src-link", kind: "directory" }, + { path: "link-file.ts", kind: "file" }, + ]); + // The dropped link does not take the only slot. + expect(files).toEqual({ + entries: [{ path: "link-file.ts", kind: "file" }], + truncated: false, + }); + expect(listed.entries).toEqual([ + { path: "link-file.ts", kind: "file" }, + { path: "src-link", kind: "directory" }, + ]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("finds symlinks in folders past the first page of the index", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" }); + yield* fileSystem.makeDirectory(path.join(cwd, "late")); + yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts")); + // Folders fff lists but that are gone by the time they are read are skipped. + const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`); + const { directorySearch } = fakeSymlinkFinder([...firstPage, "late"]); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + + expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]); + expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([ + 0, 1_000, + ]); + }), + ).pipe(Effect.provide(testLayer)), +); + +// fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there. +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "refuses to index a workspace rooted at the home directory", + () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-home-" }), + ); + yield* fs.makeDirectory(path.join(home, "OneDrive", "Remix"), { recursive: true }); + yield* fs.writeFileString(path.join(home, "OneDrive", "Remix", "part.stl"), "solid part\n"); + yield* Effect.acquireRelease( + Effect.sync(() => vi.stubEnv("HOME", home)), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + + const result = yield* WorkspaceSearchIndex.make(home).pipe( + Effect.flatMap((searchIndex) => searchIndex.search("stl", 50, undefined, false)), + Effect.map(({ entries }) => entries), + Effect.catchTags({ + WorkspaceSearchIndexCreateFailed: (error) => Effect.succeed(error._tag), + }), + ); + + expect(result).toBe("WorkspaceSearchIndexCreateFailed"); + }), + ).pipe(Effect.provide(testLayer)), ); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index ecb8c6ba87..b33ceade77 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1,20 +1,26 @@ +// @effect-diagnostics nodeBuiltinImport:off - readdir with file types avoids an lstat per child +import * as NodeFSP from "node:fs/promises"; import * as NodeModule from "node:module"; import type { DirItem, - DirSearchResult, FileItem, FileFinder as FileFinderType, GrepCursor, MixedItem, - MixedSearchResult, Result, - SearchResult, + WatchEvent, + WatchUnsubscribe, } from "@ff-labs/fff-node"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as LayerMap from "effect/LayerMap"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import type { @@ -25,12 +31,25 @@ import type { ProjectSearchContentsResult, ProjectSearchEntriesResult, } from "@t3tools/contracts"; -import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { PROJECT_FAVICON_EXTENSIONS, isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; +import { scoreSubsequenceMatch } from "@t3tools/shared/searchRanking"; + +import * as VcsProcess from "../vcs/VcsProcess.ts"; +import { type IgnoreDecision, type IgnoreFile, parseIgnoreFile } from "./IgnorePatterns.ts"; // fff-node's native library stays external; single-executables require disk packages instead of importing them. const requireForFff = NodeModule.createRequire(import.meta.url); const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node"); +// A glob intersects existing extension constraints; fff ORs bare `*.ext` constraints together. +const IMAGE_SEARCH_CONSTRAINT = `**/*.{${PROJECT_FAVICON_EXTENSIONS.map((extension) => + extension.slice(1).replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`), +).join(",")}}`; + +// fff 0.11 disables filename fallback above this match count per base/overflow segment. +const FFF_FILENAME_FALLBACK_MAX_MATCHES = 15_000; + const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2; const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds"; @@ -38,6 +57,16 @@ const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000; const WORKSPACE_INDEX_IDLE_TTL = "15 minutes"; const CONTENT_SEARCH_TIME_BUDGET_MS = 250; const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100; +const GIT_GREP_MAX_OUTPUT_BYTES = 4 * 1024 * 1024; +// fff's lineContent cap; matches past it are reported without ranges. +const CONTENT_LINE_MAX_LENGTH = 512; +const SYMLINK_SCAN_CONCURRENCY = 16; +// A scan no watcher can invalidate is reused this long, so typing does not rescan every folder. +const UNWATCHED_SYMLINK_SCAN_TTL_MS = 2_000; +// A rescan that outlasts this leaves the read on the previous scan. +const SYMLINK_RESCAN_WAIT = "5 millis"; +// Each page is a synchronous native call; small pages let searches run between them. +const SYMLINK_DIRECTORY_PAGE_SIZE = 1_000; export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError()( "WorkspaceSearchIndexCreateFailed", @@ -116,13 +145,17 @@ export class WorkspaceSearchIndex extends Context.Service< ) => Effect.Effect; readonly searchContents: ( input: Omit, - ) => Effect.Effect; + ) => Effect.Effect< + ProjectSearchContentsResult, + WorkspaceSearchIndexScanTimedOut | WorkspaceSearchIndexSearchFailed + >; readonly refresh: () => Effect.Effect; } >()("t3/workspace/WorkspaceSearchIndex") {} -function toPosixPath(input: string): string { - return input.replaceAll("\\", "/"); +// Only the host separator becomes `/`: on POSIX `\` is a file name character. +function toPosixPath(input: string, hostIsWindows: boolean): string { + return hostIsWindows ? input.replaceAll("\\", "/") : input; } function trimDirectorySeparator(input: string): string { @@ -134,8 +167,8 @@ function parentPathOf(input: string): string | undefined { return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex); } -function toProjectEntry(item: MixedItem): ProjectEntry | null { - const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath)); +function toProjectEntry(item: MixedItem, hostIsWindows: boolean): ProjectEntry | null { + const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath, hostIsWindows)); if (!normalizedPath) { return null; } @@ -146,23 +179,34 @@ function toProjectEntry(item: MixedItem): ProjectEntry | null { }; } -function toFileEntry(item: FileItem): ProjectEntry | null { - const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath)); +function toFileEntry(item: FileItem, hostIsWindows: boolean): ProjectEntry | null { + const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows)); return normalizedPath ? { path: normalizedPath, kind: "file" } : null; } -function toDirectoryEntry(item: DirItem): ProjectEntry | null { - const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath)); +function toDirectoryEntry(item: DirItem, hostIsWindows: boolean): ProjectEntry | null { + const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows)); return normalizedPath ? { path: normalizedPath, kind: "directory" } : null; } +function isLoneFuzzyPath(query: string): boolean { + const trimmed = query.trim(); + return ( + !/\s/u.test(trimmed) && + (trimmed.startsWith("/") || (trimmed.endsWith("/") && !/^[*!\\]/u.test(trimmed))) + ); +} + +type SearchPage = { readonly items: ReadonlyArray; readonly totalMatched: number }; + function mapFileSearchResult( - result: SearchResult, + result: SearchPage, limit: number, + hostIsWindows: boolean, imageOnly = false, ): ProjectSearchEntriesResult { const entries = result.items.flatMap((item) => { - const entry = toFileEntry(item); + const entry = toFileEntry(item, hostIsWindows); return entry && (!imageOnly || isProjectFaviconPath(entry.path)) ? [entry] : []; }); return { @@ -172,11 +216,12 @@ function mapFileSearchResult( } function mapDirectorySearchResult( - result: DirSearchResult, + result: SearchPage, limit: number, + hostIsWindows: boolean, ): ProjectSearchEntriesResult { const entries = result.items.flatMap((item) => { - const entry = toDirectoryEntry(item); + const entry = toDirectoryEntry(item, hostIsWindows); return entry ? [entry] : []; }); const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0; @@ -187,12 +232,13 @@ function mapDirectorySearchResult( } function mapMixedSearchResult( - result: MixedSearchResult, + result: SearchPage, limit: number, + hostIsWindows: boolean, ): { readonly entries: ProjectEntry[]; readonly truncated: boolean } { const entries: ProjectEntry[] = []; for (const item of result.items) { - const entry = toProjectEntry(item); + const entry = toProjectEntry(item, hostIsWindows); if (entry) { entries.push(entry); } @@ -251,6 +297,47 @@ function mapContentMatchRanges( })); } +function escapeRegExp(input: string): string { + return input.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&"); +} + +// Git before 2.55 reports wrong `--column` values for every match after a line's first, so +// later matches are found by their text, searching on from the end of the previous one. +function locateRegexMatches( + line: string, + matches: { readonly column: number; readonly texts: ReadonlyArray } | undefined, +): Array { + if (!matches) return []; + const lineBytes = Buffer.from(line); + const ranges: Array = []; + let start = matches.column - 1; + for (const text of matches.texts) { + const textBytes = Buffer.from(text); + if (ranges.length > 0) start = lineBytes.indexOf(textBytes, ranges.at(-1)![1]); + if (start < 0) break; + ranges.push([start, start + textBytes.length]); + } + return ranges; +} + +// `git grep -z` records: NUL-separated fields, one record per line; a truncated last line is dropped. +function parseGitGrepRecords( + stdout: string, + fieldCount: number, + truncated: boolean, +): Array> { + const lines = stdout.split("\n"); + if (truncated || lines.at(-1) === "") lines.pop(); + const records: Array> = []; + for (const line of lines) { + const fields = line.split("\0"); + if (fields.length < fieldCount) continue; + // Only the last field (the line or match text) can contain NUL bytes. + records.push([...fields.slice(0, fieldCount - 1), fields.slice(fieldCount - 1).join("\0")]); + } + return records; +} + // Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges. function isWholeWordRange( line: string, @@ -284,6 +371,190 @@ function withDirectoryAncestors(entries: ReadonlyArray): ProjectEn return [...entryByPath.values()]; } +interface ScannedDirectory { + readonly directory: string; + readonly links: ReadonlyArray; + /** Every symlink in the folder, including ones dropped for leaving the workspace. */ + readonly linkPaths: ReadonlyArray; + /** A nested repository (or the workspace's own), whose ignore rules own what is below it. */ + readonly isRepository: boolean; + readonly ignoreFile: string | undefined; +} + +const joinEntryPath = (directory: string, name: string) => + directory ? `${directory}/${name}` : name; + +/** + * fff skips symlinks, and `followSymlinks` drops file links, dedupes folder links, and walks out + * of the workspace. So links are read from the folders fff already indexed (ignore rules applied), + * without descending into them, and kept only when they resolve inside the workspace. + */ +const scanDirectory = Effect.fn("WorkspaceSearchIndex.scanDirectory")(function* ( + fileSystem: FileSystem.FileSystem, + path: Path.Path, + cwd: string, + root: string, + directory: string, +) { + // Effect's readDirectory returns bare names; one lstat per child would cost far more. + const children = yield* Effect.promise(() => + NodeFSP.readdir(path.join(cwd, directory), { withFileTypes: true }).catch(() => []), + ); + const links: ProjectEntry[] = []; + const linkPaths: string[] = []; + let isRepository = false; + let ignoreFile: string | undefined; + for (const child of children) { + if (child.name === ".git") isRepository = true; + if (child.name === ".ignore" && child.isFile()) { + ignoreFile = yield* fileSystem + .readFileString(path.join(cwd, directory, child.name)) + .pipe(Effect.orElseSucceed(() => undefined)); + } + if (!child.isSymbolicLink()) continue; + const entryPath = joinEntryPath(directory, child.name); + linkPaths.push(entryPath); + const absolutePath = path.join(cwd, entryPath); + const target = yield* Effect.all([ + fileSystem.realPath(absolutePath), + fileSystem.stat(absolutePath), + ]).pipe(Effect.orElseSucceed(() => undefined)); + if (!target) continue; + const relative = path.relative(root, target[0]); + if ( + relative === ".." || + relative.startsWith(`..${path.sep}`) || + path.isAbsolute(relative) || + relative.split(path.sep).includes(".git") || + (target[1].type !== "Directory" && target[1].type !== "File") + ) { + continue; + } + links.push({ path: entryPath, kind: target[1].type === "Directory" ? "directory" : "file" }); + } + return { directory, links, linkPaths, isRepository, ignoreFile } satisfies ScannedDirectory; +}); + +/** Whether `entryPath` is `directory` itself or below it. */ +const isWithin = (entryPath: string, directory: string) => + directory === "" || entryPath.startsWith(`${directory}/`); + +/** + * fff reads `.ignore` files alongside git's rules, and like ripgrep the nearest one that matches + * decides, ahead of any `.gitignore`. `ignoreFiles` is ordered deepest folder first. + */ +function decideByIgnoreFiles( + entry: ProjectEntry, + ignoreFiles: ReadonlyArray<{ readonly directory: string; readonly file: IgnoreFile }>, +): IgnoreDecision | undefined { + for (const { directory, file } of ignoreFiles) { + if (!isWithin(entry.path, directory) || entry.path === directory) continue; + const relative = directory ? entry.path.slice(directory.length + 1) : entry.path; + // Like git and ripgrep, a link is never a folder to a folder-only rule, whatever it targets. + const decision = file.decide(relative, false); + if (decision) return decision; + } + return undefined; +} + +/** Places each symlink before the first index result that matches the query less closely. */ +function mergeSymlinkMatches( + indexed: ProjectSearchEntriesResult, + linkPaths: ReadonlySet, + symlinks: ReadonlyArray, + query: string, + limit: number, +): ProjectSearchEntriesResult { + if (linkPaths.size === 0) return indexed; + // fff's watcher indexes links created after its scan, under a kind of its own choosing, so a + // path it already returned takes the link's kind (or drops out of a kind-filtered search). + const symlinkByPath = new Map(symlinks.map((entry) => [entry.path, entry])); + const score = (entry: ProjectEntry) => + scoreSubsequenceMatch(entry.path.toLowerCase(), query) ?? Number.POSITIVE_INFINITY; + const indexedPaths = new Set(indexed.entries.map((entry) => entry.path)); + const pending = symlinks + .flatMap((entry) => { + const entryScore = score(entry); + return Number.isFinite(entryScore) && !indexedPaths.has(entry.path) + ? [{ entry, score: entryScore }] + : []; + }) + .toSorted((left, right) => left.score - right.score); + const entries: ProjectEntry[] = []; + let nextPending = 0; + for (const indexedEntry of indexed.entries) { + const entry = linkPaths.has(indexedEntry.path) + ? symlinkByPath.get(indexedEntry.path) + : indexedEntry; + if (!entry) continue; + const entryScore = score(entry); + while (nextPending < pending.length && pending[nextPending]!.score < entryScore) { + entries.push(pending[nextPending++]!.entry); + } + entries.push(entry); + } + for (; nextPending < pending.length; nextPending += 1) entries.push(pending[nextPending]!.entry); + return { + entries: entries.slice(0, limit), + truncated: indexed.truncated || entries.length > limit, + }; +} + +// fff applies .gitignore files only; Git also ignores paths from .git/info/exclude and the global excludes file. +const listGitIgnoredPaths = Effect.fn("WorkspaceSearchIndex.listGitIgnoredPaths")(function* ( + vcsProcess: VcsProcess.VcsProcess["Service"], + cwd: string, + hostIsWindows: boolean, +) { + const result = yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.listGitIgnoredPaths", + command: "git", + args: [ + "-c", + "core.fsmonitor=false", + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "--directory", + "-z", + ], + cwd, + allowNonZeroExit: true, + timeoutMs: 10_000, + maxOutputBytes: 16 * 1024 * 1024, + }) + .pipe(Effect.orElseSucceed(() => undefined)); + if (!result || result.exitCode !== 0 || result.stdoutTruncated) return new Set(); + return new Set( + result.stdout + .split("\0") + .filter((entry) => entry.length > 0) + .map((entry) => trimDirectorySeparator(toPosixPath(entry, hostIsWindows))), + ); +}); + +function mixedItemPath(item: MixedItem): string { + return item.item.relativePath; +} + +function isIgnoredPath( + ignoredPaths: ReadonlySet, + relativePath: string, + hostIsWindows: boolean, +): boolean { + if (ignoredPaths.size === 0) return false; + let candidate: string | undefined = trimDirectorySeparator( + toPosixPath(relativePath, hostIsWindows), + ); + while (candidate) { + if (ignoredPaths.has(candidate)) return true; + candidate = parentPathOf(candidate); + } + return false; +} + const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* ( cwd: string, variant: WorkspaceSearchIndexVariant, @@ -296,8 +567,6 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* ( // Content indexing costs CPU/memory; path-only consumers use the lightweight index. disableContentIndexing: variant !== "content", aiMode: false, - enableFsRootScanning: true, - enableHomeDirScanning: true, }), catch: (cause) => new WorkspaceSearchIndexCreateFailed({ @@ -341,6 +610,9 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( cwd: string, variant: WorkspaceSearchIndexVariant = "paths", ) { + const hostIsWindows = yield* HostProcess.isWindows; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) => Effect.try({ try: () => finder.destroy(), @@ -348,42 +620,250 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }).pipe(Effect.orDie), ); let initialScanTimedOut = false; - yield* waitForIndexReady( - cwd, - finder, - ({ reason, cause }) => - new WorkspaceSearchIndexCreateFailed({ - cwd, - reason, - cause, + // The content index reads every file, which takes minutes where antivirus scans each open, + // so content searches do not wait for it; git grep answers until it is ready. + let contentIndexPending = variant === "content"; + const vcsProcess = yield* VcsProcess.VcsProcess; + let ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows); + if (variant === "paths") { + yield* waitForIndexReady( + cwd, + finder, + ({ reason, cause }) => + new WorkspaceSearchIndexCreateFailed({ + cwd, + reason, + cause, + }), + ).pipe( + Effect.catchTags({ + WorkspaceSearchIndexScanTimedOut: () => + Effect.sync(() => { + initialScanTimedOut = true; + }), }), - ).pipe( - Effect.catchTags({ - WorkspaceSearchIndexScanTimedOut: (error) => - variant === "paths" - ? Effect.sync(() => { - initialScanTimedOut = true; - }) - : Effect.fail(error), - }), - ); + ); + } + + // fff's isScanning takes the picker lock too, so progress is read off the JS thread. + const isScanning = Effect.promise(async () => { + try { + const progress = await finder.getScanProgressAsync(); + return !progress.ok || progress.value.isScanning; + } catch { + return true; + } + }); + const hasIncompleteInitialScan = () => (initialScanTimedOut ? isScanning : Effect.succeed(false)); + + const isContentIndexReady = Effect.fn("WorkspaceSearchIndex.isContentIndexReady")(function* () { + if (!contentIndexPending) return true; + const progress = yield* Effect.promise(() => + finder.getScanProgressAsync().catch(() => undefined), + ); + if (progress?.ok && !progress.value.isScanning && progress.value.isWarmupComplete) { + contentIndexPending = false; + } + return !contentIndexPending; + }); - const hasIncompleteInitialScan = () => initialScanTimedOut && finder.isScanning(); + const runGitGrep = Effect.fn("WorkspaceSearchIndex.runGitGrep")(function* ( + pattern: string, + options: { + readonly regexMode: boolean; + readonly ignoreCase: boolean; + readonly maxMatchesPerFile: number; + readonly onlyMatching: boolean; + }, + ) { + return yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.gitGrep", + command: "git", + args: [ + "-c", + "core.quotePath=false", + "-c", + "core.fsmonitor=false", + "grep", + "--untracked", + "--no-color", + "-I", + "-n", + "-z", + "-m", + String(options.maxMatchesPerFile), + ...(options.onlyMatching ? ["-o", "--column"] : []), + ...(options.ignoreCase ? ["-i"] : []), + options.regexMode ? "-P" : "-F", + "-e", + pattern, + ], + cwd, + allowNonZeroExit: true, + // Defender scanning fff's warmup reads slows git too; a late answer beats a failure. + timeoutMs: 30_000, + maxOutputBytes: GIT_GREP_MAX_OUTPUT_BYTES, + outputMode: "truncate", + appendTruncationMarker: false, + }) + .pipe(Effect.option); + }); + + // fff leaves out what `.ignore` files exclude, which git cannot evaluate; the nearest + // `.ignore` that matches a path or one of its folders decides, as in decideByIgnoreFiles. + const makeIgnoreFileFilter = () => { + const ignoreFiles = new Map(); + const readIgnoreFile = Effect.fn("WorkspaceSearchIndex.readIgnoreFile")(function* ( + directory: string, + ) { + if (ignoreFiles.has(directory)) return ignoreFiles.get(directory); + const contents = yield* fileSystem + .readFileString(path.join(cwd, directory, ".ignore")) + .pipe(Effect.option); + const file = Option.isSome(contents) ? parseIgnoreFile(contents.value) : undefined; + ignoreFiles.set(directory, file); + return file; + }); + return Effect.fn("WorkspaceSearchIndex.isExcludedByIgnoreFiles")(function* ( + relativePath: string, + ) { + const segments = relativePath.split("/"); + for (let depth = 1; depth <= segments.length; depth += 1) { + const candidate = segments.slice(0, depth).join("/"); + for (let ancestor = depth - 1; ancestor >= 0; ancestor -= 1) { + const directory = segments.slice(0, ancestor).join("/"); + const file = yield* readIgnoreFile(directory); + const relative = directory ? candidate.slice(directory.length + 1) : candidate; + const decision = file?.decide(relative, depth < segments.length); + if (decision === "ignored") return true; + if (decision === "included") break; + } + } + return false; + }); + }; + + // fff's grep before its content index is ready opens every file itself, as slowly as the build. + // None when git cannot search this folder (not a repository, git missing, no PCRE for a regex). + const searchContentsWithGit = Effect.fn("WorkspaceSearchIndex.searchContentsWithGit")(function* ( + input: Omit, + ): Effect.fn.Return> { + const options = { + ignoreCase: !input.caseSensitive, + maxMatchesPerFile: CONTENT_SEARCH_MAX_MATCHES_PER_FILE, + onlyMatching: false, + }; + let regexMode = input.useRegex; + let regexFallbackError: string | undefined; + let result = yield* runGitGrep(input.query, { ...options, regexMode }); + if (regexMode && Option.isSome(result) && result.value.exitCode === 128) { + if (/USE_LIBPCRE|Perl-compatible/i.test(result.value.stderr)) return Option.none(); + // fff searches an invalid pattern as a literal and reports why. + regexFallbackError = result.value.stderr.trim().split("\n")[0] || "Invalid regex"; + regexMode = false; + result = yield* runGitGrep(input.query, { ...options, regexMode }); + } + if (Option.isNone(result) || result.value.exitCode > 1) return Option.none(); + + // Per line: the first match's byte column and every match's text, in order. + const regexMatches = new Map(); + let rangesTruncated = false; + if (regexMode) { + // Ranges come from git too: running the user's pattern in JS could backtrack without bound. + const ranges = yield* runGitGrep(input.query, { ...options, regexMode, onlyMatching: true }); + // Without ranges, whole-word filtering would drop every hit and report no matches. + if (Option.isNone(ranges) || ranges.value.exitCode > 1) return Option.none(); + rangesTruncated = ranges.value.stdoutTruncated; + if (ranges.value.exitCode === 0) { + for (const record of parseGitGrepRecords( + ranges.value.stdout, + 4, + ranges.value.stdoutTruncated, + )) { + const [relativePath, lineNumber, column, text] = record as [ + string, + string, + string, + string, + ]; + const key = `${relativePath}\0${lineNumber}`; + const lineMatches = regexMatches.get(key); + if (lineMatches) lineMatches.texts.push(text); + else regexMatches.set(key, { column: Number(column), texts: [text] }); + } + } + } + const literal = regexMode + ? undefined + : new RegExp(escapeRegExp(input.query), input.caseSensitive ? "gu" : "giu"); + + const isExcludedByIgnoreFiles = makeIgnoreFileFilter(); + const matches: Array = []; + let rangesCutOff = false; + for (const record of parseGitGrepRecords( + result.value.stdout, + 3, + result.value.stdoutTruncated, + )) { + const [relativePath, lineNumber, rawLine] = record as [string, string, string]; + if (yield* isExcludedByIgnoreFiles(relativePath)) continue; + const key = `${relativePath}\0${lineNumber}`; + // Lines past the cut-off of a truncated ranges run have no ranges; stop there instead. + if (rangesTruncated && !regexMatches.has(key)) { + rangesCutOff = true; + break; + } + const lineContent = (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).slice( + 0, + CONTENT_LINE_MAX_LENGTH, + ); + const matchRanges = ( + literal + ? Array.from(lineContent.matchAll(literal), (match) => ({ + start: match.index, + end: match.index + match[0].length, + })) + : mapContentMatchRanges( + lineContent, + locateRegexMatches(lineContent, regexMatches.get(key)), + ) + ).filter( + (range) => + range.end <= lineContent.length && + (!input.wholeWord || isWholeWordRange(lineContent, range)), + ); + if (input.wholeWord && matchRanges.length === 0) continue; + matches.push({ + path: relativePath, + lineNumber: Number(lineNumber), + lineContent, + matchRanges, + }); + if (matches.length > input.limit) break; + } + return Option.some({ + matches: matches.slice(0, input.limit), + truncated: matches.length > input.limit || result.value.stdoutTruncated || rangesCutOff, + ...(regexFallbackError !== undefined ? { regexFallbackError } : {}), + }); + }); const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* ( query: string, pageSize: number, operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch", - execute: () => Result, + execute: () => Promise>, ): Effect.fn.Return { - const result = yield* Effect.try({ + // fff's searches wait on its picker lock, which its watcher can hold for minutes. + const result = yield* Effect.tryPromise({ try: execute, catch: (cause) => new WorkspaceSearchIndexSearchFailed({ cwd, queryLength: query.length, pageSize, - reason: `FileFinder.${operation} threw unexpectedly.`, + reason: `FileFinder.${operation} rejected unexpectedly.`, cause, }), }); @@ -398,15 +878,266 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( return result.value; }); + const root = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); + + const listIndexedDirectories = Effect.fn("WorkspaceSearchIndex.listIndexedDirectories")( + function* () { + const directories: string[] = []; + // fff's pageIndex is an offset into the results, not a page number. + for (let pageIndex = 0; ; pageIndex += SYMLINK_DIRECTORY_PAGE_SIZE) { + const result = yield* Effect.promise(async () => { + try { + return await finder.directorySearchAsync("", { + pageIndex, + pageSize: SYMLINK_DIRECTORY_PAGE_SIZE, + }); + } catch { + return undefined; + } + }); + if (!result?.ok) return directories; + for (const item of result.value.items) { + const directory = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows)); + if (directory) directories.push(directory); + } + if (result.value.items.length < SYMLINK_DIRECTORY_PAGE_SIZE) return directories; + } + }, + ); + + /** Ignore rules belong to the repository that owns a path, so each one answers for its own. */ + const listGitIgnored = Effect.fn("WorkspaceSearchIndex.listGitIgnored")(function* ( + repository: string, + entries: ReadonlyArray, + ) { + const relativePaths = entries.map((entry) => + repository ? entry.path.slice(repository.length + 1) : entry.path, + ); + const repositoryCwd = path.join(cwd, repository); + const result = yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.listGitIgnored", + command: "git", + // fff applies ignore rules to tracked paths too, so the index is not consulted. + args: ["-c", "core.fsmonitor=false", "check-ignore", "--no-index", "-z", "--stdin"], + cwd: repositoryCwd, + stdin: `${relativePaths.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 10_000, + maxOutputBytes: 16 * 1024 * 1024, + }) + .pipe(Effect.orElseSucceed(() => undefined)); + // Exit 1 means nothing matched. + if (result?.exitCode === 1) return []; + if (result?.exitCode !== 0 || result.stdoutTruncated) { + // Outside git no rules apply (git exits before reading stdin, so the cause is lost). + // Any other failure hides the repository's links rather than leaking ones it ignores. + const insideRepository = yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.listGitIgnored", + command: "git", + args: ["rev-parse", "--git-dir"], + cwd: repositoryCwd, + timeoutMs: 10_000, + }) + .pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + return insideRepository ? entries.map((entry) => entry.path) : []; + } + return result.stdout + .split("\0") + .filter(Boolean) + .map((relativePath) => (repository ? `${repository}/${relativePath}` : relativePath)); + }); + + const scanSymlinkEntries = Effect.fn("WorkspaceSearchIndex.scanSymlinkEntries")(function* () { + const indexComplete = !(yield* isScanning); + const directories = yield* listIndexedDirectories(); + const scanned = yield* Effect.forEach( + ["", ...directories], + (directory) => scanDirectory(fileSystem, path, cwd, root, directory), + { concurrency: SYMLINK_SCAN_CONCURRENCY }, + ); + const candidates = scanned.flatMap((directory) => directory.links); + const linkPaths = new Set(scanned.flatMap((directory) => directory.linkPaths)); + if (candidates.length === 0) return { entries: candidates, linkPaths, indexComplete }; + + const ignoreFiles = scanned + .flatMap(({ directory, ignoreFile }) => + ignoreFile === undefined ? [] : [{ directory, file: parseIgnoreFile(ignoreFile) }], + ) + .toSorted((left, right) => right.directory.length - left.directory.length); + const decisions = new Map( + candidates.map((entry) => [entry.path, decideByIgnoreFiles(entry, ignoreFiles)]), + ); + const repositories = [ + "", + ...scanned.flatMap(({ directory, isRepository }) => + isRepository && directory ? [directory] : [], + ), + ].toSorted((left, right) => right.length - left.length); + const entriesByRepository = Map.groupBy( + candidates.filter((entry) => decisions.get(entry.path) === undefined), + (entry) => + repositories.find( + (repository) => isWithin(entry.path, repository) && entry.path !== repository, + ) ?? "", + ); + const ignored = new Set( + (yield* Effect.forEach( + entriesByRepository, + ([repository, entries]) => listGitIgnored(repository, entries), + { concurrency: 4 }, + )).flat(), + ); + return { + entries: candidates.filter((entry) => + decisions.get(entry.path) === undefined + ? !ignored.has(entry.path) + : decisions.get(entry.path) === "included", + ), + linkPaths, + indexComplete, + }; + }); + + // One scan runs at a time and outlives the reads that started it. Only the first read waits for + // it in full: after that a change or expiry marks the result stale, and reads wait briefly for + // the rescan before answering from the last finished one, so file churn cannot stall search. + type SymlinkScan = Effect.Success>; + let lastSymlinkScan: SymlinkScan | undefined; + let lastSymlinkScanExpiresAt: number | undefined; + let pendingSymlinkScan: Deferred.Deferred | undefined; + let symlinkScanStale = false; + let knownLinkPaths: ReadonlySet = new Set(); + const invalidateSymlinkScan = () => { + symlinkScanStale = true; + }; + const isKnownLink = (absolutePath: string) => + [cwd, root].some((base) => + knownLinkPaths.has(toPosixPath(path.relative(base, absolutePath), hostIsWindows)), + ); + const onWatchBatch = (events: ReadonlyArray) => { + // fff reports a link replaced in place as `modified`, so edits to known links count too. + const editsOnly = events.every( + (event) => + event.kind === "modified" && + !/(^|[\\/])\.(git)?ignore$/.test(event.path) && + !isKnownLink(event.path), + ); + if (!editsOnly) invalidateSymlinkScan(); + }; + // fff refuses subscriptions until its watcher is up, which can trail the initial scan, so + // each read retries until one is in place. Subscribing waits on fff's picker lock, which its + // watcher holds while it indexes a new folder, so it runs off the JS thread. + let unwatch: WatchUnsubscribe | undefined; + yield* Effect.addFinalizer(() => Effect.sync(() => unwatch?.())); + const ensureWatching = Effect.fn("WorkspaceSearchIndex.ensureWatching")(function* () { + if (unwatch) return true; + const result = yield* Effect.promise(() => + finder.watchAsync(onWatchBatch).catch(() => undefined), + ); + if (result?.ok) unwatch = result.value; + return unwatch !== undefined; + }); + const indexScope = yield* Effect.scope; + const startSymlinkScan = Effect.fn("WorkspaceSearchIndex.startSymlinkScan")(function* () { + symlinkScanStale = false; + const done = yield* Deferred.make(); + pendingSymlinkScan = done; + yield* Effect.gen(function* () { + // Subscribing before the scan starts means no change during it goes unseen. + const watched = yield* ensureWatching(); + const result = yield* scanSymlinkEntries(); + lastSymlinkScan = result; + knownLinkPaths = result.linkPaths; + // Without a watcher, or before fff has seen every folder, the result is kept only briefly. + lastSymlinkScanExpiresAt = + watched && result.indexComplete + ? undefined + : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS; + return result; + }).pipe( + Effect.onExit((exit) => + Effect.sync(() => { + pendingSymlinkScan = undefined; + }).pipe(Effect.andThen(Deferred.done(done, exit))), + ), + Effect.forkIn(indexScope), + ); + return done; + }); + const listSymlinkEntries = Effect.fn("WorkspaceSearchIndex.listSymlinkEntries")(function* () { + if ( + lastSymlinkScanExpiresAt !== undefined && + (yield* Clock.currentTimeMillis) >= lastSymlinkScanExpiresAt + ) { + symlinkScanStale = true; + } + const pending = + pendingSymlinkScan ?? + (lastSymlinkScan === undefined || symlinkScanStale ? yield* startSymlinkScan() : undefined); + let result = lastSymlinkScan; + if (pending && result === undefined) { + result = yield* Deferred.await(pending); + } else if (pending) { + const fresh = yield* Deferred.await(pending).pipe(Effect.timeoutOption(SYMLINK_RESCAN_WAIT)); + if (Option.isSome(fresh)) result = fresh.value; + } + if (result === undefined) + return yield* Effect.die("The symlink scan finished without a result."); + return { + // Git's ignore rules hide a link the same way searchVisible hides the files it indexes. + entries: result.entries.filter( + (entry) => !isIgnoredPath(ignoredPaths, entry.path, hostIsWindows), + ), + linkPaths: result.linkPaths, + }; + }); + + // Grows the first page until hidden entries can no longer crowd visible ones out of it. + const searchVisible = Effect.fn("WorkspaceSearchIndex.searchVisible")(function* ( + query: string, + pageSize: number, + operation: "directorySearch" | "fileSearch" | "mixedSearch", + execute: (pageSize: number) => Promise & Metadata>>, + pathOf: (item: I) => string, + ): Effect.fn.Return & Metadata, WorkspaceSearchIndexSearchFailed> { + let size = pageSize; + while (true) { + const fetchSize = size; + const result = yield* runSearch(query, fetchSize, operation, () => execute(fetchSize)); + if (ignoredPaths.size === 0) return result; + const items = result.items.filter( + (item) => !isIgnoredPath(ignoredPaths, pathOf(item), hostIsWindows), + ); + if ( + items.length >= pageSize || + result.items.length >= result.totalMatched || + fetchSize >= WORKSPACE_INDEX_PAGE_SIZE + ) { + return { + ...result, + items, + totalMatched: result.totalMatched - (result.items.length - items.length), + }; + } + size = Math.min(WORKSPACE_INDEX_PAGE_SIZE, fetchSize * 4); + } + }); + const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn( "WorkspaceSearchIndex.refresh", )(function* () { - const result = yield* Effect.try({ - try: () => finder.scanFiles(), + // scanFiles waits on fff's picker lock, which its watcher can hold for seconds. + const result = yield* Effect.tryPromise({ + try: () => finder.scanFilesAsync(), catch: (cause) => new WorkspaceSearchIndexRefreshFailed({ cwd, - reason: "FileFinder.scanFiles threw unexpectedly.", + reason: "FileFinder.scanFilesAsync rejected unexpectedly.", cause, }), }); @@ -428,17 +1159,26 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( cause, }), ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void })); + ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows); + invalidateSymlinkScan(); }); const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")( function* () { - const incompleteBeforeQuery = hasIncompleteInitialScan(); - const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () => - finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }), + const incompleteBeforeQuery = yield* hasIncompleteInitialScan(); + const result = yield* searchVisible( + "", + WORKSPACE_INDEX_PAGE_SIZE, + "mixedSearch", + (pageSize) => finder.mixedSearchAsync("", { pageSize }), + mixedItemPath, ); - const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES); - const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) => - left.path.localeCompare(right.path), + const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES, hostIsWindows); + const symlinks = yield* listSymlinkEntries(); + // fff's watcher can index a link the scan rejected; only accepted links are listed. + const indexed = mapped.entries.filter((entry) => !symlinks.linkPaths.has(entry.path)); + const sortedEntries = withDirectoryAncestors([...indexed, ...symlinks.entries]).toSorted( + (left, right) => left.path.localeCompare(right.path), ); const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES); return { @@ -449,35 +1189,111 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }, ); - const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( - "WorkspaceSearchIndex.search", - )(function* (query, limit, kind, imageOnly) { - const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1); - const incompleteBeforeQuery = hasIncompleteInitialScan(); + const searchNames = Effect.fn("WorkspaceSearchIndex.searchNames")(function* ( + query: string, + limit: number, + kind: ProjectEntryKind | undefined, + imageOnly: boolean | undefined, + ) { + const { entries: allSymlinks, linkPaths } = yield* listSymlinkEntries(); + const symlinks = allSymlinks.filter((entry) => + imageOnly + ? entry.kind === "file" && isProjectFaviconPath(entry.path) + : kind === undefined || entry.kind === kind, + ); + // Index results that are filtered-out links get dropped in the merge, so fetch past them. + const indexLimit = limit + linkPaths.size - symlinks.length; + const pageSize = Math.max(1, indexLimit + 1); + const merge = (indexed: ProjectSearchEntriesResult) => + mergeSymlinkMatches(indexed, linkPaths, symlinks, query, limit); if (kind === "file" || imageOnly) { - const result = yield* runSearch(query, pageSize, "fileSearch", () => - finder.fileSearch(query, { pageSize }), + const searchFiles = (fileQuery: string, size: number) => + searchVisible( + query, + size, + "fileSearch", + (fetchSize) => finder.fileSearchAsync(fileQuery, { pageSize: fetchSize }), + (item: FileItem) => item.relativePath, + ); + // Adding a constraint changes fff's lone-path parse; offset pages can skip tied matches. + if (imageOnly && isLoneFuzzyPath(query)) { + const result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE); + return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, true)); + } + let result = yield* searchFiles( + imageOnly ? `${query} ${IMAGE_SEARCH_CONSTRAINT}` : query, + pageSize, ); - const mapped = mapFileSearchResult(result, limit, imageOnly); - return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; + if ( + imageOnly && + query.trim() && + result.totalFiles > FFF_FILENAME_FALLBACK_MAX_MATCHES && + result.totalMatched > 0 + ) { + const unfiltered = yield* runSearch(query, 1, "fileSearch", () => + finder.fileSearchAsync(query, { pageSize: 1 }), + ); + if (unfiltered.totalMatched > FFF_FILENAME_FALLBACK_MAX_MATCHES) { + result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE); + } + } + return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, imageOnly)); } if (kind === "directory") { - const result = yield* runSearch(query, pageSize, "directorySearch", () => - finder.directorySearch(query, { pageSize }), + const result = yield* searchVisible( + query, + pageSize, + "directorySearch", + (size) => finder.directorySearchAsync(query, { pageSize: size }), + (item) => item.relativePath, ); - const mapped = mapDirectorySearchResult(result, limit); - return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; + return merge(mapDirectorySearchResult(result, indexLimit, hostIsWindows)); } - const result = yield* runSearch(query, pageSize, "mixedSearch", () => - finder.mixedSearch(query, { pageSize }), + const result = yield* searchVisible( + query, + pageSize, + "mixedSearch", + (size) => finder.mixedSearchAsync(query, { pageSize: size }), + mixedItemPath, ); - const mapped = mapMixedSearchResult(result, limit); + return merge(mapMixedSearchResult(result, indexLimit, hostIsWindows)); + }); + + const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( + "WorkspaceSearchIndex.search", + )(function* (rawQuery, limit, kind, imageOnly) { + // fff parses any word containing "[" or "{" as a glob and has no escape for them; fuzzy + // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths. + // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working. + const query = rawQuery.replaceAll("[", ""); + const incompleteBeforeQuery = yield* hasIncompleteInitialScan(); + let mapped = yield* searchNames(query, limit, kind, imageOnly); + if (mapped.entries.length === 0 && query.includes("{")) { + mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly); + } return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; }); const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn( "WorkspaceSearchIndex.searchContents", )(function* (input) { + if (!(yield* isContentIndexReady())) { + const gitResult = yield* searchContentsWithGit(input); + if (Option.isSome(gitResult)) return gitResult.value; + yield* waitForIndexReady( + cwd, + finder, + ({ reason, cause }) => + new WorkspaceSearchIndexSearchFailed({ + cwd, + queryLength: input.query.length, + pageSize: input.limit, + reason, + cause, + }), + ); + contentIndexPending = false; + } let { searchQuery, regexMode } = buildContentSearchQuery(input); const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS; // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing. @@ -492,7 +1308,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( do { const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now())); const result = yield* runSearch(input.query, input.limit, "grep", () => - finder.grep(searchQuery, { + finder.grepAsync(searchQuery, { mode: regexMode ? "regex" : "plain", smartCase: !input.caseSensitive && !regexMode, maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize), @@ -510,13 +1326,14 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( } for (const match of result.items) { + if (isIgnoredPath(ignoredPaths, match.relativePath, hostIsWindows)) continue; const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter( (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range), ); // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there. if (input.wholeWord && matchRanges.length === 0) continue; matches.push({ - path: toPosixPath(match.relativePath), + path: toPosixPath(match.relativePath, hostIsWindows), lineNumber: match.lineNumber, lineContent: match.lineContent, matchRanges, diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts new file mode 100644 index 0000000000..dee23025db --- /dev/null +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -0,0 +1,261 @@ +import { ThreadId, type ProjectId, type TerminalCwdNotFoundError } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import * as ServerConfig from "../config.ts"; +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import { scratchFolderRoot } from "../project/ManagedProjectFolders.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; +import { isWithinRoot } from "./KnownWorkspaces.ts"; +import { withWorkspaceLease } from "./workspaceLease.ts"; +import { TerminalCwdRecovery } from "../terminal/Manager.ts"; + +export class WorktreeRecreateError extends Schema.TaggedError()( + "WorktreeRecreateError", + { + worktreePath: Schema.String, + branch: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Could not recreate the worktree for branch '${this.branch}' at ${this.worktreePath}.`; + } +} + +class WorktreeRecreateNoBaseError extends Schema.TaggedError()( + "WorktreeRecreateNoBaseError", + { worktreePath: Schema.String, branch: Schema.String }, +) { + override get message(): string { + return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no commit to start it from.`; + } +} + +// `git worktree remove` skips pnpm junctions on Windows, leaving these behind without a checkout. +const LEFTOVER_WORKTREE_ENTRIES = new Set(["node_modules", ".next"]); + +interface WorktreeThread { + readonly id: ThreadId; + readonly projectId: ProjectId; + readonly worktreePath: string | null; + readonly branch: string | null; +} + +export const makeRestoreMissingWorktree = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const projects = yield* ProjectService.ProjectService; + const isManagedWorktreePath = yield* makeIsManagedWorktreePath; + const serverConfig = yield* ServerConfig.ServerConfig; + + // Storage cleanup prunes idle No project folders, which have no branch to restore from. + // An empty folder, only directly inside the No project's own root, lets the thread run again. + const recreateScratchFolder = Effect.fn("restoreMissingWorktree.recreateScratchFolder")( + function* (thread: WorktreeThread, folder: string) { + if (path.resolve(folder) !== folder || (yield* fileSystem.exists(folder))) return; + const project = Option.getOrUndefined(yield* projects.getById(thread.projectId)); + if (project === undefined || path.dirname(folder) !== path.resolve(project.workspaceRoot)) + return; + const root = scratchFolderRoot(serverConfig.baseDir, path); + const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)); + if (path.dirname(folder) !== root && path.dirname(folder) !== realRoot) return; + yield* Effect.logWarning("recreating missing scratch folder", { + threadId: thread.id, + folder, + }); + yield* fileSystem.makeDirectory(folder, { recursive: true }); + }, + // Turn start reports a folder that is still missing. + Effect.orElseSucceed(() => undefined), + ); + + // Only folders holding nothing but leftovers are cleared, never user files. + const isLeftoverFolder = (worktreePath: string) => + fileSystem.exists(path.join(worktreePath, ".git")).pipe( + Effect.flatMap((hasGit) => + hasGit + ? Effect.succeed(false) + : fileSystem.readDirectory(worktreePath).pipe( + Effect.flatMap((entries) => + Effect.forEach(entries, (entry) => + LEFTOVER_WORKTREE_ENTRIES.has(entry) + ? fileSystem + .stat(path.join(worktreePath, entry)) + .pipe(Effect.map((info) => info.type === "Directory")) + : Effect.succeed(false), + ), + ), + Effect.map((leftovers) => leftovers.every(Boolean)), + ), + ), + Effect.orElseSucceed(() => false), + ); + + const resolveRecreateBase = Effect.fn("restoreMissingWorktree.resolveRecreateBase")(function* ( + cwd: string, + remoteName: string | null, + ) { + // Recovery can follow an external checkout, before the status cache expires. + yield* gitWorkflow.invalidateLocalStatus(cwd); + const { refName: currentBranch } = yield* gitWorkflow.localStatus({ cwd }); + if (currentBranch !== null) { + const refName = `refs/heads/${currentBranch}`; + return { refName, baseRefName: refName }; + } + const remoteHead = `refs/remotes/${remoteName}/HEAD`; + if (remoteName !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: remoteHead }))) { + const { commitSha } = yield* gitWorkflow.resolveRemoteTrackingCommit({ + cwd, + refName: "HEAD", + fallbackRemoteName: remoteName, + }); + // Start from the commit so the thread branch does not track the default branch. + return { refName: commitSha, baseRefName: remoteHead }; + } + if (yield* gitWorkflow.hasCommit({ cwd, refName: "HEAD" })) { + return { refName: "HEAD", baseRefName: undefined }; + } + return null; + }); + + const recreateMissingWorktree = Effect.fn("restoreMissingWorktree.recreate")(function* (input: { + readonly cwd: string; + readonly worktreePath: string; + readonly branch: string; + }) { + const { cwd, worktreePath, branch } = input; + yield* gitWorkflow.pruneWorktrees({ cwd }); + const localBranchNames = yield* gitWorkflow.listLocalBranchNames(cwd); + if (localBranchNames.includes(branch)) { + yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath }); + return; + } + const remoteName = yield* gitWorkflow + .resolvePrimaryRemoteName(cwd) + .pipe(Effect.orElseSucceed(() => null)); + // Push keeps the tracking ref current, so recovery reads it without fetching. + const pushedRef = remoteName === null ? null : `refs/remotes/${remoteName}/${branch}`; + if (pushedRef !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: pushedRef }))) { + yield* gitWorkflow.createWorktree({ + cwd, + refName: pushedRef, + newRefName: branch, + path: worktreePath, + }); + return; + } + const base = yield* resolveRecreateBase(cwd, remoteName); + if (base === null) { + return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch }); + } + yield* gitWorkflow.createWorktree({ + cwd, + refName: base.refName, + newRefName: branch, + ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }), + path: worktreePath, + }); + }); + + return Effect.fn("restoreMissingWorktree")(function* (thread: WorktreeThread) { + const { worktreePath, branch } = thread; + if (worktreePath === null) return; + if (branch === null) return yield* recreateScratchFolder(thread, worktreePath); + const exists = yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true)); + const leftover = exists && (yield* isLeftoverFolder(worktreePath)); + if ((exists && !leftover) || !(yield* isManagedWorktreePath(worktreePath))) return; + const project = yield* projects.getById(thread.projectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + if (project === undefined) return; + yield* Effect.logWarning("recreating missing worktree", { + threadId: thread.id, + worktreePath, + branch, + }); + // `git worktree add` refuses a non-empty target. + yield* (leftover ? fileSystem.remove(worktreePath, { recursive: true }) : Effect.void).pipe( + Effect.andThen(recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch })), + Effect.mapError((cause) => + cause._tag === "WorktreeRecreateNoBaseError" + ? cause + : new WorktreeRecreateError({ worktreePath, branch, cause }), + ), + ); + }); +}); + +export class ThreadWorktreeRestore extends Context.Service< + ThreadWorktreeRestore, + { + readonly restore: ( + thread: WorktreeThread, + ) => Effect.Effect; + } +>()("t3/workspace/restoreMissingWorktree/ThreadWorktreeRestore") {} + +// Turn start restores under the same lease, so concurrent restores see each other's worktree. +export const layerThreadWorktreeRestore = Layer.effect( + ThreadWorktreeRestore, + Effect.gen(function* () { + const path = yield* Path.Path; + const restore = yield* makeRestoreMissingWorktree; + return { + restore: Effect.fn("ThreadWorktreeRestore.restore")(function* (thread: WorktreeThread) { + return yield* thread.worktreePath === null + ? restore(thread) + : withWorkspaceLease(path.resolve(thread.worktreePath), restore(thread)); + }), + }; + }), +); + +// Worktree setup uses terminals, so recovery must stay outside TerminalManager. +export const makePrepareTerminalLaunch = Effect.fn( + "restoreMissingWorktree.makePrepareTerminalLaunch", +)(function* ( + getThreadShell: (threadId: ThreadId) => Effect.Effect, +) { + const path = yield* Path.Path; + const restoreMissingWorktree = yield* makeRestoreMissingWorktree; + return Effect.fn("restoreMissingWorktree.prepareTerminalLaunch")(function* < + Input extends { + readonly threadId: string; + readonly cwd?: string | undefined; + readonly worktreePath?: string | null | undefined; + }, + >(input: Input) { + const thread = yield* getThreadShell(ThreadId.make(input.threadId)).pipe( + Effect.orElseSucceed(() => null), + ); + const worktreePath = thread?.worktreePath ?? null; + if ( + thread === null || + worktreePath === null || + !isWithinRoot(path, path.resolve(input.cwd ?? worktreePath), worktreePath) + ) { + return { input, recover: TerminalCwdRecovery.defaultValue() }; + } + const recover = (error: TerminalCwdNotFoundError) => + restoreMissingWorktree(thread).pipe( + Effect.catch((cause) => + Effect.logWarning("failed to recreate missing worktree", { + threadId: thread.id, + worktreePath, + cause, + }).pipe(Effect.andThen(Effect.fail(error))), + ), + ); + // The lease must cover the worktree root, even when the terminal opens in a subdirectory. + return { input: { ...input, worktreePath }, recover }; + }); +}); diff --git a/apps/server/src/workspace/workspaceLease.ts b/apps/server/src/workspace/workspaceLease.ts index 8ad6e41b85..90e6124bb1 100644 --- a/apps/server/src/workspace/workspaceLease.ts +++ b/apps/server/src/workspace/workspaceLease.ts @@ -1,4 +1,7 @@ +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; +import type * as Path from "effect/Path"; import * as Semaphore from "effect/Semaphore"; const leases = new Map(); @@ -20,3 +23,92 @@ export const withWorkspaceLease = ( ), ); }); + +// A restore rewrites files under its directory, so it must exclude provider +// startup in any overlapping workspace: symlink aliases, parents, and children. +// Kept apart from withWorkspaceLease because that lease is non-reentrant and +// restores call Git work that leases the project root. +interface Reservation { + readonly cwd: string; + readonly kind: "restore" | "turn-start"; +} + +const reservations = new Set(); +let reservationReleased = Deferred.makeUnsafe(); + +// path.relative folds win32 drive-letter case and treats a POSIX backslash as +// part of a name, unlike a raw prefix check. +const contains = (path: Path.Path, parent: string, child: string) => { + const relative = path.relative(parent, child); + return ( + relative === "" || + (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`)) + ); +}; + +const conflicts = (path: Path.Path, a: Reservation, b: Reservation) => + (a.kind === "restore" || b.kind === "restore") && + (contains(path, a.cwd, b.cwd) || contains(path, b.cwd, a.cwd)); + +const reserve = (path: Path.Path, reservation: Reservation): Effect.Effect => + Effect.suspend(() => { + for (const held of reservations) { + if (conflicts(path, held, reservation)) { + return Deferred.await(reservationReleased).pipe(Effect.andThen(reserve(path, reservation))); + } + } + reservations.add(reservation); + return Effect.void; + }); + +const release = (reservation: Reservation) => + Effect.sync(() => { + if (!reservations.delete(reservation)) return; + const released = reservationReleased; + reservationReleased = Deferred.makeUnsafe(); + Deferred.doneUnsafe(released, Effect.void); + }); + +// A worktree removed by storage cleanup is recreated inside the reserved +// section, so resolve its nearest existing ancestor: a symlink alias above it +// must still canonicalize the same on both sides. Walks at most the path depth. +const canonicalize = ( + fileSystem: FileSystem.FileSystem, + path: Path.Path, + target: string, +): Effect.Effect => + fileSystem.realPath(target).pipe( + Effect.catchReason("PlatformError", "NotFound", () => { + const parent = path.dirname(target); + return parent === target + ? Effect.succeed(target) + : canonicalize(fileSystem, path, parent).pipe( + Effect.map((resolved) => path.join(resolved, path.basename(target))), + ); + }), + Effect.orElseSucceed(() => target), + ); + +const withReservation = + (kind: Reservation["kind"]) => + ( + fileSystem: FileSystem.FileSystem, + path: Path.Path, + cwd: string, + effect: Effect.Effect, + ): Effect.Effect => + canonicalize(fileSystem, path, cwd).pipe( + Effect.flatMap((canonical) => { + const reservation: Reservation = { cwd: canonical, kind }; + return reserve(path, reservation).pipe( + Effect.andThen(effect), + Effect.ensuring(release(reservation)), + ); + }), + ); + +/** Exclusive over every overlapping workspace while checkpoint files are restored. */ +export const withCheckpointRestoreReservation = withReservation("restore"); + +/** Waits out overlapping restores; turn startups never wait on each other. */ +export const withTurnStartReservation = withReservation("turn-start"); diff --git a/apps/server/src/workspace/wslDrivePath.ts b/apps/server/src/workspace/wslDrivePath.ts new file mode 100644 index 0000000000..188e1c85f4 --- /dev/null +++ b/apps/server/src/workspace/wslDrivePath.ts @@ -0,0 +1,29 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isWindowsDrivePath } from "@t3tools/shared/path"; +import * as Effect from "effect/Effect"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +// WSL mounts Windows drives under a configurable automount root, so only wslpath knows where. +// No WSL env check: servers started by systemd lack WSL_DISTRO_NAME, and off WSL the spawn just fails. +// Untraced: it runs for every chip path, and only drive paths on Linux do any work. +export const toWslDrivePath = Effect.fnUntraced(function* (requestedPath: string) { + // spawn throws on a NUL byte instead of failing. + if (!isWindowsDrivePath(requestedPath) || requestedPath.includes("\0")) return requestedPath; + if ((yield* HostProcess.Platform) !== "linux") return requestedPath; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner + .string( + ChildProcess.make("wslpath", ["-u", requestedPath], { + env: yield* HostProcess.Environment, + stdin: "ignore", + stderr: "ignore", + }), + ) + .pipe( + Effect.timeout("1 second"), + Effect.orElseSucceed(() => ""), + ); + const linuxPath = output.endsWith("\n") ? output.slice(0, -1) : output; + return linuxPath.startsWith("/") ? linuxPath : requestedPath; +}); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index f8c92cf804..6208e5b891 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -1,25 +1,41 @@ // apps/server/src/ws.test.ts // checks websocket rpc behavior import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import { WebSocket } from "@effect/platform-node/NodeWS"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Bind an isolated WebSocket negotiation fixture. +import * as NodeHttp from "node:http"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + AuthAccessReadScope, + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, AuthSessionId, AuthSourceControlWriteScope, + ORCHESTRATION_PROTOCOL_VERSION, + ORCHESTRATION_PROTOCOL_QUERY_PARAM, EnvironmentId, EventId, + GitManagerError, + VcsProcessSpawnError, MessageId, ProjectId, ThreadId, TurnItemId, ProviderDriverKind, ProviderInstanceId, + ProviderThreadId, + RunId, SourceControlRepositoryError, WS_METHODS, WsRpcGroup, WsServerRefreshProvidersRpc, WsSubscribeServerConfigRpc, + type AuthAccessStreamEvent, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, type OrchestrationV2StoredEvent, type OrchestrationV2ThreadShell, type OrchestrationProjectShell, @@ -27,7 +43,9 @@ import { type ServerConfigStreamEvent, type ServerProvider, } from "@t3tools/contracts"; +import { SOCKET_FRAME_PARTS_QUERY_PARAM } from "@t3tools/shared/socketFrameParts"; import * as Deferred from "effect/Deferred"; +import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -40,8 +58,14 @@ import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; -import { Headers } from "effect/http"; +import { Headers, HttpRouter, HttpServer } from "effect/http"; +import * as Context from "effect/Context"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as VcsProcess from "./vcs/VcsProcess.ts"; +import * as ProviderInstallationGate from "./provider/ProviderInstallationGate.ts"; +import * as Ws from "./ws.ts"; import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc"; +import * as RpcTest from "effect/rpc/RpcTest"; import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; import { vi } from "vite-plus/test"; @@ -84,6 +108,7 @@ import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts"; import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; import * as ProviderAuthService from "./provider/ProviderAuthService.ts"; +import * as AcpRegistrySessions from "./provider/AcpRegistrySessions.ts"; import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; @@ -122,6 +147,7 @@ import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as TextGenerators from "./textGeneration/TextGenerators.ts"; import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; +import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as ServerConfigModule from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; @@ -129,6 +155,7 @@ import * as ServerSettings from "./serverSettings.ts"; import * as HostAppUpdates from "./fincke/HostAppUpdates.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; +import * as EventStore from "./orchestration-v2/EventStore.ts"; import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; @@ -136,6 +163,7 @@ import * as EventSink from "./orchestration-v2/EventSink.ts"; import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; import * as ThreadCommandExecutor from "./orchestration-v2/ThreadCommandExecutor.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { projectIdentitiesDigest } from "./orchestration-v2/ShellStream.ts"; import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts"; import * as SqlitePersistence from "./persistence/Sqlite.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; @@ -220,7 +248,7 @@ it.effect("resends a reveal kind and remote targets that outlast the snapshot ti assert.deepEqual(remote.config.remoteOpenTargets, targets); assert.equal(remote.config.shellRevealInFileManagerKind, "file-explorer"); } - }).pipe(Effect.scoped), + }), ); it.effect("runs editor, remote open target and direct endpoint discovery side by side", () => @@ -259,25 +287,23 @@ const ReplayTestLayer = OrchestrationEventStore.layer.pipe( Layer.provideMerge(SqlitePersistence.layerMemory), ); -it.live.each(["thread", "shell"] as const)( - "%s resume skips unknown types, synchronizes, and receives the live tail", - (scope) => - Effect.gen(function* () { - const store = yield* OrchestrationEventStore.OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-05T00:00:00.000Z"; - const threadId = ThreadId.make("thread:replay"); - const projectId = ProjectId.make("project:replay"); - const project = { - id: projectId, - title: "Replay", - workspaceRoot: "/tmp/replay", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - } satisfies OrchestrationProjectShell; - const insert = (version: number, unknown = false) => sql<{ sequence: number }>` +const resumeSkipsUnknownTypes = (scope: "thread" | "shell") => + Effect.gen(function* () { + const store = yield* OrchestrationEventStore.OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = "2026-01-05T00:00:00.000Z"; + const threadId = ThreadId.make("thread:replay"); + const projectId = ProjectId.make("project:replay"); + const project = { + id: projectId, + title: "Replay", + workspaceRoot: "/tmp/replay", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + } satisfies OrchestrationProjectShell; + const insert = (version: number, unknown = false) => sql<{ sequence: number }>` INSERT INTO orchestration_events ( event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version @@ -292,85 +318,91 @@ it.live.each(["thread", "shell"] as const)( )}, '{}', 2 ) RETURNING sequence `; - const [before] = yield* insert(0); - yield* insert(1, true); - const [after] = yield* insert(2); - const [highWater] = yield* insert(3, true); - const updates = yield* PubSub.unbounded(); - let liveSequence = 0; - const consume = ( - stream: Stream.Stream, - ) => - stream.pipe( - Stream.tap((item) => - Effect.gen(function* () { - if (item.kind !== "synchronized") return; - const [live] = yield* insert(4); - liveSequence = live!.sequence; - const events = yield* store - .readApplicationEvents({ - afterSequence: highWater!.sequence, - throughSequence: liveSequence, - }) - .pipe(Stream.runCollect); - yield* store.publishCommitted(events); - }), - ), - Stream.takeUntil((item) => item.sequence === liveSequence), - Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })), - Stream.runCollect, - ); - const subscription = Effect.gen(function* () { - return scope === "thread" - ? yield* subscribeOrchestrationV2Thread({ - threadId, - afterSequence: before!.sequence, - requestCompletionMarker: true, - }).pipe(Effect.flatMap(consume)) - : yield* subscribeOrchestrationV2Shell({ - afterSequence: before!.sequence, - requestCompletionMarker: true, - }).pipe(Effect.flatMap(consume)); - }); - const items = yield* subscription.pipe( - Effect.provideService(ThreadManagement.ThreadManagementService, { - ensureLegacyTranscript: () => Effect.void, - getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"), - listActiveSubagentThreadIds: () => Effect.succeed([]), - streamStoredEventsFrom: ( - input: Parameters< - ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"] - >[0], - ) => { - assert.equal(input?.afterSequence, highWater!.sequence); - return store - .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 }) - .pipe( - Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event), - ); - }, - } as unknown as ThreadManagement.ThreadManagementService["Service"]), - Effect.provideService(ProjectStore.ProjectStoreV2, { - listShells: () => Effect.succeed([]), - } as unknown as ProjectStore.ProjectStoreV2["Service"]), - Effect.provideService(ProjectService.ProjectService, { - getShell: () => Effect.succeedSome(project), - } as unknown as ProjectService.ProjectService["Service"]), - Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, { - subscribeChanges: PubSub.subscribe(updates), - } as ProjectEnrichment.ProjectEnrichmentService["Service"]), - ); - assert.deepEqual( - items.map((item) => item.kind), - scope === "thread" - ? ["event", "synchronized", "event"] - : ["project.updated", "synchronized", "project.updated"], - ); - assert.deepEqual( - items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])), - [after!.sequence, liveSequence], + const [before] = yield* insert(0); + yield* insert(1, true); + const [after] = yield* insert(2); + const [highWater] = yield* insert(3, true); + const updates = yield* PubSub.unbounded(); + let liveSequence = 0; + const consume = ( + stream: Stream.Stream, + ) => + stream.pipe( + Stream.tap((item) => + Effect.gen(function* () { + if (item.kind !== "synchronized") return; + const [live] = yield* insert(4); + liveSequence = live!.sequence; + const events = yield* store + .readApplicationEvents({ + afterSequence: highWater!.sequence, + throughSequence: liveSequence, + }) + .pipe(Stream.runCollect); + yield* store.publishCommitted(events); + }), + ), + Stream.takeUntil((item) => item.sequence === liveSequence), + Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })), + Stream.runCollect, ); - }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), + const subscription = Effect.gen(function* () { + return scope === "thread" + ? yield* subscribeOrchestrationV2Thread({ + threadId, + afterSequence: before!.sequence, + requestCompletionMarker: true, + }).pipe(Effect.flatMap(consume)) + : yield* subscribeOrchestrationV2Shell({ + afterSequence: before!.sequence, + requestCompletionMarker: true, + }).pipe(Effect.flatMap(consume)); + }); + const items = yield* subscription.pipe( + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"), + listActiveSubagentThreadIds: () => Effect.succeed([]), + streamStoredEventsFrom: ( + input: Parameters< + ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"] + >[0], + ) => { + assert.equal(input?.afterSequence, highWater!.sequence); + return store + .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 }) + .pipe(Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event)); + }, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + Effect.provideService(ProjectStore.ProjectStoreV2, { + listShells: () => Effect.succeed([]), + } as unknown as ProjectStore.ProjectStoreV2["Service"]), + Effect.provideService(ProjectService.ProjectService, { + getShell: () => Effect.succeedSome(project), + } as unknown as ProjectService.ProjectService["Service"]), + Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, { + subscribeChanges: PubSub.subscribe(updates), + } as ProjectEnrichment.ProjectEnrichmentService["Service"]), + ); + assert.deepEqual( + items.map((item) => item.kind), + scope === "thread" + ? ["event", "synchronized", "event"] + : ["project.updated", "synchronized", "project.updated"], + ); + assert.deepEqual( + items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])), + [after!.sequence, liveSequence], + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)); + +it.effect("thread resume skips unknown types, synchronizes, and receives the live tail", () => + resumeSkipsUnknownTypes("thread"), +); + +// Shell updates batch through `Stream.groupedWithin`, whose window needs real time to close. +it.live("shell resume skips unknown types, synchronizes, and receives the live tail", () => + resumeSkipsUnknownTypes("shell"), ); it.effect("coalesces streaming replay before synchronization and the live tail", () => @@ -695,6 +727,8 @@ it.effect("shell snapshots omit idle children and older settled threads only on shell("live", "parent", "running"), ...Array.from({ length: 25 }, (_, index) => shell(`recent-${index}`, null, null, 1)), shell("old", null, null, 30), + shell("remote-parent", null, null, 40), + shell("remote-child-parent", "parent", null), ]; const firstSnapshot = (input: { readonly omitIdleSubagents?: boolean; @@ -711,6 +745,7 @@ it.effect("shell snapshots omit idle children and older settled threads only on pinnedAt: null, snoozedUntil: null, mayBeLive: thread.activityRunStatus !== null, + hasRemoteTasks: thread.id.startsWith("remote-"), })), ), readShellSnapshot: (options?: { readonly threadIds?: ReadonlyArray }) => @@ -754,15 +789,17 @@ it.effect("shell snapshots omit idle children and older settled threads only on const withoutChildren = yield* firstSnapshot({ omitIdleSubagents: true }); assert.deepEqual( withoutChildren?.threads.map((thread) => thread.id), - ["parent", "live", ...recent, "old"], + ["parent", "live", ...recent, "old", "remote-parent", "remote-child-parent"], ); + // A linked environment's clients nest its task under its parent, so that parent stays: an + // older settled thread or an idle subagent. const withoutOld = yield* firstSnapshot({ omitIdleSubagents: true, omitOlderSettled: true }); assert.deepEqual( withoutOld?.threads.map((thread) => thread.id), - ["parent", "live", ...recent], + ["parent", "live", ...recent, "remote-parent", "remote-child-parent"], ); assert.deepEqual(withoutOld?.olderSettled?.counts, [ - { projectId: ProjectId.make("project"), count: 1 }, + { projectId: ProjectId.make("project"), count: 2 }, ]); }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); @@ -771,6 +808,7 @@ it.effect("shell snapshots omit idle children and older settled threads only on const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(DocumentText.DocumentText)({}), Layer.mock(ServerSecretStore.ServerSecretStore)({}), + Layer.mock(SecretCheck.SecretCheck)({}), Layer.mock(WorkspacePaths.WorkspacePaths)({}), Layer.mock(TraceDiagnostics.TraceDiagnostics)({}), Layer.mock(TextGenerators.TextGenerators)({}), @@ -778,6 +816,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}), Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}), Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({}), + Layer.mock(AcpRegistrySessions.AcpRegistrySessions)({}), Layer.mock(AgentSessionImporter.AgentSessionImporter)({}), Layer.mock(AgentSessionScanner.AgentSessionScanner)({}), Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }), @@ -857,6 +896,98 @@ const layerConfigSources = Layer.mergeAll( Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); +it.live.each([ + { subject: "desktop-bootstrap", extensions: "", framed: false }, + { subject: "desktop-bootstrap", extensions: "", framed: true }, + { subject: "one-time-token", extensions: "permessage-deflate", framed: false }, +])( + "negotiates compression for $subject sessions (framed=$framed)", + ({ subject, extensions, framed }) => + Effect.gen(function* () { + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(HostAppUpdates.HostAppUpdates)({ available: false }), + Layer.mock(ServerBrowser.ServerBrowser)({ + profileReporter: Effect.succeed(() => Effect.void), + }), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({ + authenticateWebSocketUpgrade: () => + Effect.succeed({ + sessionId: AuthSessionId.make("compression-test"), + subject, + method: "bearer-access-token", + scopes: [], + }), + }), + Layer.mock(SessionStore.SessionStore)({ + cookieName: "compression-test", + legacyCookieName: undefined, + markConnected: () => Effect.void, + markDisconnected: () => Effect.void, + awaitInvalidation: () => Effect.never, + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: process.cwd(), + }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(VcsProcess.VcsProcess)({ + run: (input) => + Effect.fail( + new VcsProcessSpawnError({ + operation: input.operation, + command: input.command, + cwd: input.cwd, + cause: "No VCS commands in the compression fixture", + }), + ), + }), + ProviderInstallationGate.layer, + FetchHttpClient.layer, + ); + const context = yield* Layer.build( + HttpRouter.serve(Ws.layer, { disableListenLog: true }).pipe( + Layer.provideMerge( + NodeHttpServer.layer(NodeHttp.createServer, { + host: "127.0.0.1", + port: 0, + websocket: { perMessageDeflate: true }, + }), + ), + Layer.provide(services), + Layer.provide(layerConfigSources), + ), + ); + const server = Context.get(context, HttpServer.HttpServer); + const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws"); + const socket = yield* Effect.acquireRelease( + Effect.sync( + () => + new WebSocket( + `${origin}/ws?${ORCHESTRATION_PROTOCOL_QUERY_PARAM}=${ORCHESTRATION_PROTOCOL_VERSION}${framed ? `&${SOCKET_FRAME_PARTS_QUERY_PARAM}=1` : ""}`, + { + origin: "t3code://app", + }, + ), + ), + (socket) => Effect.sync(() => socket.terminate()), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + socket.once("open", resolve); + socket.once("error", reject); + }), + ); + assert.equal(socket.extensions, extensions); + }).pipe(Effect.scoped), +); + it.effect.each([ "pending", "cached", @@ -1118,10 +1249,124 @@ it.effect.each([ Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); +it.effect("access changes made while the snapshot loads reach the client after it", () => + Effect.gen(function* () { + const pairingChanges = yield* PubSub.unbounded(); + const sessionChanges = yield* PubSub.unbounded(); + const subscribed = yield* Queue.unbounded(); + const subscribe = (changes: PubSub.PubSub) => + Stream.unwrap( + PubSub.subscribe(changes).pipe( + Effect.tap(() => Queue.offer(subscribed, undefined)), + Effect.map(Stream.fromSubscription), + ), + ); + const revokedElsewhere = AuthSessionId.make("revoked-elsewhere"); + const responses = yield* Queue.unbounded(); + const server = yield* RpcServer.makeNoSerialization(WsRpcGroup, { + ...WS_RPC_SERVER_OPTIONS, + onFromServer: (response) => + response._tag === "Chunk" + ? Effect.forEach( + response.values, + (event) => Queue.offer(responses, event as AuthAccessStreamEvent), + { + discard: true, + }, + ) + : Effect.void, + }).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("current"), + subject: "current", + method: "browser-session-cookie", + scopes: [], + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe( + Layer.merge(RpcAuthorization.layer([AuthAccessReadScope])), + Layer.provide( + Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(HostAppUpdates.HostAppUpdates)({ available: false }), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/unused", + }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({ + listPairingLinks: () => Effect.succeed([]), + // Another client revokes a session after the snapshot read it. + listClientSessions: () => + PubSub.publish(sessionChanges, { + type: "clientRemoved", + sessionId: revokedElsewhere, + }).pipe(Effect.as([])), + }), + Layer.mock(PairingGrantStore.PairingGrantStore)({ + streamChanges: subscribe(pairingChanges), + }), + Layer.mock(SessionStore.SessionStore)({ + cookieName: "auth-access-test", + legacyCookieName: undefined, + streamChanges: subscribe(sessionChanges), + }), + ), + ), + ), + ), + ); + const requestId = RpcMessage.RequestId("auth-access"); + yield* server.write(0, { + _tag: "Request", + id: requestId, + tag: WS_METHODS.subscribeAuthAccess, + payload: {}, + headers: Headers.empty, + }); + const snapshot = yield* Queue.take(responses); + assert.equal(snapshot.type, "snapshot"); + yield* server.write(0, { _tag: "Ack", requestId }); + yield* Queue.take(subscribed); + yield* Queue.take(subscribed); + + // A later change arrives either way, so a dropped revocation fails as a mismatch. + yield* PubSub.publish(pairingChanges, { type: "pairingLinkRemoved", id: "later" }); + const next = yield* Queue.take(responses); + assert.deepEqual(next, { + version: 1, + revision: 2, + type: "clientRemoved", + payload: { sessionId: revokedElsewhere }, + }); + yield* server.write(0, { _tag: "Ack", requestId }); + assert.equal((yield* Queue.take(responses)).type, "pairingLinkRemoved"); + yield* server.write(0, { _tag: "Ack", requestId }); + yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] }); + }).pipe( + Effect.provide( + Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), + ), + ), + ), +); + it.effect("on-demand clients get provider config without workspace snapshots", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("claudeAgent"); @@ -1156,6 +1401,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( ], }; let scansCwd = true; + let registryProviders: ReadonlyArray = [provider]; const providerChanges = yield* Queue.unbounded>(); const pulled = yield* Queue.unbounded(); const responses = yield* Queue.unbounded(); @@ -1166,11 +1412,12 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( resolveFileManagerRevealKind: () => Effect.undefined, }), Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([provider]), + getProviders: Effect.sync(() => registryProviders), streamChanges: Stream.fromQueue(providerChanges).pipe( Stream.tap(() => Queue.offer(pulled, undefined)), ), - refreshWorkspaceSnapshot: () => Effect.succeed([provider]), + refresh: () => Effect.sync(() => registryProviders), + refreshWorkspaceSnapshot: () => Effect.sync(() => registryProviders), }), Layer.mock(ProjectService.ProjectService)({ workspaceScanDirectory: (cwd) => Effect.succeed(cwd), @@ -1192,6 +1439,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( Layer.mock(UsageLimitSources.UsageLimitSources)({ current: Effect.succeed([]), streamChanges: Stream.make([]), + refresh: Effect.void, }), Layer.mock(HostAppUpdates.HostAppUpdates)({ available: false, @@ -1351,6 +1599,121 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( }, ]); yield* server.write(0, { _tag: "Interrupt", requestId: configRequest, interruptors: [] }); + + // A client that takes digests and deltas, against a catalog of over 200 KB. + const heavy: ServerProvider = { + ...provider, + slashCommands: Array.from({ length: 250 }, (_, index) => ({ + name: `command-${index}`, + description: "d".repeat(400), + })), + skills: Array.from({ length: 200 }, (_, index) => ({ + name: `skill-${index}`, + description: "d".repeat(500), + path: `/home/user/.claude/skills/skill-${index}/SKILL.md`, + enabled: true, + })), + }; + registryProviders = [heavy]; + const lightRequest = RpcMessage.RequestId("light-config"); + yield* server.write(0, { + _tag: "Request", + id: lightRequest, + tag: WS_METHODS.subscribeServerConfig, + payload: { + workspaceSnapshotsOnDemand: true, + providerCatalogsOnDemand: true, + providerCatalogDigests: true, + providerStatusDeltas: true, + }, + headers: Headers.empty, + }); + const light = (yield* Queue.take(responses)) as ServerConfigStreamEvent; + if (light.type !== "snapshot") return yield* Effect.die("Missing light snapshot"); + const digest = light.config.providers[0]?.catalogDigest; + assert.isString(digest); + assert.deepEqual( + [light.config.providers[0]?.slashCommands, light.config.providers[0]?.skills], + [[], []], + ); + // Budget for the first config a phone decodes: the catalog stays out of it. + assert.isBelow(JSON.stringify(light.config.providers).length, 1024); + yield* server.write(0, { _tag: "Ack", requestId: lightRequest }); + + // A health check sends the provider without the lists the client already holds. + yield* Queue.offer(providerChanges, [{ ...heavy, checkedAt: "2026-10-25T00:10:00.000Z" }]); + yield* Queue.take(pulled); + yield* TestClock.adjust("1 second"); + const delta = (yield* Queue.take(responses)) as ServerConfigStreamEvent; + if (delta.type !== "providerStatusDeltas") return yield* Effect.die("Expected provider deltas"); + assert.deepEqual( + delta.payload.providers.map((entry) => [ + entry.checkedAt, + entry.catalogDigest, + entry.models, + entry.slashCommands, + entry.skills, + ]), + [["2026-10-25T00:10:00.000Z", digest, undefined, undefined, undefined]], + ); + yield* server.write(0, { _tag: "Ack", requestId: lightRequest }); + + // A changed description changes the digest, so the client loads the lists again. + yield* Queue.offer(providerChanges, [ + { + ...heavy, + checkedAt: "2026-10-25T00:20:00.000Z", + skills: heavy.skills.map((skill, index) => + index === 0 ? { ...skill, description: "changed" } : skill, + ), + }, + ]); + yield* Queue.take(pulled); + yield* TestClock.adjust("1 second"); + const redescribed = (yield* Queue.take(responses)) as ServerConfigStreamEvent; + if (redescribed.type !== "providerStatusDeltas") { + return yield* Effect.die("Expected provider deltas"); + } + assert.notEqual(redescribed.payload.providers[0]?.catalogDigest, digest); + yield* server.write(0, { _tag: "Ack", requestId: lightRequest }); + + // A caller that only waits for a machine refresh gets no provider list back. + yield* server.write(0, { + _tag: "Request", + id: RpcMessage.RequestId("refresh-omitted"), + tag: WS_METHODS.serverRefreshProviders, + payload: { workspaceSnapshotsOnDemand: true, omitProviders: true }, + headers: Headers.empty, + }); + assert.deepEqual(yield* Queue.take(responses), { providers: [] }); + + // The cwd snapshot brings the lists the digest stands for, under the same digest. + yield* server.write(0, { + _tag: "Request", + id: RpcMessage.RequestId("refresh-machine-catalog"), + tag: WS_METHODS.serverRefreshProviders, + payload: { + instanceId, + cwd: "/b", + workspaceSnapshotsOnDemand: true, + providerCatalogsOnDemand: true, + omitProviders: true, + machineCatalog: true, + }, + headers: Headers.empty, + }); + const loaded = (yield* Queue.take(responses)) as { + readonly providers: ReadonlyArray; + }; + assert.equal(loaded.providers[0]?.catalogDigest, digest); + assert.deepEqual(loaded.providers[0]?.slashCommands[0], { name: "command-0" }); + assert.deepEqual(loaded.providers[0]?.skills[0], { + name: "skill-0", + path: "/home/user/.claude/skills/skill-0/SKILL.md", + enabled: true, + }); + assert.lengthOf(loaded.providers[0]?.workspaceSnapshots ?? [], 1); + yield* server.write(0, { _tag: "Interrupt", requestId: lightRequest, interruptors: [] }); }).pipe( Effect.provide( Layer.mergeAll( @@ -1359,7 +1722,6 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -1535,7 +1897,80 @@ it.effect("a missing thread worktree gets its project's skills in the cwd snapsh Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, + ), +); + +it.effect("a git action that fails partway still refreshes the repository status", () => + Effect.gen(function* () { + const failure = new GitManagerError({ operation: "test", cwd: "/repo", detail: "push failed" }); + const refreshFailure = new GitManagerError({ + operation: "refresh", + cwd: "/repo", + detail: "refresh failed", + }); + const refreshed = yield* Deferred.make(); + const exits = yield* Queue.unbounded>(); + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(HostAppUpdates.HostAppUpdates)({ available: false }), + Layer.mock(GitWorkflowService.GitWorkflowService)({ + runStackedAction: () => Effect.fail(failure), + }), + Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ + refreshStatus: (cwd) => + Deferred.succeed(refreshed, cwd).pipe(Effect.andThen(Effect.fail(refreshFailure))), + }), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + ); + const server = yield* RpcServer.makeNoSerialization(WsRpcGroup, { + ...WS_RPC_SERVER_OPTIONS, + onFromServer: (response) => + response._tag === "Exit" ? Queue.offer(exits, response.exit) : Effect.void, + }).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("git-test"), + subject: "git-test", + method: "browser-session-cookie", + scopes: [AuthSourceControlWriteScope], + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe( + Layer.provide(services), + Layer.merge(RpcAuthorization.layer([AuthSourceControlWriteScope])), + ), + ), + ); + yield* server.write(0, { + _tag: "Request", + id: RpcMessage.RequestId("git"), + tag: WS_METHODS.gitRunStackedAction, + payload: { actionId: "action", cwd: "/repo", action: "commit_push" }, + headers: Headers.empty, + }); + const exit = yield* Queue.take(exits); + assert.deepEqual(Exit.isFailure(exit) ? Cause.squash(exit.cause) : exit, failure); + assert.equal(yield* Deferred.await(refreshed), "/repo"); + }).pipe( + Effect.provide( + Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), + ), + ), ), ); @@ -1624,7 +2059,6 @@ it.effect("a publish whose push fails still refreshes the new remote", () => Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -1780,39 +2214,410 @@ it.effect.each(["thread", "shell"] as const)( }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); -// A thread idle since before the boundary missed nothing; resuming must not resend its body. -it.effect("thread resume at its own high-water below the pruned boundary skips the snapshot", () => +// A cursor at the high-water missed nothing, even below the boundary; resuming must not resend +// a snapshot. The shell cases are a client that just loaded the HTTP snapshot of a pruned +// database: it gets the marker, and the project identities only when it does not name them. +it.effect.each([ + { scope: "thread", knowsIdentities: false, isRepository: true, kinds: [] }, + { + scope: "shell", + knowsIdentities: false, + isRepository: true, + kinds: ["snapshot", "synchronized"], + }, + { scope: "shell", knowsIdentities: true, isRepository: true, kinds: ["synchronized"] }, + // The client keeps a cached identity over an absent one, so "resolved to none" still goes out. + { + scope: "shell", + knowsIdentities: true, + isRepository: false, + kinds: ["snapshot", "synchronized"], + }, +] as const)( + "$scope resume at its own high-water below the pruned boundary skips the snapshot (knows identities: $knowsIdentities, repository: $isRepository)", + ({ scope, knowsIdentities, isRepository, kinds }) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const now = "2026-10-13T00:00:00.000Z"; + const threadId = ThreadId.make("thread:idle"); + const [last] = yield* sql<{ sequence: number }>` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, + occurred_at, actor_kind, payload_json, metadata_json, application_event_version + ) VALUES ( + 'idle:0', 'thread', ${threadId}, 0, 'provider-session.detached', + ${now}, 'server', ${JSON.stringify({ providerSessionId: "session:idle", detachedAt: now })}, + '{}', 2 + ) RETURNING sequence + `; + yield* sql` + INSERT INTO orchestration_v2_projection_metadata ( + projection_name, schema_version, last_sequence, updated_at + ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${last!.sequence + 10}, ${now}) + `; + const identity = isRepository + ? ({ + canonicalKey: "github.com/t3/idle", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "git@github.com:t3/idle", + }, + } as const) + : null; + const project = { + id: ProjectId.make("project:idle"), + title: "Idle", + workspaceRoot: "/tmp/idle", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + } satisfies OrchestrationProjectShell; + const subscription = Effect.gen(function* () { + if (scope === "thread") { + return yield* subscribeOrchestrationV2Thread({ + threadId, + afterSequence: last!.sequence, + }).pipe(Effect.as([])); + } + const stream = yield* subscribeOrchestrationV2Shell({ + afterSequence: last!.sequence, + requestCompletionMarker: true, + ...(knowsIdentities + ? { + knownProjectIdentities: projectIdentitiesDigest([ + { ...project, repositoryIdentity: identity }, + ]), + } + : {}), + }); + return yield* stream.pipe( + Stream.takeUntil((item) => item.kind === "synchronized"), + Stream.map((item) => item.kind), + Stream.runCollect, + ); + }); + const exit = yield* subscription.pipe( + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + getThreadSnapshot: () => Effect.die("snapshot"), + listActiveShellIndex: () => Effect.die("snapshot"), + readShellSnapshot: () => Effect.die("snapshot"), + listActiveSubagentThreadIds: () => Effect.succeed([]), + streamStoredEventsFrom: () => Stream.empty, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + Effect.provideService(ProjectStore.ProjectStoreV2, { + listShells: () => Effect.succeed([project]), + } as unknown as ProjectStore.ProjectStoreV2["Service"]), + Effect.provideService( + ProjectService.ProjectService, + {} as ProjectService.ProjectService["Service"], + ), + Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, { + subscribeChanges: PubSub.subscribe(yield* PubSub.unbounded()), + getAvailable: () => + Effect.succeed({ + repositoryIdentity: identity, + faviconPath: null, + repositoryIdentityResolved: true, + }), + } as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"]), + Effect.exit, + ); + // A snapshot load dies with "snapshot", so success means the resume replayed nothing. + assert.deepEqual( + Exit.isFailure(exit) ? Cause.squash(exit.cause) : Array.from(exit.value), + kinds, + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + +const acpDriver = ProviderDriverKind.make("acpRegistry"); +const acpInstanceId = ProviderInstanceId.make("acpRegistry_test"); +const acpProjectId = ProjectId.make("project:acp"); +const acpThreadId = (sessionId: string) => + IdAllocator.deriveThreadFromProviderThread({ + driver: acpDriver, + providerInstanceId: acpInstanceId, + nativeThreadId: sessionId, + }); +const acpSessionTags = [ + WS_METHODS.serverListAcpRegistrySessions, + WS_METHODS.serverImportAcpRegistrySession, + WS_METHODS.serverDeleteAcpRegistrySession, +] as const; +const acpSessionRpcs = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RpcAuthorization.RPC_REQUIRED_SCOPES, + (typeof acpSessionTags)[number] + > => !(acpSessionTags as ReadonlyArray).includes(tag), + ), +); +const acpStores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( + Layer.provideMerge(SqlitePersistence.layerMemory), +); + +const seedAcpThread = Effect.fn(function* ( + sessionId: string, + state: { readonly imported: boolean; readonly ran: boolean; readonly nativeId?: string }, +) { + const sink = yield* EventSink.EventSinkV2; + const now = DateTime.makeUnsafe("2026-10-23T00:00:00.000Z"); + const threadId = acpThreadId(sessionId); + const thread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: acpProjectId, + title: sessionId, + providerInstanceId: acpInstanceId, + modelSelection: { instanceId: acpInstanceId, model: "default" }, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + ...(state.imported ? { historyOrigin: "v1_import" as const } : {}), + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + }; + const events: Array = [ + { + id: EventId.make(`${threadId}:created`), + type: "thread.created", + threadId, + occurredAt: now, + payload: thread, + }, + ]; + if (state.nativeId !== undefined) { + events.push({ + id: EventId.make(`${threadId}:provider`), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderThreadId.make(`${threadId}:provider`), + appThreadId: threadId, + ownerNodeId: null, + driver: acpDriver, + providerInstanceId: acpInstanceId, + providerSessionId: null, + nativeThreadRef: { driver: acpDriver, nativeId: state.nativeId, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + pendingBackgroundTasks: [], + }, + }); + } + if (state.ran) { + events.push({ + id: EventId.make(`${threadId}:run`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + id: RunId.make(`${threadId}:run`), + threadId, + ordinal: 1, + providerInstanceId: acpInstanceId, + modelSelection: thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make(`${threadId}:prompt`), + rootNodeId: null, + activeAttemptId: null, + status: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }, + }); + } + yield* sink.write({ events }); + return threadId; +}); + +it.effect("ACP session RPCs list a thread missing its history and repair it on import", () => Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; const sql = yield* SqlClient.SqlClient; - const now = "2026-10-13T00:00:00.000Z"; - const threadId = ThreadId.make("thread:idle"); - const [last] = yield* sql<{ sequence: number }>` - INSERT INTO orchestration_events ( - event_id, aggregate_kind, stream_id, stream_version, event_type, - occurred_at, actor_kind, payload_json, metadata_json, application_event_version - ) VALUES ( - 'idle:0', 'thread', ${threadId}, 0, 'provider-session.detached', - ${now}, 'server', ${JSON.stringify({ providerSessionId: "session:idle", detachedAt: now })}, - '{}', 2 - ) RETURNING sequence - `; - yield* sql` - INSERT INTO orchestration_v2_projection_metadata ( - projection_name, schema_version, last_sequence, updated_at - ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${last!.sequence + 10}, ${now}) - `; - const exit = yield* subscribeOrchestrationV2Thread({ - threadId, - afterSequence: last!.sequence, - }).pipe( - Effect.provideService(ThreadManagement.ThreadManagementService, { - ensureLegacyTranscript: () => Effect.void, - getThreadSnapshot: () => Effect.die("snapshot"), - streamStoredEventsFrom: () => Stream.empty, - } as unknown as ThreadManagement.ThreadManagementService["Service"]), - Effect.exit, + const pending = yield* seedAcpThread("pending", { imported: false, ran: false }); + const complete = yield* seedAcpThread("complete", { imported: true, ran: false }); + const ran = yield* seedAcpThread("ran", { imported: false, ran: true }); + const owned = yield* seedAcpThread("existing-t3-thread", { + imported: false, + ran: true, + nativeId: "owned-session", + }); + const repaired: Array = []; + const deleted: Array = []; + const session = (sessionId: string) => ({ + sessionId, + cwd: "/workspace/acp", + additionalDirectories: [], + title: null, + updatedAt: null, + importedThreadId: null, + }); + const instance = { + driverKind: acpDriver, + snapshot: { + getSnapshot: Effect.succeed({ nativeSessions: { canLoad: true, canDelete: true } }), + }, + acpSessionManagement: { + listSessions: () => + Effect.succeed({ + sessions: ["new", "pending", "complete", "ran", "owned-session"].map(session), + nextCursor: null, + canLoad: true, + canResume: true, + canDelete: true, + }), + deleteSession: ({ sessionId }: { readonly sessionId: string }) => + Effect.sync(() => { + deleted.push(sessionId); + }), + }, + } as unknown as ProviderInstance; + const dependencies = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(HostAppUpdates.HostAppUpdates)({ available: false }), + Layer.fresh(layerConfigSources), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeedSome({ + id: acpProjectId, + title: "ACP", + workspaceRoot: "/workspace/acp", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-10-23T00:00:00.000Z", + updatedAt: "2026-10-23T00:00:00.000Z", + deletedAt: null, + }), + }), + Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({ + getInstance: () => Effect.succeed(instance), + }), + Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({ + withSessionMutation: (effect) => effect, + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (threadId) => + projections + .getThreadShell(threadId) + .pipe( + Effect.mapError( + (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }), + ), + ), + }), + // Repairing an existing thread must not launch another one. + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(AgentSessionImporter.AgentSessionImporter)({ + importNativeHistory: ({ threadId }) => + Effect.sync(() => repaired.push(threadId)).pipe(Effect.as(1)), + }), + Layer.succeed(SqlClient.SqlClient, sql), ); - // A snapshot load dies with "snapshot", so success means the resume replayed nothing. - assert.isTrue(Exit.isSuccess(exit)); - }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), + const services = AcpRegistrySessions.layer.pipe(Layer.provideMerge(dependencies)); + const client = yield* RpcTest.makeClient(acpSessionRpcs).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("acp-test"), + subject: "acp-test", + method: "browser-session-cookie", + scopes: [], + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe( + Layer.provide(services), + Layer.merge( + RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]), + ), + ), + ), + ); + + const listed = yield* client[WS_METHODS.serverListAcpRegistrySessions]({ + instanceId: acpInstanceId, + projectId: acpProjectId, + }); + assert.deepEqual( + listed.sessions.map(({ sessionId, importedThreadId, nativeHistoryPending }) => [ + sessionId, + importedThreadId, + nativeHistoryPending, + ]), + [ + ["new", null, undefined], + ["pending", pending, true], + ["complete", complete, undefined], + ["ran", ran, undefined], + ["owned-session", owned, undefined], + ], + ); + + const imported = yield* client[WS_METHODS.serverImportAcpRegistrySession]({ + instanceId: acpInstanceId, + projectId: acpProjectId, + sessionId: "pending", + }); + assert.deepEqual(imported, { threadId: pending, imported: true }); + assert.deepEqual(repaired, [pending]); + const reopened = yield* client[WS_METHODS.serverImportAcpRegistrySession]({ + instanceId: acpInstanceId, + projectId: acpProjectId, + sessionId: "owned-session", + }); + assert.deepEqual(reopened, { threadId: owned, imported: false }); + assert.deepEqual(repaired, [pending]); + const deletion = yield* client[WS_METHODS.serverDeleteAcpRegistrySession]({ + instanceId: acpInstanceId, + projectId: acpProjectId, + sessionId: "owned-session", + }).pipe(Effect.exit); + assert.isTrue(Exit.isFailure(deletion)); + assert.deepEqual(deleted, []); + }).pipe( + Effect.provide( + Layer.mergeAll( + EventSink.layer.pipe(Layer.provideMerge(acpStores)), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), + ), + ), + ), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 4eb7da5020..010b9af8e9 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2,7 +2,11 @@ // serves authenticated upstream and cartographer rpc handlers import * as CartographerService from "./cartographer/CartographerService.ts"; import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. +import * as NodeCrypto from "node:crypto"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; +import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; @@ -20,7 +24,6 @@ import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import { rpcInitialItems } from "./rpcInitialItems.ts"; import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; @@ -42,7 +45,6 @@ import { type GitActionProgressEvent, type GitManagerServiceError, type MessageId, - type AcpRegistryImportSessionInput, type AcpRegistryDeleteSessionInput, type AcpRegistryDisableProviderInput, type AcpRegistryListProvidersInput, @@ -82,6 +84,7 @@ import { type ServerConfigStreamEvent, type ServerLifecycleStreamEvent, type ServerProvider, + serverProviderDeltas, type FilesystemBrowseFailure, FilesystemBrowseError, AssetWorkspaceContextNotFoundError, @@ -91,9 +94,6 @@ import { PersistChatAttachmentsError, RpcClientId, EnvironmentAuthorizationError, - type ProjectId, - type ProviderDriverKind, - type ProviderInstanceId, ThreadId, type TerminalMetadataStreamEvent, type PullRequestRef, @@ -121,7 +121,6 @@ import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManag import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"; import * as DocumentText from "./provider/DocumentText.ts"; -import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; import { @@ -135,6 +134,8 @@ import { shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, loadSubscriberShellSnapshot, + canResumeShellFrom, + resumeIdentityRoots, shellStreamItemsFromResumeSnapshot, shouldPublishShellApplicationEvent, skipUnchangedThreadShells, @@ -170,6 +171,8 @@ import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts"; import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts"; import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; +import * as SecretCheck from "./secrets/SecretCheck.ts"; +import * as AcpRegistrySessions from "./provider/AcpRegistrySessions.ts"; import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; @@ -185,6 +188,7 @@ import { invalidateSettingsSecrets } from "./sourceControl/sourceControlHostSecr import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; +import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; @@ -253,6 +257,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as SessionStore from "./auth/SessionStore.ts"; import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import { isNetworkPath } from "@t3tools/shared/path"; import { SOCKET_FRAME_PARTS_QUERY_PARAM, @@ -438,26 +443,67 @@ function workspaceSnapshotOrCatalog( ]; } -// On-demand catalog clients read full entries from the cwd snapshot they fetch. Names still -// change the config when the machine catalog does, so the client refetches, and skill names -// and labels keep skill links working where no snapshot is fetched. +// What an on-demand catalog client keeps of the machine catalog: full entries come from the +// cwd snapshot it fetches, and skill names and labels keep skill links working without one. +function machineCatalogNames(provider: Pick) { + return { + slashCommands: provider.slashCommands.map(({ name }) => ({ name })), + skills: provider.skills.map(({ description: _d, shortDescription: _s, ...skill }) => skill), + }; +} + +// Stable across restarts, so a client's cached lists stay current until the catalog changes. +// It covers the full entries: a changed description or input hint must reach the client too. +const machineCatalogDigest = (provider: Pick) => + NodeCrypto.createHash("sha256") + .update(JSON.stringify([provider.slashCommands, provider.skills])) + .digest("hex") + .slice(0, 16); + +// Names, or the digest that stands for them, still change the config when the machine catalog +// does, so the client refetches its cwd snapshot. function withoutWorkspaceSnapshots( providers: ReadonlyArray, catalogsPerCwd: ReadonlySet = new Set(), + catalogDigests = false, ): ServerProvider[] { - return providers.map(({ workspaceSnapshots: _workspaceSnapshots, ...provider }) => - catalogsPerCwd.has(provider.instanceId) + return providers.map(({ workspaceSnapshots: _workspaceSnapshots, ...provider }) => { + if (!catalogsPerCwd.has(provider.instanceId)) return provider; + return catalogDigests ? { ...provider, - slashCommands: provider.slashCommands.map(({ name }) => ({ name })), - skills: provider.skills.map( - ({ description: _d, shortDescription: _s, ...skill }) => skill, - ), + slashCommands: [], + skills: [], + catalogDigest: machineCatalogDigest(provider), } - : provider, - ); + : { ...provider, ...machineCatalogNames(provider) }; + }); } +// Deltas are taken from the list this client last received, which a late snapshot replaces. +const withProviderStatusDeltas = (sent: ReadonlyArray) => + Stream.mapAccum( + () => sent, + ( + previous, + event: ServerConfigStreamEvent, + ): readonly [ReadonlyArray, ReadonlyArray] => { + if (event.type === "snapshot") return [event.config.providers, [event]]; + if (event.type !== "providerStatuses") return [previous, [event]]; + const { providers } = event.payload; + return [ + providers, + [ + { + version: 1, + type: "providerStatusDeltas", + payload: { providers: serverProviderDeltas(previous, providers) }, + }, + ], + ]; + }, + ); + function unexpectedCompatibilityError(error: never): never { throw new Error(`Unhandled compatibility error: ${String(error)}`); } @@ -671,12 +717,6 @@ const isOtherWsRpc = (rpc: ServerWsRpc): rpc is Exclude const serverWsRpcs = Array.from(ServerWsRpcGroup.requests.values()); const SplitWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isSplitWsRpc)); const OtherWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isOtherWsRpc)); -// Replaying each intervening event costs a shell refetch; past this gap a -// single O(active-threads) snapshot is cheaper and bounded. -const SHELL_RESUME_MAX_GAP = 1_000; -// Row counts do not bound large tool payloads; sum stored JSON bytes in SQL and snapshot above budget. -const ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES = 8 * 1024 * 1024; - function toAuthAccessStreamEvent( change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, revision: number, @@ -757,36 +797,6 @@ function readClientConnectionOrigin( }; } -const canReplayPersistedRange = Effect.fnUntraced(function* ( - afterSequence: number, - headSequence: number, - maxGap: number, -) { - const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; - - const replayGap = headSequence - afterSequence; - if (replayGap < 0 || replayGap > maxGap) { - return false; - } - if (afterSequence < (yield* applicationEvents.prunedThroughSequence)) return false; - const stats = yield* applicationEvents.getReplayStats({ - afterSequence, - throughSequence: headSequence, - }); - if (stats.rawPayloadBytes > ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES) { - yield* Effect.logDebug("orchestration replay replaced by snapshot", { - afterSequence, - headSequence, - replayGap, - eventCount: stats.eventCount, - payloadBytes: stats.rawPayloadBytes, - payloadBudgetBytes: ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES, - }); - return false; - } - return true; -}); - const enrichProjectShells = Effect.fn("ws.orchestrationV2.enrichProjectShells")( (projects: ReadonlyArray) => Effect.flatMap(ProjectEnrichmentService.ProjectEnrichmentService, (projectEnrichment) => @@ -1051,6 +1061,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc function* (input: { readonly afterSequence?: number; readonly httpSnapshotFallback?: true; + readonly knownProjectIdentities?: string; readonly requestCompletionMarker?: boolean; readonly omitIdleSubagents?: boolean; readonly omitOlderSettled?: boolean; @@ -1276,7 +1287,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc }); }); const highWater = yield* applicationEvents.latestApplicationSequence; - if (!(yield* canReplayPersistedRange(input.afterSequence, highWater, SHELL_RESUME_MAX_GAP))) { + if (!(yield* canResumeShellFrom(applicationEvents, input.afterSequence, highWater))) { return yield* fromSnapshot; } @@ -1295,12 +1306,22 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc skipUnknownEventTypes: true, }) .pipe(Stream.filter(filterSubagentTranscript), Stream.runCollect); - if (input.afterSequence < (yield* applicationEvents.prunedThroughSequence)) { + if ( + input.afterSequence < highWater && + input.afterSequence < (yield* applicationEvents.prunedThroughSequence) + ) { return yield* fromSnapshot; } const replay = toShellStream(Stream.fromIterable(replayed)); return composeShellStreamWithEnrichment({ - initial: initialEnrichmentItems(loaded), + initial: initialEnrichmentItems({ + snapshot: loaded.snapshot, + resolvedRepositoryIdentityRoots: resumeIdentityRoots({ + projects: loaded.snapshot.projects, + resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, + knownProjectIdentities: input.knownProjectIdentities, + }), + }), tail: Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)), enrichment: enrichmentRefreshes, }); @@ -1414,6 +1435,9 @@ export const layerWsRpc = ( const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const terminalManager = yield* TerminalManager.TerminalManager; + const prepareTerminalLaunch = yield* makePrepareTerminalLaunch( + threadManagement.getThreadShell, + ); const previewManager = yield* PreviewManager.PreviewManager; const portDiscovery = yield* PortScanner.PortDiscovery; const providerRegistry = yield* ProviderRegistry.ProviderRegistry; @@ -1421,6 +1445,7 @@ export const layerWsRpc = ( const acpRegistryCatalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const acpRegistryRuntimeCoordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const acpRegistrySessions = yield* AcpRegistrySessions.AcpRegistrySessions; const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; const providerAuth = yield* ProviderAuthService.ProviderAuthService; const providerInstallation = yield* ProviderInstallation.ProviderInstallation; @@ -1455,11 +1480,14 @@ export const layerWsRpc = ( ); const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery; + const secretCheck = yield* SecretCheck.SecretCheck; const otlpEndpointCheck = yield* OtlpEndpointCheck.OtlpEndpointCheck; const textGenerators = yield* TextGenerators.TextGenerators; const sourceControlRepositories = yield* SourceControlRepositoryService.SourceControlRepositoryService; const withPullRequestViewer = pullRequests.withRoutingCredential; + // The panel's reads for a pull request the user opened go out during a rate-limit pause. + const openedPullRequestRead = Effect.provideService(SourceControlRateLimit.Interactive, true); const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; const sessions = yield* SessionStore.SessionStore; const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; @@ -1471,6 +1499,7 @@ export const layerWsRpc = ( currentSession.scopes.includes(AuthOrchestrationOperateScope) ? result : { + ...result, tasks: result.tasks.map(({ webhook: _webhook, ...task }) => task), }; const authorizeEffect = ( @@ -1481,64 +1510,11 @@ export const layerWsRpc = ( ? effect : Effect.fail(rpcAuthorizationError(requiredScope)); - const acpRegistryProject = Effect.fn("ws.acpRegistry.project")(function* ( - projectId: ProjectId, - ) { - const project = yield* projectService.getById(projectId).pipe( - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ - reason: "project_not_found", - message: `Project ${projectId} is unavailable.`, - cause, - }), - ), - ); - return yield* Effect.fromOption( - project, - () => - new AcpRegistryOperationError({ - reason: "project_not_found", - message: `Project ${projectId} was not found.`, - }), - ); - }); - - const acpSessionManager = Effect.fn("ws.acpRegistry.sessionManager")(function* ( - instanceId: ProviderInstanceId, - ) { - const instance = yield* providerInstances.getInstance(instanceId); - if (instance === undefined) { - return yield* new AcpRegistryOperationError({ - reason: "instance_not_found", - message: `Provider instance ${instanceId} was not found.`, - }); - } - if (instance.acpSessionManagement === undefined) { - return yield* new AcpRegistryOperationError({ - reason: "session_list_unsupported", - message: `Provider instance ${instanceId} does not expose ACP session management.`, - }); - } - return { instance, manager: instance.acpSessionManagement }; - }); - - const importedAcpThreadId = (input: { - readonly driver: ProviderDriverKind; - readonly instanceId: ProviderInstanceId; - readonly sessionId: string; - }) => - IdAllocator.deriveThreadFromProviderThread({ - driver: input.driver, - providerInstanceId: input.instanceId, - nativeThreadId: input.sessionId, - }); - const listAcpRegistrySessions = Effect.fn("ws.acpRegistry.listSessions")(function* ( input: AcpRegistryListSessionsInput, ) { - const project = yield* acpRegistryProject(input.projectId); - const { instance, manager } = yield* acpSessionManager(input.instanceId); + const project = yield* acpRegistrySessions.project(input.projectId); + const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); const listed = yield* manager.listSessions({ cwd: project.workspaceRoot, ...(input.cursor === undefined ? {} : { cursor: input.cursor }), @@ -1546,24 +1522,36 @@ export const layerWsRpc = ( const sessions = yield* Effect.forEach( listed.sessions, (session) => { - const threadId = importedAcpThreadId({ + const idInput = { driver: instance.driverKind, instanceId: input.instanceId, sessionId: session.sessionId, - }); - return threadManagement.getThreadShell(threadId).pipe( - Effect.map((thread) => ({ - ...session, - importedThreadId: thread === null ? null : threadId, - })), - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ - reason: "session_import_failed", - message: "Could not inspect existing imported ACP sessions.", - cause, - }), - ), + }; + return acpRegistrySessions.findOwner(idInput).pipe( + Effect.flatMap((owner) => { + const threadId = owner ?? AcpRegistrySessions.importedThreadId(idInput); + return threadManagement.getThreadShell(threadId).pipe( + Effect.map((thread) => ({ + ...session, + importedThreadId: thread === null ? null : threadId, + ...(thread !== null && + AgentSessionImporter.isNativeHistoryPending({ + historyOrigin: thread.historyOrigin, + hasRun: thread.latestRunId !== null, + }) + ? { nativeHistoryPending: true } + : {}), + })), + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not inspect existing imported ACP sessions.", + cause, + }), + ), + ); + }), ); }, { concurrency: 16 }, @@ -1571,106 +1559,15 @@ export const layerWsRpc = ( return { ...listed, sessions }; }); - const importAcpRegistrySession = Effect.fn("ws.acpRegistry.importSession")(function* ( - input: AcpRegistryImportSessionInput, - ) { - return yield* acpRegistryRuntimeCoordinator.withSessionMutation( - Effect.gen(function* () { - yield* acpRegistryProject(input.projectId); - const { instance } = yield* acpSessionManager(input.instanceId); - const providerSnapshot = yield* instance.snapshot.getSnapshot; - if ( - providerSnapshot.nativeSessions?.canLoad !== true && - providerSnapshot.nativeSessions?.canResume !== true - ) { - return yield* new AcpRegistryOperationError({ - reason: "session_resume_unsupported", - message: "The ACP agent cannot load or resume native sessions.", - }); - } - const threadId = importedAcpThreadId({ - driver: instance.driverKind, - instanceId: input.instanceId, - sessionId: input.sessionId, - }); - const existing = yield* threadManagement.getThreadShell(threadId).pipe( - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ - reason: "session_import_failed", - message: "Could not inspect the imported ACP session mapping.", - cause, - }), - ), - ); - if (existing !== null) return { threadId, imported: false } as const; - - const provider = (yield* providerRegistry.getProviders).find( - (candidate) => candidate.instanceId === input.instanceId, - ); - const model = - provider?.models.find((candidate) => candidate.isDefault)?.slug ?? - provider?.models[0]?.slug ?? - "default"; - const commandId = CommandId.make(yield* random.uuidV4()); - const launched = yield* Effect.result( - startup.enqueueCommand( - threadLaunch.launch({ - commandId, - threadId, - projectId: input.projectId, - title: input.title ?? "Imported ACP session", - modelSelection: { instanceId: input.instanceId, model }, - runtimeMode: "approval-required", - interactionMode: "default", - workspaceStrategy: { type: "root" }, - importedNativeThread: { - ref: { - driver: instance.driverKind, - nativeId: input.sessionId, - strength: "strong", - }, - metadata: { - itemIdentityVersion: 2, - ...(input.title === undefined ? {} : { title: input.title }), - ...(input.updatedAt === undefined ? {} : { updatedAt: input.updatedAt }), - }, - }, - createdBy: "user", - creationSource: "web", - }), - ), - ); - if (Result.isFailure(launched)) { - const racedImport = yield* threadManagement.getThreadShell(threadId).pipe( - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ - reason: "session_import_failed", - message: "Could not inspect the imported ACP session after launch failed.", - cause, - }), - ), - ); - if (racedImport !== null) return { threadId, imported: false } as const; - return yield* new AcpRegistryOperationError({ - reason: "session_import_failed", - message: "Could not create a 456code thread for the ACP session.", - cause: launched.failure, - }); - } - return { threadId, imported: true } as const; - }), - ); - }); - const deleteAcpRegistrySession = Effect.fn("ws.acpRegistry.deleteSession")(function* ( input: AcpRegistryDeleteSessionInput, ) { return yield* acpRegistryRuntimeCoordinator.withSessionMutation( Effect.gen(function* () { - const project = yield* acpRegistryProject(input.projectId); - const { instance, manager } = yield* acpSessionManager(input.instanceId); + const project = yield* acpRegistrySessions.project(input.projectId); + const { instance, manager } = yield* acpRegistrySessions.sessionManager( + input.instanceId, + ); const snapshot = yield* instance.snapshot.getSnapshot; if (snapshot.nativeSessions?.canDelete !== true) { return yield* new AcpRegistryOperationError({ @@ -1678,11 +1575,14 @@ export const layerWsRpc = ( message: "The ACP agent does not advertise session deletion.", }); } - const threadId = importedAcpThreadId({ + const idInput = { driver: instance.driverKind, instanceId: input.instanceId, sessionId: input.sessionId, - }); + }; + const threadId = + (yield* acpRegistrySessions.findOwner(idInput)) ?? + AcpRegistrySessions.importedThreadId(idInput); const importedThread = yield* threadManagement.getThreadShell(threadId).pipe( Effect.mapError( (cause) => @@ -1712,8 +1612,8 @@ export const layerWsRpc = ( const listAcpRegistryProviders = Effect.fn("ws.acpRegistry.listProviders")(function* ( input: AcpRegistryListProvidersInput, ) { - const project = yield* acpRegistryProject(input.projectId); - const { instance, manager } = yield* acpSessionManager(input.instanceId); + const project = yield* acpRegistrySessions.project(input.projectId); + const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); const snapshot = yield* instance.snapshot.getSnapshot; if (snapshot.configurableProviders !== true) { return yield* new AcpRegistryOperationError({ @@ -1727,8 +1627,8 @@ export const layerWsRpc = ( const setAcpRegistryProvider = Effect.fn("ws.acpRegistry.setProvider")(function* ( input: AcpRegistrySetProviderInput, ) { - const project = yield* acpRegistryProject(input.projectId); - const { manager } = yield* acpSessionManager(input.instanceId); + const project = yield* acpRegistrySessions.project(input.projectId); + const { manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); if (input.headers !== undefined && Object.keys(input.headers).length > 32) { return yield* new AcpRegistryOperationError({ reason: "provider_configuration_failed", @@ -1769,8 +1669,8 @@ export const layerWsRpc = ( const disableAcpRegistryProvider = Effect.fn("ws.acpRegistry.disableProvider")(function* ( input: AcpRegistryDisableProviderInput, ) { - const project = yield* acpRegistryProject(input.projectId); - const { manager } = yield* acpSessionManager(input.instanceId); + const project = yield* acpRegistrySessions.project(input.projectId); + const { manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); const listed = yield* manager.listProviders(project.workspaceRoot); const provider = listed.providers.find( (candidate) => candidate.providerId === input.providerId, @@ -1819,6 +1719,7 @@ export const layerWsRpc = ( readonly workspaceSnapshotsOnDemand: boolean; readonly deferNetworkDiscovery: boolean; readonly catalogsPerCwd?: ReadonlySet; + readonly catalogDigests?: boolean; }) { const keybindingsConfig = yield* keybindings.loadConfigState; const currentProviders = yield* providerRegistry.getProviders; @@ -1826,7 +1727,11 @@ export const layerWsRpc = ( ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current) : currentProviders; const providers = options.workspaceSnapshotsOnDemand - ? withoutWorkspaceSnapshots(commandProviders, options.catalogsPerCwd) + ? withoutWorkspaceSnapshots( + commandProviders, + options.catalogsPerCwd, + options.catalogDigests, + ) : commandProviders; const settings = ServerSettings.redactServerSettingsForClient( yield* serverSettings.getSettings, @@ -1851,6 +1756,7 @@ export const layerWsRpc = ( environment, auth, cwd: config.cwd, + hostname: yield* HostProcess.Hostname, keybindingsConfigPath: config.keybindingsConfigPath, keybindings: keybindingsConfig.keybindings, issues: keybindingsConfig.issues, @@ -1905,6 +1811,7 @@ export const layerWsRpc = ( }), newProjectsRoot: managedFolders.namedProjectsRoot, ...(lastEventLoopStall === undefined ? {} : { lastEventLoopStall }), + serverTime: DateTime.formatIso(yield* DateTime.now), }; }); @@ -2161,38 +2068,49 @@ export const layerWsRpc = ( Effect.andThen( startup .enqueueCommand( - ThreadMessageIntake.launchThread({ - commandId: input.commandId, - ...(input.threadId === undefined ? {} : { threadId: input.threadId }), - ...(input.reuseExistingThread === undefined - ? {} - : { reuseExistingThread: input.reuseExistingThread }), - projectId: input.projectId, - title: input.title, - ...(input.generateTitle === undefined - ? {} - : { generateTitle: input.generateTitle }), - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - workspaceStrategy: input.workspaceStrategy, - ...(input.initialMessage === undefined - ? {} - : { - initialMessage: { - ...(input.initialMessage.messageId === undefined - ? {} - : { messageId: input.initialMessage.messageId }), - text: input.initialMessage.text, - attachments: input.initialMessage.attachments, - ...(input.initialMessage.context === undefined - ? {} - : { context: input.initialMessage.context }), - }, + threadLaunch + .checkWorktreeBase({ + commandId: input.commandId, + projectId: input.projectId, + workspaceStrategy: input.workspaceStrategy, + }) + .pipe( + Effect.andThen( + ThreadMessageIntake.launchThread({ + commandId: input.commandId, + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + ...(input.reuseExistingThread === undefined + ? {} + : { reuseExistingThread: input.reuseExistingThread }), + projectId: input.projectId, + title: input.title, + ...(input.generateTitle === undefined + ? {} + : { generateTitle: input.generateTitle }), + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + workspaceStrategy: input.workspaceStrategy, + ...(input.initialMessage === undefined + ? {} + : { + initialMessage: { + ...(input.initialMessage.messageId === undefined + ? {} + : { messageId: input.initialMessage.messageId }), + text: input.initialMessage.text, + attachments: input.initialMessage.attachments, + ...(input.initialMessage.context === undefined + ? {} + : { context: input.initialMessage.context }), + }, + }), + createdBy: "user", + creationSource: input.creationSource ?? "web", }), - createdBy: "user", - creationSource: input.creationSource ?? "web", - }).pipe(Effect.provide(intakeContext)), + ), + Effect.provide(intakeContext), + ), ) .pipe( Effect.map((result) => ({ @@ -2228,6 +2146,27 @@ export const layerWsRpc = ( message: cause.message, cause, }), + ThreadLaunchBaseRefError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: cause.message, + cause, + }), + ThreadLaunchBranchConflictError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: cause.message, + cause, + }), + ThreadLaunchNotRepositoryError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: cause.message, + cause, + }), }), ), ), @@ -2323,7 +2262,7 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "provider.instance_id": input.instanceId, "project.id": input.projectId, - }).pipe(Effect.andThen(importAcpRegistrySession(input))), + }).pipe(Effect.andThen(acpRegistrySessions.importSession(input))), [WS_METHODS.serverDeleteAcpRegistrySession]: (input) => Effect.annotateCurrentSpan({ "provider.instance_id": input.instanceId, @@ -2348,7 +2287,9 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "provider.instance_id": input.instanceId }).pipe( Effect.andThen( Effect.gen(function* () { - const { instance, manager } = yield* acpSessionManager(input.instanceId); + const { instance, manager } = yield* acpRegistrySessions.sessionManager( + input.instanceId, + ); const snapshot = yield* instance.snapshot.getSnapshot; if (snapshot.auth.canLogout !== true) { return yield* new AcpRegistryOperationError({ @@ -2445,12 +2386,15 @@ export const layerWsRpc = ( providers = yield* providerRegistry.refreshInstance(instance.instanceId); } } + const { instanceId, cwd } = input; + if (input.omitProviders === true && (instanceId === undefined || cwd === undefined)) { + return { providers: [] }; + } if (input.workspaceSnapshotsOnDemand !== true) return { providers }; const commandProviders = input.usageLimitsCommand === true ? withUsageLimitsCommands(providers, yield* usageLimitSources.current) : providers; - const { instanceId, cwd } = input; if (instanceId === undefined || cwd === undefined) { return { providers: withoutWorkspaceSnapshots(commandProviders) }; } @@ -2460,14 +2404,23 @@ export const layerWsRpc = ( return { providers: commandProviders .filter((provider) => provider.instanceId === instanceId) - .map((provider) => ({ - ...provider, - // Callers read only the cwd snapshot; the config stream carries the rest. - models: [], - slashCommands: [], - skills: [], - workspaceSnapshots: workspaceSnapshotOrCatalog(provider, cwd, catalogOnDemand), - })), + .map((provider) => { + const catalog = + catalogOnDemand && input.machineCatalog === true + ? machineCatalogNames(provider) + : undefined; + return { + ...provider, + // Callers read only the cwd snapshot; the config stream carries the rest. + models: [], + slashCommands: catalog?.slashCommands ?? [], + skills: catalog?.skills ?? [], + ...(catalog === undefined + ? {} + : { catalogDigest: machineCatalogDigest(provider) }), + workspaceSnapshots: workspaceSnapshotOrCatalog(provider, cwd, catalogOnDemand), + }; + }), }; }), [WS_METHODS.mcpAppsCallTool]: (input) => mcpAppRequests.callTool(input), @@ -2604,6 +2557,10 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(peerLinkRequests.answer(input)), ), + [WS_METHODS.serverGetSettings]: (_input) => + Effect.map(serverSettings.getSettings, (settings) => + ServerSettings.redactServerSettingsForClient(settings, settingsClient), + ), [WS_METHODS.serverUpdateSettings]: /* Request instrumentation already owns the span; keep this helper in that context. */ Effect.fnUntraced(function* ({ patch, providerInstanceMutation }) { @@ -2619,6 +2576,7 @@ export const layerWsRpc = ( return ServerSettings.redactServerSettingsForClient(settings, settingsClient); }), [WS_METHODS.serverDiscoverSourceControl]: (_input) => sourceControlDiscovery.discover, + [WS_METHODS.serverCheckSecretSource]: (input) => secretCheck.check(input.source), [WS_METHODS.serverGetTraceDiagnostics]: (_input) => TraceDiagnostics.readTraceDiagnostics({ traceFilePath: config.serverTracePath, @@ -2670,13 +2628,13 @@ export const layerWsRpc = ( ), ), [WS_METHODS.pullRequestsDetail]: (input) => - withPullRequestViewer(input, pullRequests.detail(input)), + withPullRequestViewer(input, openedPullRequestRead(pullRequests.detail(input))), [WS_METHODS.pullRequestsPreview]: (input) => withPullRequestViewer(input, pullRequests.preview(input)), [WS_METHODS.pullRequestsChecks]: (input) => withPullRequestViewer(input, pullRequests.checks(input)), [WS_METHODS.pullRequestsActivity]: (input) => - withPullRequestViewer(input, pullRequests.activity(input)), + withPullRequestViewer(input, openedPullRequestRead(pullRequests.activity(input))), [WS_METHODS.pullRequestsReviewGuide]: (input) => withPullRequestViewer(input, reviewGuides.get(input)), [WS_METHODS.pullRequestsGenerateReviewGuide]: (input) => @@ -2731,6 +2689,8 @@ export const layerWsRpc = ( ), ), [WS_METHODS.pullRequestsSubscribeRefreshes]: () => pullRequests.subscribeRefreshes, + [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: () => + pullRequests.subscribeLinkedThreadRefreshes, [WS_METHODS.pullRequestsReviewerCandidates]: (input) => withPullRequestViewer(input, pullRequests.reviewerCandidates(input)), [WS_METHODS.pullRequestsRequestReviewers]: (input) => @@ -2895,7 +2855,7 @@ export const layerWsRpc = ( new ProjectMutationError({ commandId: mutation.commandId, message: - cause._tag === "ProjectNotEmptyError" + cause._tag === "ProjectNotEmptyError" || cause._tag === "ProjectInvalidError" ? cause.message : "Failed to mutate project.", cause, @@ -2927,6 +2887,7 @@ export const layerWsRpc = ( if ( input.resource._tag === "attachment" || input.resource._tag === "native-app-icon" || + input.resource._tag === "environment-theme-background" || input.resource._tag === "tool-output-image" || input.resource._tag === SOURCE_CONTROL_MEDIA_ASSET || // A network path is served only from the thread's project, looked up below. @@ -3033,7 +2994,9 @@ export const layerWsRpc = ( }) .pipe( Effect.matchCauseEffect({ - onFailure: (cause) => Queue.failCause(queue, cause), + // Earlier steps (branch, commit) may have landed before the failing one. + onFailure: (cause) => + refreshGitStatus(input.cwd).pipe(Effect.andThen(Queue.failCause(queue, cause))), onSuccess: (result) => (input.threadId === undefined ? Effect.void @@ -3071,20 +3034,54 @@ export const layerWsRpc = ( [WS_METHODS.vcsCreateWorktree]: (input) => gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsRemoveWorktree]: (input) => - gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + gitWorkflow.removeWorktree(input).pipe( + Effect.tap(() => refreshGitStatus(input.cwd)), + // Subscribers of the removed checkout learn it is no longer a repository. + Effect.tap(() => + vcsStatusBroadcaster + .refreshLocalStatus(input.path) + .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid), + ), + ), [WS_METHODS.vcsCreateRef]: (input) => - gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + gitWorkflow + .createRef(input) + .pipe( + Effect.tap(() => + input.switchRef + ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) + : refreshGitStatus(input.cwd), + ), + ), [WS_METHODS.vcsSwitchRef]: (input) => - gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + gitWorkflow + .switchRef(input) + .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), [WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input), [WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input), - [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input), + [WS_METHODS.terminalOpen]: (input) => + prepareTerminalLaunch(input).pipe( + Effect.flatMap((launch) => + terminalManager + .open(launch.input) + .pipe(Effect.provideService(TerminalManager.TerminalCwdRecovery, launch.recover)), + ), + ), [WS_METHODS.terminalAttach]: (input, metadata) => - terminalManager.attachOutputStream(input, terminalViewerId(metadata)), - [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input), + Stream.unwrap( + prepareTerminalLaunch(input).pipe( + Effect.map((launch) => + terminalManager + .attachOutputStream(launch.input, terminalViewerId(metadata)) + .pipe(Stream.provideService(TerminalManager.TerminalCwdRecovery, launch.recover)), + ), + ), + ), + [WS_METHODS.terminalWrite]: (input, metadata) => + terminalManager.write(input, terminalViewerId(metadata)), [WS_METHODS.terminalResize]: (input, metadata) => terminalManager.resize(input, terminalViewerId(metadata)), [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), @@ -3183,6 +3180,7 @@ export const layerWsRpc = ( ), ) : Effect.succeed(new Set()); + const catalogDigests = input.providerCatalogDigests === true; // Buffer changes through discovery and the initial snapshot's send. const keybindingsChanges = yield* keybindings.subscribeChanges; const settingsChanges = yield* serverSettings.subscribeChanges; @@ -3200,6 +3198,7 @@ export const layerWsRpc = ( workspaceSnapshotsOnDemand, deferNetworkDiscovery: true, catalogsPerCwd: yield* currentCatalogsPerCwd, + catalogDigests, }); const keybindingsUpdates = keybindingsChanges.pipe( Stream.map((event) => ({ @@ -3230,7 +3229,11 @@ export const layerWsRpc = ( workspaceSnapshotsOnDemand ? currentCatalogsPerCwd.pipe( Effect.map((catalogsPerCwd) => - withoutWorkspaceSnapshots(commandProviders, catalogsPerCwd), + withoutWorkspaceSnapshots( + commandProviders, + catalogsPerCwd, + catalogDigests, + ), ), ) : Effect.succeed(commandProviders), @@ -3309,19 +3312,22 @@ export const layerWsRpc = ( remoteResult?._tag === "Success" ? { ...config, remoteOpenTargets: remoteResult.value } : config; + const updates = withLateConfigDiscovery( + initialConfig, + liveUpdates, + externalLauncher, + { + resolveTargets: () => Fiber.join(remoteTargets), + }, + { resolve: () => Fiber.join(directResult) }, + ); return Stream.concat( rpcInitialItems([ { version: 1 as const, type: "snapshot" as const, config: initialConfig }, ]), - withLateConfigDiscovery( - initialConfig, - liveUpdates, - externalLauncher, - { - resolveTargets: () => Fiber.join(remoteTargets), - }, - { resolve: () => Fiber.join(directResult) }, - ), + input.providerStatusDeltas === true + ? updates.pipe(withProviderStatusDeltas(initialConfig.providers)) + : updates, ); }), ), @@ -3348,21 +3354,35 @@ export const layerWsRpc = ( [WS_METHODS.subscribeAuthAccess]: (_input) => Stream.unwrap( Effect.gen(function* () { + const liveBuffer = yield* Queue.unbounded< + PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange + >(); + // Each store subscribes only when consumed, so start both before the snapshot read. + yield* Effect.forkScoped( + Stream.runForEach(bootstrapCredentials.streamChanges, (change) => + Queue.offer(liveBuffer, change), + ), + { startImmediately: true }, + ); + yield* Effect.forkScoped( + Stream.runForEach(sessions.streamChanges, (change) => + Queue.offer(liveBuffer, change), + ), + { startImmediately: true }, + ); const initialSnapshot = yield* loadAuthAccessSnapshot(); const revisionRef = yield* Ref.make(1); - const accessChanges: Stream.Stream< - PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange - > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges); - const liveEvents: Stream.Stream = accessChanges.pipe( - Stream.mapEffect((change) => - Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe( - Effect.map((revision) => - toAuthAccessStreamEvent(change, revision, currentSessionId), + const liveEvents: Stream.Stream = + Stream.fromQueue(liveBuffer).pipe( + Stream.mapEffect((change) => + Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe( + Effect.map((revision) => + toAuthAccessStreamEvent(change, revision, currentSessionId), + ), ), ), - ), - ); + ); return Stream.concat( rpcInitialItems([ @@ -3438,6 +3458,12 @@ export const layer = Layer.unwrap( failEnvironmentInternal("internal_error", error), ), ); + // Desktop bootstrap sessions connect to their own backend, including same-machine WSL. + if (session.subject === "desktop-bootstrap") { + delete NodeHttpServerRequest.toIncomingMessage(request).headers[ + "sec-websocket-extensions" + ]; + } const clientOrigin = readClientConnectionOrigin(request); const reportProfiles = yield* serverBrowser.profileReporter; const rpcWebSocketHttpEffect = yield* Effect.gen(function* () { @@ -3462,8 +3488,8 @@ export const layer = Layer.unwrap( Layer.provideMerge(RpcSerialization.layerJson), // Handler-context reporters see only request defects, not server-wide defects. Layer.provide(DefectReporter.layer), + Layer.provide(AcpRegistrySessions.layer), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), - Layer.provide(AgentSessionScanner.layer), Layer.provide(ProviderMaintenanceRunner.layer), Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)), // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 37605c48f9..0d5f20f721 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -116,6 +116,8 @@ export default mergeConfig( }, } : {}), + // jsonc-parser's UMD main requires its own files at runtime, which the bundle cannot follow. + alias: { "jsonc-parser": "jsonc-parser/lib/esm/main.js" }, deps: { // alwaysBundle=false has no opinion; neverBundle must retain transitive native acceleration. alwaysBundle: (id: string) => id !== "dependency-cruiser" && shouldBundleCliDependency(id), diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json new file mode 100644 index 0000000000..f0746dc7d2 --- /dev/null +++ b/apps/web/gt.config.json @@ -0,0 +1,9 @@ +{ + "defaultLocale": "en", + "locales": ["de", "es", "fr", "ja", "ko", "pt-BR", "ru", "zh"], + "files": { + "gt": { + "output": "src/i18n/translations/[locale].json" + } + } +} diff --git a/apps/web/index.html b/apps/web/index.html index 8972562697..4e20c9a050 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -15,6 +15,7 @@ const LIGHT_BACKGROUND = "#ffffff"; const DARK_BACKGROUND = "#000000"; const CUSTOM_THEMES_STORAGE_KEY = "t3code:themes:v1"; + const ENVIRONMENT_THEMES_STORAGE_KEY = "t3code:environment-themes:v1"; const THEME_FOLLOW_SYSTEM_STORAGE_KEY = "t3code:theme-follow-system"; const THEME_APPEARANCE_MODE_STORAGE_KEY = "t3code:theme-appearance-mode"; const THEME_HALVES_STORAGE_KEY = "t3code:theme-halves:v1"; @@ -197,12 +198,9 @@ (appearance === value.appearance || isRecord(colors)), ); }; - const findCustomTheme = (themeId) => { - if (RESERVED_THEME_IDS.includes(themeId)) return null; + const findStoredTheme = (storageKey, themeId) => { try { - const parsed = JSON.parse( - window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY) ?? "null", - ); + const parsed = JSON.parse(window.localStorage.getItem(storageKey) ?? "null"); if (!Array.isArray(parsed)) return null; return ( parsed.find((value) => isStoredCustomTheme(value) && value.id === themeId) ?? null @@ -211,6 +209,14 @@ return null; } }; + // Same precedence as getThemeDefinition: saved custom themes, then published ones. + const findCustomTheme = (themeId) => { + if (RESERVED_THEME_IDS.includes(themeId)) return null; + return ( + findStoredTheme(CUSTOM_THEMES_STORAGE_KEY, themeId) ?? + findStoredTheme(ENVIRONMENT_THEMES_STORAGE_KEY, themeId) + ); + }; try { const storedTheme = window.localStorage.getItem("t3code:theme"); @@ -634,6 +640,13 @@ white-space: nowrap; } + + 456code diff --git a/apps/web/package.json b/apps/web/package.json index 133bb322cd..ca719f8e9d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.1.8", + "version": "0.1.9", "private": true, "type": "module", "scripts": { @@ -8,15 +8,18 @@ "dev": "vp dev", "dev:built": "vp build --watch", "build": "vp build", + "i18n:generate": "gt generate", "preview": "vp preview", - "test": "vp test run --passWithNoTests --project unit --project browser" + "test": "vp test run --passWithNoTests --project unit --project browser", + "i18n:translate": "gt translate" }, "dependencies": { "@base-ui/react": "^1.9.0", - "@betteroffice/docx": "0.4.3", + "@betteroffice/docx": "0.5.1", "@betteroffice/fonts": "0.4.0", - "@betteroffice/pptx": "0.2.0", - "@betteroffice/xlsx": "0.3.0", + "@betteroffice/fonts-cjk": "0.4.0", + "@betteroffice/pptx": "0.5.1", + "@betteroffice/xlsx": "0.5.1", "@daypicker/react": "^10.0.1", "@dnd-kit/core": "^6.3.1", "@dnd-kit/modifiers": "^9.0.0", @@ -62,6 +65,7 @@ "effect": "catalog:", "entities": "8.1.0", "fast-xml-parser": "5.7.3", + "gt-react": "11.4.18", "hast-util-to-html": "^9.0.5", "hast-util-to-jsx-runtime": "^2.3.6", "heic-to": "^1.5.2", @@ -106,6 +110,7 @@ "@vitejs/plugin-react": "^6.1.2", "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", + "gt": "2.27.0", "lucide": "^0.564.0", "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsx index 2491e9a813..279e1b70d5 100644 --- a/apps/web/src/AppRoot.tsx +++ b/apps/web/src/AppRoot.tsx @@ -2,16 +2,19 @@ import { RouterProvider } from "@tanstack/react-router"; import { ElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { QuitHoldOverlay } from "./components/QuitHoldOverlay"; +import { I18nProvider } from "./i18n/I18nProvider"; import { AppAtomRegistryProvider } from "./rpc/atomRegistry"; import type { AppRouter } from "./router"; // Keep webviews outside the router but inside its atom registry so route changes preserve them. export function AppRoot({ router }: { readonly router: AppRouter }) { return ( - - - - - + + + + + + + ); } diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index 69fb583eb7..3b3f4101fe 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -1,4 +1,9 @@ -import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + scopedThreadKey, + scopeProjectRef, + scopeThreadRef, +} from "@t3tools/client-runtime/environment"; +import type { ScopedThreadRef } from "@t3tools/contracts"; import type { ClientSettings } from "@t3tools/contracts/settings"; import { createBrowserHistory, createHashHistory } from "@tanstack/react-router"; import * as Schema from "effect/Schema"; @@ -9,6 +14,7 @@ import { startElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter"; import { startPreviewTitleRecording } from "./browserHistoryStore"; import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention"; +import { resolveWindowTitleThreadStatus } from "./components/Sidebar.logic"; import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer"; import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator"; import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast"; @@ -21,7 +27,7 @@ import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoord import { startThreadNotifications } from "./components/ThreadNotificationCoordinator"; import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator"; import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding"; -import { resolveServerBackedAppDisplayName } from "./branding.logic"; +import { resolveServerBackedAppDisplayName, resolveWindowTitle } from "./branding.logic"; import { isElectron } from "./env"; import { subscribeComposerDraftModelReconciliation, @@ -30,6 +36,7 @@ import { } from "./composerDraftStore"; import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme"; import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme"; +import { startThemeBackground } from "./themeBackground"; import { readLocalStorageValue, subscribeLocalStorageKey } from "./hooks/useLocalStorage"; import { startHostEnvironmentLookup } from "./state/primaryEnvironment"; import { @@ -47,14 +54,16 @@ import { import { startProviderAuthDelivery } from "./providerAuthDelivery"; import { getRouter, type AppRouter } from "./router"; import { appAtomRegistry } from "./rpc/atomRegistry"; +import { environmentProjects } from "./state/projects"; import { primaryServerConfigAtom } from "./state/server"; import { environmentShell } from "./state/shell"; import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; +import { startI18n } from "./i18n/runtime"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; -import { resolveThreadRouteTarget } from "./threadRoutes"; +import { resolveActiveThreadRouteRef, resolveThreadRouteTarget } from "./threadRoutes"; /** Writes appearance settings onto the document, touching only the groups that changed. */ function startClientAppearance(): void { @@ -120,19 +129,82 @@ function startClientAppearance(): void { apply(); } -function startDocumentTitle(): void { - appAtomRegistry.subscribe( - primaryServerConfigAtom, - (config) => { - document.title = resolveServerBackedAppDisplayName({ +function readOpenThreadRef(router: AppRouter): ScopedThreadRef | null { + const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {}); + const draft = + target?.kind === "draft" + ? useComposerDraftStore.getState().getDraftSession(target.draftId) + : null; + return resolveActiveThreadRouteRef(target, draft); +} + +/** + * Names the open thread and its project in the window title, or the app when none is open. + * Screen readers read it on Alt+Tab, so it can lead with the thread and what it's doing. + */ +function startDocumentTitle(router: AppRouter): void { + let openThreadRef = readOpenThreadRef(router); + const write = () => { + const thread = + openThreadRef === null + ? null + : appAtomRegistry.get(environmentThreadShells.quietThreadShellAtom(openThreadRef)); + const project = + thread === null + ? null + : appAtomRegistry.get( + environmentProjects.projectAtom( + scopeProjectRef(thread.environmentId, thread.projectId), + ), + ); + const title = resolveWindowTitle({ + appDisplayName: resolveServerBackedAppDisplayName({ baseName: APP_BASE_NAME, fallbackDisplayName: APP_DISPLAY_NAME, fallbackStageLabel: APP_STAGE_LABEL, - primaryServerVersion: config?.environment.serverVersion ?? null, - }); - }, - { immediate: true }, - ); + primaryServerVersion: + appAtomRegistry.get(primaryServerConfigAtom)?.environment.serverVersion ?? null, + }), + projectTitle: project?.title ?? null, + threadTitle: thread?.title ?? null, + ...(getClientSettings().screenReaderWindowTitle && { + screenReader: { + threadStatus: thread === null ? null : resolveWindowTitleThreadStatus(thread), + }, + }), + desktop: isElectron, + }); + // Projects change whenever any project does; most changes leave the title alone. + if (document.title !== title) document.title = title; + }; + // The open thread's own shell, since the shell lists skip threads hidden by a tag filter. + let unsubscribeOpenThread = () => {}; + const watchOpenThread = () => { + unsubscribeOpenThread(); + unsubscribeOpenThread = + openThreadRef === null + ? () => {} + : appAtomRegistry.subscribe( + environmentThreadShells.quietThreadShellAtom(openThreadRef), + write, + ); + }; + // The draft store changes on every keystroke; only a new open thread matters here. + const updateOpenThread = () => { + const next = readOpenThreadRef(router); + if ((next && scopedThreadKey(next)) === (openThreadRef && scopedThreadKey(openThreadRef))) { + return; + } + openThreadRef = next; + watchOpenThread(); + write(); + }; + watchOpenThread(); + appAtomRegistry.subscribe(primaryServerConfigAtom, write, { immediate: true }); + appAtomRegistry.subscribe(environmentProjects.projectsAtom, write); + subscribeClientSettings(write); + router.subscribe("onResolved", updateOpenThread); + useComposerDraftStore.subscribe(updateOpenThread); } /** @@ -183,9 +255,11 @@ export function startAppServices(): AppRouter { installDesktopPasteAsText(window.desktopBridge, window); startClientAppearance(); - startDocumentTitle(); + startI18n(); + startDocumentTitle(router); startHostEnvironmentLookup(); startEnvironmentThemeRepaint(); + startThemeBackground(); startBrowserChromeThemeSync(router); startDefaultThemeAdoption(); startModelPreferencesMigration(); diff --git a/apps/web/src/appearanceFonts.browser.test.ts b/apps/web/src/appearanceFonts.browser.test.ts index 9bdc5c2ef9..289e48ecad 100644 --- a/apps/web/src/appearanceFonts.browser.test.ts +++ b/apps/web/src/appearanceFonts.browser.test.ts @@ -52,4 +52,40 @@ describe("applyAppearanceFontVariables", () => { else root.setAttribute("style", style); } }); + + it("widens the numbered-list gutter only when the interface font's marker would clip", () => { + const root = document.documentElement; + const style = root.getAttribute("style"); + const gutter = (sans: string) => { + applyAppearanceFontVariables(root, { + sans, + code: "", + composer: "", + sizeInterface: 16, + sizePrompt: 14, + sizeCode: 13, + smoothing: true, + separate: false, + }); + const markdown = document.createElement("div"); + markdown.className = "chat-markdown"; + markdown.style.fontSize = "14px"; + const list = document.createElement("ol"); + markdown.append(list); + document.body.append(markdown); + try { + return Number.parseFloat(getComputedStyle(list).paddingInlineStart); + } finally { + markdown.remove(); + } + }; + try { + // `0. ` in a 14px monospace font is about 25px, past the 20px default. + expect(gutter("monospace")).toBeGreaterThan(24); + expect(gutter("sans-serif")).toBe(20); + } finally { + if (style === null) root.removeAttribute("style"); + else root.setAttribute("style", style); + } + }); }); diff --git a/apps/web/src/appearanceFonts.ts b/apps/web/src/appearanceFonts.ts index ba605fb9ee..d6d72175a9 100644 --- a/apps/web/src/appearanceFonts.ts +++ b/apps/web/src/appearanceFonts.ts @@ -92,6 +92,16 @@ export function applyAppearanceFontVariables( } } + const markerWidth = probeWidth( + appearanceFontStack(preferences.sans, DEFAULT_SANS_FONT_STACK), + LIST_MARKER_PROBE_TEXT, + ); + if (markerWidth === null) { + root.style.removeProperty("--list-marker-sans"); + } else { + root.style.setProperty("--list-marker-sans", `${(markerWidth / PROBE_FONT_SIZE).toFixed(3)}em`); + } + root.style.fontSize = `${clampInterfaceFontSize(preferences.sizeInterface)}px`; root.style.setProperty( "--font-size-prompt", @@ -131,15 +141,18 @@ function clampCodeFontSize(value: number): number { } const FONT_PROBE_TEXT = "mmmmmmmmMMWli1O0@# fjord"; +// The widest single-digit `ol` marker; CSS can't measure it to size the list gutter. +const LIST_MARKER_PROBE_TEXT = "0. "; +const PROBE_FONT_SIZE = 16; let fontProbeContext: CanvasRenderingContext2D | null | undefined; -function probeWidth(fontList: string): number | null { +function probeWidth(fontList: string, text = FONT_PROBE_TEXT): number | null { if (fontProbeContext === undefined) { fontProbeContext = document.createElement("canvas").getContext("2d"); } if (fontProbeContext === null) return null; - fontProbeContext.font = `16px ${fontList}`; - return fontProbeContext.measureText(FONT_PROBE_TEXT).width; + fontProbeContext.font = `${PROBE_FONT_SIZE}px ${fontList}`; + return fontProbeContext.measureText(text).width; } /** Probes canvas metrics because document.fonts.check() accepts uninstalled families. */ @@ -267,6 +280,18 @@ function resolveGenericFamilyLabel(generic: string): string | null { return null; } +// Synthetic Apple labels are not necessarily available as named CSS families. +export function displayFontFamily(family: string): string { + const label = family + .trim() + .replace(/^(['"])(.*)\1$/, "$2") + .trim() + .toLowerCase(); + if (label === "sf pro") return appearanceFontStack(family, DEFAULT_SANS_FONT_STACK); + if (label === "sf mono") return DEFAULT_CODE_FONT_STACK; + return cssFontFamilies(family) ?? ""; +} + export function resolveDefaultFamilyLabel(stack: string): string | null { for (const raw of stack.split(",")) { const family = raw.trim().replace(/^(['"])(.*)\1$/, "$2"); diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts index 65c6f8edd3..8d834ed9ac 100644 --- a/apps/web/src/authBootstrap.test.ts +++ b/apps/web/src/authBootstrap.test.ts @@ -8,6 +8,7 @@ import { import { createBrowserHistory } from "@tanstack/react-router"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import { HttpClientError, HttpClientRequest } from "effect/http"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { installEnvironmentHttpTest } from "../test/environmentHttpTest"; @@ -165,6 +166,54 @@ describe("resolveInitialServerAuthGateState", () => { expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]); }); + it("retries the desktop bootstrap while the backend is still unreachable", async () => { + const nextSession = sequence( + unauthenticatedSession(DESKTOP_AUTH), + authenticatedSession(DESKTOP_AUTH), + ); + const testApi = await installAuthApi({ + session: nextSession, + browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])), + }); + // What FetchHttpClient yields when nothing listens on the backend port. + const connectionRefused = new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request: HttpClientRequest.get("http://localhost:3773/api/auth/session"), + cause: new TypeError("Failed to fetch"), + }), + }); + let unreachableAttempts = 1; + __setPrimaryHttpRunnerForTests((effect) => { + if (unreachableAttempts > 0) { + unreachableAttempts -= 1; + return Promise.reject(connectionRefused); + } + return testApi.run(effect); + }); + + const testWindow = installTestBrowser("http://localhost/"); + testWindow.desktopBridge = { + getLocalEnvironmentBootstraps: () => [ + { + id: "primary", + label: "Local", + httpBaseUrl: "http://localhost:3773", + wsBaseUrl: "ws://localhost:3773", + bootstrapToken: "desktop-bootstrap-token", + }, + ], + } as unknown as DesktopBridge; + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + vi.useFakeTimers({ toFake: ["setTimeout", "Date"] }); + await Promise.all([ + expect(resolveInitialServerAuthGateState()).resolves.toEqual({ status: "authenticated" }), + vi.advanceTimersByTimeAsync(1_000), + ]); + expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]); + }); + it("takes a pairing token from the location hash and strips it immediately", async () => { const testWindow = installTestBrowser("http://localhost/#token=pairing-token"); const { takePairingTokenFromUrl } = await import("./environments/primary"); @@ -279,7 +328,9 @@ describe("resolveInitialServerAuthGateState", () => { await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth); // Token removal synchronously reloads the TanStack auth gate via replaceState. + const pairingHistoryState = history.location.state; const token = takePairingTokenFromUrl(); + expect(history.location.state).toEqual(pairingHistoryState); expect(gateLoads).toHaveLength(1); await expect(gateLoads[0]).resolves.toEqual(requiresAuth); const rejected = expect(submitServerAuthCredential(token!)).rejects.toMatchObject({ diff --git a/apps/web/src/branding.logic.ts b/apps/web/src/branding.logic.ts index 126fb77062..328360a469 100644 --- a/apps/web/src/branding.logic.ts +++ b/apps/web/src/branding.logic.ts @@ -11,6 +11,21 @@ export function formatAppDisplayName(input: { return `${input.baseName} (${input.stageLabel})`; } +function resolveHostedAppChannelLabel(channel: string | null | undefined): string | null { + const normalized = channel?.trim().toLowerCase(); + return normalized === "nightly" ? "Nightly" : normalized === "latest" ? "Latest" : null; +} + +/** Stage label of a web build. vite.config.ts stamps it into index.html's title too. */ +export function resolveWebAppStageLabel(input: { + readonly hostedAppChannel: string | null | undefined; + readonly development: boolean; +}): string { + return ( + resolveHostedAppChannelLabel(input.hostedAppChannel) ?? (input.development ? "Dev" : "Beta") + ); +} + export function resolveServerBackedAppStageLabel(input: { readonly primaryServerVersion: string | null | undefined; readonly fallbackStageLabel: string; @@ -36,3 +51,32 @@ export function resolveServerBackedAppDisplayName(input: { ? input.fallbackDisplayName : formatAppDisplayName({ baseName: input.baseName, stageLabel }); } + +/** + * Names the open thread: `project / thread` on desktop, where the OS already + * shows the app, with the app name appended in browser tabs. + */ +export function resolveWindowTitle(input: { + readonly appDisplayName: string; + readonly projectTitle: string | null; + readonly threadTitle: string | null; + /** The screen reader title: status, then thread, then project, since a screen reader reads from the start. */ + readonly screenReader?: { readonly threadStatus: string | null }; + readonly desktop: boolean; +}): string { + const threadTitle = input.threadTitle?.trim() ?? ""; + const status = input.screenReader?.threadStatus; + if (threadTitle === "") { + return status ? `${status}: ${input.appDisplayName}` : input.appDisplayName; + } + + const projectTitle = input.projectTitle?.trim() ?? ""; + const context = + projectTitle === "" + ? threadTitle + : input.screenReader + ? `${threadTitle} - ${projectTitle}` + : `${projectTitle} / ${threadTitle}`; + const title = status ? `${status}: ${context}` : context; + return input.desktop ? title : `${title} - ${input.appDisplayName}`; +} diff --git a/apps/web/src/branding.ts b/apps/web/src/branding.ts index 80b528017f..51946df589 100644 --- a/apps/web/src/branding.ts +++ b/apps/web/src/branding.ts @@ -1,5 +1,5 @@ import type { DesktopAppBranding } from "@t3tools/contracts"; -import { formatAppDisplayName } from "./branding.logic"; +import { formatAppDisplayName, resolveWebAppStageLabel } from "./branding.logic"; function readInjectedDesktopAppBranding(): DesktopAppBranding | null { if (typeof window === "undefined") { @@ -12,7 +12,8 @@ function readInjectedDesktopAppBranding(): DesktopAppBranding | null { const injectedDesktopAppBranding = readInjectedDesktopAppBranding(); export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "456code"; export const APP_STAGE_LABEL = - injectedDesktopAppBranding?.stageLabel ?? (import.meta.env.DEV ? "Dev" : "Beta"); + injectedDesktopAppBranding?.stageLabel ?? + resolveWebAppStageLabel({ hostedAppChannel: null, development: import.meta.env.DEV }); export const APP_DISPLAY_NAME = injectedDesktopAppBranding?.displayName ?? formatAppDisplayName({ baseName: APP_BASE_NAME, stageLabel: APP_STAGE_LABEL }); diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index 34c7978b7b..023fb03c3a 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -7,6 +7,10 @@ import { useShallow } from "zustand/react/shallow"; import { useEffect, useEffectEvent, useRef, useState } from "react"; import { previewBridge } from "~/components/preview/previewBridge"; +import { + preventThumbButtonFocus, + takeThumbButtonNavigation, +} from "~/components/preview/thumbButtons"; import { usePreviewBridge } from "~/components/preview/usePreviewBridge"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; import { cn, isMacPlatform } from "~/lib/utils"; @@ -16,6 +20,7 @@ import { useActiveBrowserRecordingTabIds } from "./browserRecording"; import { browserViewportSettingKey, resolveBrowserViewportLayout, + resolveBrowserViewportTransform, resolveFittedBrowserViewport, } from "./browserViewportLayout"; import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar"; @@ -180,16 +185,24 @@ export function HostedBrowserWebview(props: { if (!disposed) remountCrashedWebview(); }, recovery.delayMs); }; - // Guest clicks only emit focus here; replay pointerdown to dismiss host popups. + // Guest clicks never reach this document, so replay a pointerdown to dismiss host popups. + // The guest preload reports each press, since the guest does not always take focus. const dismissHostPopups = () => { webview.dispatchEvent( new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }), ); }; + const guestPointerDown = (event: Event) => { + // Mirrors POINTER_DOWN_HOST_CHANNEL in apps/desktop/src/preview/GuestProtocol.ts. + if ((event as Event & { channel?: string }).channel === "preview:pointer-down") { + dismissHostPopups(); + } + }; webview.addEventListener("did-attach", register); webview.addEventListener("dom-ready", register); webview.addEventListener("render-process-gone", recoverGuest); webview.addEventListener("focus", dismissHostPopups); + webview.addEventListener("ipc-message", guestPointerDown); register(); return () => { disposed = true; @@ -198,6 +211,7 @@ export function HostedBrowserWebview(props: { webview.removeEventListener("dom-ready", register); webview.removeEventListener("render-process-gone", recoverGuest); webview.removeEventListener("focus", dismissHostPopups); + webview.removeEventListener("ipc-message", guestPointerDown); }; }, [ clientSettingsHydrated, @@ -300,9 +314,33 @@ export function HostedBrowserWebview(props: { return () => withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, false)); }, [clientSettingsHydrated, runtimeTabId, serverDriven, shown]); + // Captures copy the guest's raster, which a scaled guest only keeps at full detail on request. + const fullDetail = backgroundActivity || pictureInPicture || recordingActive; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the desktop host once the guest is drawn at full detail, so its screenshot waits for that frame + useEffect(() => { + const bridge = window.desktopBridge?.preview; + if (!clientSettingsHydrated || !bridge || !serverDriven || !fullDetail) return; + let frame = requestAnimationFrame(() => { + frame = requestAnimationFrame(() => + withDesktopTab(runtimeTabId, () => bridge.setCaptureDrawn(runtimeTabId, true)), + ); + }); + return () => { + cancelAnimationFrame(frame); + withDesktopTab(runtimeTabId, () => bridge.setCaptureDrawn(runtimeTabId, false)); + }; + }, [clientSettingsHydrated, fullDetail, runtimeTabId, serverDriven]); + if (!clientSettingsHydrated || !config) return null; + // This fixed wrapper sits outside the right panel shell, so it takes thumb presses itself. + const navigateThumb = (direction: "back" | "forward") => { + if (direction === "back") void previewBridge?.goBack(runtimeTabId); + else void previewBridge?.goForward(runtimeTabId); + }; + const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive; + const viewportTransform = resolveBrowserViewportTransform(layout.viewportScale, fullDetail); const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({ active, renderingActive, @@ -320,6 +358,8 @@ export function HostedBrowserWebview(props: { className="fixed overflow-hidden bg-muted/35" style={{ ...wrapperStyle, overscrollBehavior: "contain" }} onScroll={syncContentPresentation} + onMouseDown={preventThumbButtonFocus} + onMouseUp={(event) => takeThumbButtonNavigation(event, navigateThumb)} data-preview-rendering={renderingActive ? "active" : "suspended"} data-preview-viewport={runtimeTabId} > @@ -333,47 +373,56 @@ export function HostedBrowserWebview(props: { onChange={commitViewportChange} /> ) : null} - + > + + {active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? ( <> void; readonly history: (delta: -1 | 1) => void; readonly reload: (options?: { readonly ignoreCache?: boolean }) => void; + readonly stopLoading: () => void; readonly viewport: (setting: PreviewViewportSetting) => void; readonly canvas: () => HTMLCanvasElement | null; } @@ -311,6 +312,7 @@ export function ServerBrowserSurface(props: { history: (delta) => send({ type: "history", delta }), reload: (options) => send({ type: "reload", ...(options?.ignoreCache ? { ignoreCache: true } : {}) }), + stopLoading: () => send({ type: "stopLoading" }), viewport: (setting) => send({ type: "viewport", setting }), canvas: () => (!pdfUrl && hasFrameRef.current ? canvasRef.current : null), }), diff --git a/apps/web/src/browser/browserDefaults.ts b/apps/web/src/browser/browserDefaults.ts index bf1c2da40d..5cc74bb1b7 100644 --- a/apps/web/src/browser/browserDefaults.ts +++ b/apps/web/src/browser/browserDefaults.ts @@ -5,6 +5,7 @@ import { type DesktopPreviewTabDefaults, type PreviewAppearancePreference, type PreviewViewportSetting, + type PreviewZoomFactor, } from "@t3tools/contracts"; import { @@ -17,7 +18,7 @@ import { resolveResponsiveBrowserViewportSize } from "./browserViewportLayout"; export interface BrowserDefaults { readonly viewport: PreviewViewportSetting; - readonly zoomFactor: number; + readonly zoomFactor: PreviewZoomFactor; readonly appearance: PreviewAppearancePreference; readonly autoShowFloatingPreview: boolean; readonly profiles: ReadonlyArray; @@ -26,7 +27,7 @@ export interface BrowserDefaults { const toBrowserDefaults = (settings: { readonly browserDefaultViewport: PreviewViewportSetting; - readonly browserDefaultZoomFactor: number; + readonly browserDefaultZoomFactor: PreviewZoomFactor; readonly browserDefaultAppearance: PreviewAppearancePreference; readonly browserAutoShowFloatingPreview: boolean; readonly browserProfiles: ReadonlyArray; diff --git a/apps/web/src/browser/browserLinkTarget.ts b/apps/web/src/browser/browserLinkTarget.ts index f1c4e65a99..74330bf3ed 100644 --- a/apps/web/src/browser/browserLinkTarget.ts +++ b/apps/web/src/browser/browserLinkTarget.ts @@ -7,6 +7,9 @@ import { import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings"; import { readEnvironmentScope } from "~/state/session"; import { isPreviewAvailableFor } from "./previewRuntime"; +import { isWebUrl } from "./webUrl"; + +export { isWebUrl }; export interface ResolveLinkTargetInput { readonly url: string; @@ -27,15 +30,6 @@ export function resolveLinkTarget(input: ResolveLinkTargetInput): BrowserLinkTar return "app"; } -export function isWebUrl(url: string): boolean { - try { - const { protocol } = new URL(url); - return protocol === "http:" || protocol === "https:"; - } catch { - return false; - } -} - /** Before hydration, the default "system" would ignore a saved "app" link target. */ export async function resolveBrowserLinkTargetPreference(): Promise { await ensureClientSettingsHydrated(); diff --git a/apps/web/src/browser/browserRecording.test.ts b/apps/web/src/browser/browserRecording.test.ts index b0e8cc62ab..5944c3e6cf 100644 --- a/apps/web/src/browser/browserRecording.test.ts +++ b/apps/web/src/browser/browserRecording.test.ts @@ -69,6 +69,10 @@ vi.mock(import("~/components/preview/previewBridge"), async (original) => { } }); +vi.mock("./recordingCompositor", () => ({ + createRecordingCompositor: async (stream: MediaStream) => ({ stream, dispose: () => {} }), +})); + vi.mock("~/rpc/atomRegistry", () => ({ appAtomRegistry: { set: registrySet }, })); diff --git a/apps/web/src/browser/browserRecording.ts b/apps/web/src/browser/browserRecording.ts index ededb45c9e..ef1f95309e 100644 --- a/apps/web/src/browser/browserRecording.ts +++ b/apps/web/src/browser/browserRecording.ts @@ -144,7 +144,7 @@ interface ActiveRecording { releaseSurfaceActivity: (() => void) | null; stream: MediaStream | null; recorder: MediaRecorder | null; - compositor: Awaited>; + compositor: Awaited> | null; lifecycle: BrowserRecordingLifecycle; } @@ -641,7 +641,7 @@ export async function startBrowserRecording( if (event.tabId === tabId) listener(event.input); }), ); - recorder = createMediaRecorder(recording.compositor?.stream ?? stream); + recorder = createMediaRecorder(recording.compositor.stream); recording.recorder = recorder; recorder.addEventListener("dataavailable", (event) => { if (event.data.size > 0) chunks.push(event.data); diff --git a/apps/web/src/browser/browserViewportLayout.test.ts b/apps/web/src/browser/browserViewportLayout.test.ts index 1932a634fb..c72f68e1e2 100644 --- a/apps/web/src/browser/browserViewportLayout.test.ts +++ b/apps/web/src/browser/browserViewportLayout.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test"; import { resizeBrowserViewportFromRail, + resolveBrowserViewportTransform, resolveFittedBrowserViewport, } from "./browserViewportLayout"; @@ -43,3 +44,19 @@ describe("resolveBrowserViewportLayout", () => { ).toEqual({ width: 460, height: 409 }); }); }); + +describe("resolveBrowserViewportTransform", () => { + it("keeps a full-detail guest at raster scale 1 while it draws at the fitted scale", () => { + expect(resolveBrowserViewportTransform(1, true)).toBeUndefined(); + expect(resolveBrowserViewportTransform(0.6, false)).toBe("scale(0.6)"); + const values = resolveBrowserViewportTransform(0.6, true) + ?.match(/^matrix3d\((.*)\)$/)?.[1] + ?.split(",") + .map(Number); + // Column-major: the x and y columns keep their 0.6 screen terms and reach length 1 through z. + expect(values?.slice(0, 2)).toEqual([0.6, 0]); + expect(values?.slice(4, 6)).toEqual([0, 0.6]); + expect(Math.hypot(...(values?.slice(0, 3) ?? []))).toBeCloseTo(1); + expect(Math.hypot(...(values?.slice(4, 7) ?? []))).toBeCloseTo(1); + }); +}); diff --git a/apps/web/src/browser/browserViewportLayout.ts b/apps/web/src/browser/browserViewportLayout.ts index 2fe4e03510..7fe6b170c6 100644 --- a/apps/web/src/browser/browserViewportLayout.ts +++ b/apps/web/src/browser/browserViewportLayout.ts @@ -125,6 +125,22 @@ export function resolveBrowserViewportLayout( }; } +/** + * Chromium rasters a CSS-scaled guest at its on-screen scale, so captures of it lose detail. + * Its raster scale also counts x/y-to-z terms, which a `preserve-3d` parent keeps and the + * screen drops, so `fullDetail` draws like `scale()` but keeps full-resolution frames. + */ +export function resolveBrowserViewportTransform( + scale: number, + fullDetail: boolean, +): string | undefined { + if (scale >= 1) return undefined; + if (!fullDetail) return `scale(${scale})`; + // Positive depth keeps the guest in front of its parent for hit testing. + const depth = Math.sqrt(1 - scale * scale); + return `matrix3d(${scale}, 0, ${depth}, 0, 0, ${scale}, ${depth}, 0, 0, 0, 1, 0, 0, 0, 0, 1)`; +} + export function resolveBrowserDeviceViewportLayout( container: { readonly width: number; readonly height: number }, setting: Exclude, diff --git a/apps/web/src/browser/openFileInPreview.ts b/apps/web/src/browser/openFileInPreview.ts index a997ee2b55..db1a58e98d 100644 --- a/apps/web/src/browser/openFileInPreview.ts +++ b/apps/web/src/browser/openFileInPreview.ts @@ -85,7 +85,9 @@ export async function openUrlInPreview(input: { url: input.url, viewport: defaults.viewport, profileId: input.profileId ?? defaults.profileId, - ...(runtime === undefined ? {} : { runtime }), + ...(runtime === undefined + ? {} + : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }), }, }); return mapAtomCommandResult(result, (snapshot) => { diff --git a/apps/web/src/browser/recordingCompositor.browser.test.ts b/apps/web/src/browser/recordingCompositor.browser.test.ts new file mode 100644 index 0000000000..b817252692 --- /dev/null +++ b/apps/web/src/browser/recordingCompositor.browser.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { createRecordingCompositor } from "./recordingCompositor"; + +const paintSource = (canvas: HTMLCanvasElement, color: string) => { + const context = canvas.getContext("2d"); + if (!context) throw new Error("Source canvas is unavailable."); + context.fillStyle = color; + context.fillRect(0, 0, canvas.width, canvas.height); +}; + +const samplePixel = (video: HTMLVideoElement, x: number, y: number) => { + const canvas = document.createElement("canvas"); + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + const context = canvas.getContext("2d", { willReadFrequently: true }); + if (!context) throw new Error("Sample canvas is unavailable."); + context.drawImage(video, 0, 0); + return Array.from(context.getImageData(x, y, 1, 1).data.slice(0, 3)); +}; + +describe("recording compositor", () => { + it("keeps the starting size and letterboxes a resized source", async () => { + const source = document.createElement("canvas"); + source.width = 320; + source.height = 180; + paintSource(source, "#f00"); + const sourceStream = source.captureStream(30); + const compositor = await createRecordingCompositor( + sourceStream, + { showKeyPresses: false, showMousePresses: false, frameRate: 30 }, + () => () => {}, + ); + const output = document.createElement("video"); + output.muted = true; + output.srcObject = compositor.stream; + try { + await output.play(); + await vi.waitFor(() => { + expect([output.videoWidth, output.videoHeight]).toEqual([320, 180]); + expect(samplePixel(output, 160, 90)).toEqual([255, 0, 0]); + }); + + source.width = 90; + source.height = 160; + paintSource(source, "#0f0"); + + await vi.waitFor(() => { + paintSource(source, "#0f0"); + expect(samplePixel(output, 160, 90)).toEqual([0, 255, 0]); + }); + expect([output.videoWidth, output.videoHeight]).toEqual([320, 180]); + expect(samplePixel(output, 10, 90)).toEqual([0, 0, 0]); + } finally { + output.srcObject = null; + compositor.dispose(); + for (const track of sourceStream.getTracks()) track.stop(); + } + }); +}); diff --git a/apps/web/src/browser/recordingCompositor.ts b/apps/web/src/browser/recordingCompositor.ts index 07e19c78d1..67d9964846 100644 --- a/apps/web/src/browser/recordingCompositor.ts +++ b/apps/web/src/browser/recordingCompositor.ts @@ -13,7 +13,6 @@ export async function createRecordingCompositor( options: RecordingDecorationOptions, subscribe: (listener: (input: DesktopPreviewRecordingInput) => void) => () => void, ) { - if (!options.showKeyPresses && !options.showMousePresses) return null; const canvas = document.createElement("canvas"); const context = canvas.getContext("2d", { alpha: false }); if (!context) throw new Error("Recording canvas is unavailable."); @@ -26,17 +25,35 @@ export async function createRecordingCompositor( canvas.height = settings?.height ?? 1080; const decorations = new RecordingDecorations(options, readPreviewAnnotationTheme().primary); let disposed = false; + let sized = false; let frameId: number | undefined; let timer: number | undefined; const draw = () => { if (disposed || video.readyState < 2) return; - const width = video.videoWidth || canvas.width; - const height = video.videoHeight || canvas.height; - if (canvas.width !== width) canvas.width = width; - if (canvas.height !== height) canvas.height = height; - context.drawImage(video, 0, 0, width, height); + // The encoded size stays at the first frame's: avc1 MP4 stores one set of decoder + // parameters, so a resized source is letterboxed instead of changing the stream size. + if (!sized) { + canvas.width = video.videoWidth || canvas.width; + canvas.height = video.videoHeight || canvas.height; + sized = true; + } + const sourceWidth = video.videoWidth || canvas.width; + const sourceHeight = video.videoHeight || canvas.height; + const fit = Math.min(canvas.width / sourceWidth, canvas.height / sourceHeight); + const width = Math.round(sourceWidth * fit); + const height = Math.round(sourceHeight * fit); + const left = Math.floor((canvas.width - width) / 2); + const top = Math.floor((canvas.height - height) / 2); + if (width < canvas.width || height < canvas.height) { + context.fillStyle = "#000"; + context.fillRect(0, 0, canvas.width, canvas.height); + } + context.drawImage(video, left, top, width, height); const now = performance.now(); + context.save(); + context.translate(left, top); decorations.draw(context, width, height, now); + context.restore(); window.clearTimeout(timer); const next = decorations.nextRedraw(now); if (next !== null) timer = window.setTimeout(draw, next); diff --git a/apps/web/src/browser/serverPictureInPicture.browser.test.ts b/apps/web/src/browser/serverPictureInPicture.browser.test.ts new file mode 100644 index 0000000000..d1f439fae7 --- /dev/null +++ b/apps/web/src/browser/serverPictureInPicture.browser.test.ts @@ -0,0 +1,55 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +const mocks = vi.hoisted(() => ({ readAccess: vi.fn() })); + +vi.mock(import("~/state/previewStream"), () => ({ + readPreviewStreamAccess: mocks.readAccess, +})); + +import { closeServerPictureInPicture, openServerPictureInPicture } from "./serverPictureInPicture"; + +function setup() { + return { + [Symbol.dispose]() { + closeServerPictureInPicture(); + mocks.readAccess.mockReset(); + }, + }; +} + +it("cancels pending playback without reporting a failed popout", async () => { + using _cleanup = setup(); + const opening = openServerPictureInPicture({ + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread"), + tabId: "tab", + seed: null, + }); + const video = document.querySelector("video")!; + const tracks = (video.srcObject as MediaStream).getTracks(); + closeServerPictureInPicture(); + await expect(opening).resolves.toBeUndefined(); + expect(video.isConnected).toBe(false); + expect(tracks.length).toBeGreaterThan(0); + expect(tracks.every((track) => track.readyState === "ended")).toBe(true); + expect(mocks.readAccess).not.toHaveBeenCalled(); +}); + +it("still reports playback failures for an active popout", async () => { + using _cleanup = setup(); + const error = new Error("Playback failed"); + using _play = vi.spyOn(HTMLMediaElement.prototype, "play").mockRejectedValue(error); + const opening = openServerPictureInPicture({ + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread"), + tabId: "tab", + seed: null, + }); + const video = document.querySelector("video")!; + const tracks = (video.srcObject as MediaStream).getTracks(); + await expect(opening).rejects.toBe(error); + expect(video.isConnected).toBe(false); + expect(tracks.every((track) => track.readyState === "ended")).toBe(true); + expect(mocks.readAccess).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/browser/serverPictureInPicture.ts b/apps/web/src/browser/serverPictureInPicture.ts index fda9ec7fa7..04b6d3ddd8 100644 --- a/apps/web/src/browser/serverPictureInPicture.ts +++ b/apps/web/src/browser/serverPictureInPicture.ts @@ -175,6 +175,7 @@ export async function openServerPictureInPicture(input: { video.webkitSetPresentationMode?.("picture-in-picture"); } } catch (error) { + if (stopped) return; onLeave(); throw error; } diff --git a/apps/web/src/browser/webUrl.ts b/apps/web/src/browser/webUrl.ts new file mode 100644 index 0000000000..19e637794b --- /dev/null +++ b/apps/web/src/browser/webUrl.ts @@ -0,0 +1,8 @@ +export function isWebUrl(url: string): boolean { + try { + const { protocol } = new URL(url); + return protocol === "http:" || protocol === "https:"; + } catch { + return false; + } +} diff --git a/apps/web/src/browserHistoryStore.test.ts b/apps/web/src/browserHistoryStore.test.ts index c68d3334b6..bc0aa9a29d 100644 --- a/apps/web/src/browserHistoryStore.test.ts +++ b/apps/web/src/browserHistoryStore.test.ts @@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { + type BrowserProfileId, EnvironmentId, + INCOGNITO_BROWSER_PROFILE_ID, type PreviewSessionSnapshot, ProjectId, ThreadId, @@ -157,7 +159,13 @@ const threadRef = { let settledAt = 0; -function settle(url: string, title: string, tabId = "tab_a", ref = threadRef): void { +function settle( + url: string, + title: string, + tabId = "tab_a", + ref = threadRef, + profileId?: BrowserProfileId, +): void { settledAt += 1; const snapshot: PreviewSessionSnapshot = { threadId: ref.threadId, @@ -166,6 +174,7 @@ function settle(url: string, title: string, tabId = "tab_a", ref = threadRef): v canGoBack: false, canGoForward: false, updatedAt: new Date(settledAt).toISOString(), + ...(profileId ? { profileId } : {}), }; applyPreviewServerSnapshot(ref, snapshot); } @@ -208,6 +217,17 @@ describe("useBrowserHistoryStore", () => { expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("New"); }); + it("never titles history from an Incognito page, whichever settles first", () => { + useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a"); + settle("http://a.test/", "Private A", "tab_incognito", threadRef, INCOGNITO_BROWSER_PROFILE_ID); + recordVisitForThread(threadRef, "http://a.test/", 1); + recordVisitForThread(threadRef, "http://b.test/", 2); + settle("http://b.test/", "Private B", "tab_incognito", threadRef, INCOGNITO_BROWSER_PROFILE_ID); + expect( + useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((entry) => entry.title), + ).toEqual([undefined, undefined]); + }); + it("keeps another thread's newer title when an unrelated tab settles", () => { const otherThreadRef = { ...threadRef, threadId: ThreadId.make("thread-2") }; const store = useBrowserHistoryStore.getState(); diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index fe1982f742..d5ccb0fcd6 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -3,11 +3,12 @@ import { scopedThreadKey, scopeProjectRef, } from "@t3tools/client-runtime/environment"; -import type { - EnvironmentId, - PreviewSessionSnapshot, - ScopedProjectRef, - ScopedThreadRef, +import { + type EnvironmentId, + INCOGNITO_BROWSER_PROFILE_ID, + type PreviewSessionSnapshot, + type ScopedProjectRef, + type ScopedThreadRef, } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; @@ -468,6 +469,7 @@ function recordPreviewTitles( ); for (const session of sessions) { const status = session.navStatus; + if (session.profileId === INCOGNITO_BROWSER_PROFILE_ID) continue; if (status._tag !== "Success" || !status.title || !include(session, status.url)) continue; state.setTitleForUrl(projectKey, status.url, status.title, environmentHostname); } diff --git a/apps/web/src/clientPersistenceStorage.ts b/apps/web/src/clientPersistenceStorage.ts index e1c1459fac..5e3c97649f 100644 --- a/apps/web/src/clientPersistenceStorage.ts +++ b/apps/web/src/clientPersistenceStorage.ts @@ -23,3 +23,18 @@ export function writeBrowserClientSettings(settings: ClientSettings): void { setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema); } + +/** Storage events fire only for other tabs' writes; a null key means storage was cleared. */ +export function subscribeBrowserClientSettingsWrites(onChange: () => void): () => void { + if (!hasWindow()) { + return () => undefined; + } + const handleStorage = (event: StorageEvent) => { + if (event.key === CLIENT_SETTINGS_STORAGE_KEY || event.key === null) { + onChange(); + } + }; + const target = window; + target.addEventListener("storage", handleStorage); + return () => target.removeEventListener("storage", handleStorage); +} diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 3d9c064cfc..a6f2a2fa54 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -26,15 +26,18 @@ import { useAddProjectTargets } from "../hooks/useAddProjectTargets"; import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments"; import { + COPIED_FILES_MAX_COUNT, COPYABLE_FILE_MAX_BYTES, addProjectToMachine, isDefaultCopiedFile, } from "../lib/addProjectToMachine"; import { formatBytes } from "../lib/formatBytes"; +import { seedDraftModelSelection } from "../lib/seedDraftModelSelection"; import { newProjectId } from "../lib/utils"; import { readProject, subscribeProject, useProject } from "../state/entities"; import { useEnvironments } from "../state/environments"; import { projectEnvironment } from "../state/projects"; +import { useDebouncedValue } from "../state/queries"; import { useEnvironmentQuery } from "../state/query"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { Button } from "./ui/button"; @@ -121,8 +124,10 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const [pathOverride, setPathOverride] = useState(null); const destinationPath = pathOverride ?? defaultPath; - const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true; - const ignoredFiles = useEnvironmentQuery( + const capabilities = source?.serverConfig?.environment.capabilities; + const canListFiles = capabilities?.ignoredFileListing === true; + const canSearchFiles = canListFiles && capabilities?.ignoredFileSearch === true; + const allIgnoredFiles = useEnvironmentQuery( project && canListFiles ? projectEnvironment.listIgnoredFiles({ environmentId: project.environmentId, @@ -130,13 +135,29 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe }) : null, ); + const [fileQuery, setFileQuery] = useState(""); + const sentFileQuery = useDebouncedValue(fileQuery.trim(), 120); + const searching = canSearchFiles && sentFileQuery.length > 0; + const searchedFiles = useEnvironmentQuery( + project && searching + ? projectEnvironment.listIgnoredFiles({ + environmentId: project.environmentId, + input: { cwd: project.workspaceRoot, query: sentFileQuery }, + }) + : null, + ); + const ignoredFiles = searching ? searchedFiles : allIgnoredFiles; const files = ignoredFiles.data?.files ?? []; - const [selected, setSelected] = useState | null>(null); - const selectedFiles = selected ?? defaultSelection(files); + // Keyed by path with the file kept, so picks made under one search survive the next. + const [selected, setSelected] = useState | null>(null); + const selectedFiles = selected ?? defaultSelection(allIgnoredFiles.data?.files ?? []); const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES); - const selectedBytes = files - .filter((file) => selectedFiles.has(file.path)) - .reduce((total, file) => total + file.byteLength, 0); + const allCopyableSelected = copyable.every((file) => selectedFiles.has(file.path)); + const atSelectionLimit = selectedFiles.size >= COPIED_FILES_MAX_COUNT; + const selectedBytes = [...selectedFiles.values()].reduce( + (total, file) => total + file.byteLength, + 0, + ); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); @@ -146,11 +167,19 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const unavailable = project === null || target === null || - (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null); - const toggleFile = (path: string, checked: boolean) => { - const next = new Set(selectedFiles); - if (checked) next.add(path); - else next.delete(path); + (canListFiles && allIgnoredFiles.data === null && allIgnoredFiles.error === null); + const toggleFile = (file: ProjectIgnoredFile, checked: boolean) => { + const next = new Map(selectedFiles); + if (!checked) next.delete(file.path); + else if (!atSelectionLimit) next.set(file.path, file); + setSelected(next); + }; + const toggleShownFiles = () => { + const next = new Map(selectedFiles); + for (const file of copyable) { + if (allCopyableSelected) next.delete(file.path); + else if (next.size < COPIED_FILES_MAX_COUNT) next.set(file.path, file); + } setSelected(next); }; @@ -173,6 +202,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe environmentSelection: "manual", loadBalancedEnvironmentId: null, }); + seedDraftModelSelection(draftId, targetRef); return; } void handleNewThread(targetRef); @@ -198,7 +228,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe title: project.title, remoteUrl, destinationPath: destinationPath.trim(), - files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path), + files: [...selectedFiles.keys()], }); close(); openClonedProject(scopeProjectRef(target.environmentId, projectId)); @@ -334,33 +364,41 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe {copyable.length > 0 ? ( <> - {selectedFiles.size} of {files.length} + {selectedFiles.size} of {allIgnoredFiles.data?.files.length ?? 0} {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""} - ) : null} + {canSearchFiles && (allIgnoredFiles.data?.truncated || fileQuery.length > 0) ? ( + setFileQuery(event.target.value)} + // Enter would otherwise submit the clone. + onKeyDown={(event) => { + if (event.key === "Enter") event.preventDefault(); + }} + spellCheck={false} + autoComplete="off" + /> + ) : null} {ignoredFiles.error ? (

    {ignoredFiles.error}

    ) : files.length === 0 ? (

    - {ignoredFiles.isSuccess - ? "No ignored files to copy." - : "Finding ignored files…"} + {!ignoredFiles.isSuccess + ? "Finding ignored files…" + : searching + ? "No ignored files match." + : "No ignored files to copy."}

    ) : (
    @@ -369,7 +407,8 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe key={file.path} file={file} checked={selectedFiles.has(file.path)} - onCheckedChange={(checked) => toggleFile(file.path, checked)} + disabled={atSelectionLimit && !selectedFiles.has(file.path)} + onCheckedChange={(checked) => toggleFile(file, checked)} /> ))}
    @@ -377,6 +416,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe {ignoredFiles.data?.truncated ? (

    Showing the first {files.length} files. + {canSearchFiles ? " Search to find the rest." : ""}

    ) : null}

    @@ -415,29 +455,37 @@ function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: : ""; } -function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet { - return new Set( +function defaultSelection( + files: readonly ProjectIgnoredFile[], +): ReadonlyMap { + return new Map( files .filter( (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path), ) - .map((file) => file.path), + .map((file) => [file.path, file]), ); } function IgnoredFileRow({ file, checked, + disabled, onCheckedChange, }: { file: ProjectIgnoredFile; checked: boolean; + disabled: boolean; onCheckedChange: (checked: boolean) => void; }) { const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES; return (

    +