diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 31fd088d324..189428c47fe 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -56,17 +56,15 @@ CI enforces this for `src/preload/` and `src/shared/` — see `docs/preload-type ## Pull Requests -Each pull request should: +Each pull request should follow [`.github/pull_request_template.md`](./pull_request_template.md). In particular: -- explain the user-visible change -- stay focused on a single topic when possible -- include screenshots or screen recordings for new UI or behavior changes +- open with an ELI5 of the change (plain language paragraph; the PR title is the one-liner) +- explain what changed and why, and stay focused on a single topic when possible +- for any UI or interaction change, attach **before and after** screenshots (or short videos); if there is no visual change, say `No visual change` and why - include high-quality tests when behavior changes or bug fixes warrant them - include a brief code review summary from your AI coding agent that explicitly checks cross-platform compatibility, SSH/remote/local compatibility, supported agent and integration compatibility, performance risk, UI quality when applicable, and basic security risk - mention any platform-specific, remote/SSH-specific, agent-specific, integration-specific, or git-provider-specific behavior and testing notes -- **Include your X (Twitter) handle!** We love giving shoutouts to our contributors when we merge features on [@orca_build](https://x.com/orca_build). - -If there is no visual change, say that explicitly in the PR description. +- **Include your X (Twitter) handle** in the PR template Author section — we shout out contributors when we merge features on [@orca_build](https://x.com/orca_build). ## Release Process diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index b69e2dcc233..21f7fa08eb8 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,29 +1,52 @@ -## Summary +## ELI5 -Describe the user-visible change. + -## Screenshots +## What Changed -- Add screenshots or a screen recording for any new or changed UI behavior. -- If there is no visual change, say `No visual change`. + + +## Why + + + +## Linked Issue + + + +Fixes # + +## Visual Proof + + + ## Testing -- [ ] `pnpm lint` -- [ ] `pnpm typecheck` -- [ ] `pnpm test` -- [ ] `pnpm build` -- [ ] Added or updated high-quality tests that would catch regressions, or explained why tests were not needed + -## AI Review Report +- [ ] I manually tested these changes locally +- [ ] Automated tests added/updated, or explained why not below -Summarize the code review you ran with your AI coding agent. Include the main risks it checked, what it flagged, and what you changed or verified as a result. -Confirm that the review explicitly checked cross-platform compatibility for macOS, Linux, and Windows, including shortcuts, labels, paths, shell behavior, and any Electron-specific platform differences touched by this PR. -## Security Audit +## AI Disclosure + + -Provide a basic security audit summary from your AI coding agent. Call out any input handling, command execution, path handling, auth, secrets, dependency, or IPC risks that were reviewed, plus any follow-up needed. +## Review -## Notes +Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance -Call out any platform-specific behavior, risks, or follow-up work. +## Checklist + +- [ ] This PR is small and focused +- [ ] I explained what changed and why (including ELI5) +- [ ] Before/after screenshots or videos attached for UI changes, or `N/A` with reason +- [ ] Self-reviewed for correctness, security, and performance +- [ ] Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A) +- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test`, and `pnpm build` pass (or CI will cover; local preferred) + +## Author + +- X / Twitter: @your_handle + diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 5455d0b7fb8..9838baf4afd 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -126,7 +126,7 @@ jobs: # scripts still need the Linux toolchain even though this shard reuses # the prebuilt Electron output. - name: Install native build tools - run: sudo apt-get update && sudo apt-get install -y build-essential python3 + run: sudo apt-get update && sudo apt-get install -y build-essential python3 zsh # Why: Electron on Linux needs an X display even when the app # suppresses mainWindow.show() via ORCA_E2E_HEADLESS. xvfb provides a @@ -174,7 +174,7 @@ jobs: # ORCA_E2E_FORWARD_APP_LOGS keeps startup failures visible when Electron # launches but never creates a BrowserWindow. - name: Run E2E tests (${{ matrix.shard_name }}) - run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e --shard=${{ matrix.shard }} + run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 ORCA_E2E_WEB_CLIENT=1 pnpm run test:e2e --shard=${{ matrix.shard }} # Why: Playwright retains traces/screenshots only on failure. Uploading # them as an artifact makes post-mortem debugging on CI possible without @@ -202,7 +202,7 @@ jobs: ref: ${{ inputs.ref || github.ref }} - name: Install native build and headless UI tools - run: sudo apt-get update && sudo apt-get install -y build-essential python3 xvfb + run: sudo apt-get update && sudo apt-get install -y build-essential python3 xvfb zsh - name: Setup Node.js uses: actions/setup-node@v6 @@ -232,8 +232,15 @@ jobs: env: TEST_FILES_JSON: ${{ inputs.test_files }} run: | - mapfile -t TEST_FILES < <(jq -r '.[]' <<<"$TEST_FILES_JSON") - xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 \ + mapfile -t TEST_FILES < <(jq -r '.[] | select( + . != "tests/e2e/ssh-startup-exec-readiness.spec.ts" and + . != "tests/e2e/paired-startup-exec-readiness.spec.ts" + )' <<<"$TEST_FILES_JSON") + if [ "${#TEST_FILES[@]}" -eq 0 ]; then + echo "Changed startup-readiness specs are owned by the dedicated live lane." + exit 0 + fi + xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 ORCA_E2E_WEB_CLIENT=1 \ pnpm run test:e2e "${TEST_FILES[@]}" --workers=1 - name: Upload Playwright traces @@ -248,10 +255,13 @@ jobs: ssh-docker-watcher-isolation: name: ssh docker watcher isolation needs: build - if: inputs.test_files == '' + if: >- + inputs.test_files == '' || + contains(inputs.test_files, 'tests/e2e/ssh-startup-exec-readiness.spec.ts') || + contains(inputs.test_files, 'tests/e2e/paired-startup-exec-readiness.spec.ts') runs-on: ubuntu-latest - # Why 35: the terminal parking + retention specs below add two more - # docker-rig tests capped at 240s each on top of the watcher isolation pair. + # Why 35: the parking, retention, startup-exec, and paired parity specs run + # serially on isolated Electron/SSH fixtures after watcher isolation. timeout-minutes: 35 steps: @@ -261,7 +271,7 @@ jobs: ref: ${{ inputs.ref || github.ref }} - name: Install native build and headless UI tools - run: sudo apt-get update && sudo apt-get install -y build-essential openssh-client python3 xvfb + run: sudo apt-get update && sudo apt-get install -y build-essential openssh-client python3 xvfb zsh - name: Setup Node.js uses: actions/setup-node@v6 @@ -295,10 +305,9 @@ jobs: - name: Run Docker SSH watcher isolation E2E run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:ssh-docker-watcher-isolation - # Why always(): these specs gate the C1 terminal parking/retention budget - # over a real SSH host and run in no other lane, so a watcher-isolation - # failure above must not silently skip them. - - name: Run Docker SSH terminal parking + retention E2E + # Why always(): this lane gates SSH parking/retention plus startup-exec + # readiness across live SSH, headed paired, and headless serve topologies. + - name: Run Docker SSH terminal parking + startup readiness E2E if: always() run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:ssh-docker-terminal-parking diff --git a/.github/workflows/golden-e2e-experiment.yml b/.github/workflows/golden-e2e-experiment.yml index 89c1c86096f..5a2562bf2ba 100644 --- a/.github/workflows/golden-e2e-experiment.yml +++ b/.github/workflows/golden-e2e-experiment.yml @@ -23,10 +23,9 @@ jobs: platform: linux - os: macos-15 platform: mac - # Why: Windows golden E2E is temporarily disabled on CI while its - # flaky runner-only failures are investigated. - # - os: windows-latest - # platform: windows + # Match the release gate: Windows runs the fresh-startup golden only. + - os: windows-2022 + platform: windows steps: - name: Checkout @@ -67,12 +66,22 @@ jobs: run: | xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e -- tests/e2e/golden-core-flows.spec.ts xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden + xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:posix-profile-index-golden - name: Run golden E2E tests on macOS if: runner.os == 'macOS' run: | env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e -- tests/e2e/golden-core-flows.spec.ts env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden + env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:posix-profile-index-golden + + - name: Run golden E2E tests on Windows + if: runner.os == 'Windows' + shell: pwsh + run: | + $env:SKIP_BUILD = '1' + $env:ORCA_E2E_FORWARD_APP_LOGS = '1' + pnpm run test:e2e:windows-fresh-startup-golden - name: Upload Playwright traces if: failure() diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index d10463173dd..0c1789bf3ea 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -176,6 +176,12 @@ jobs: shell_contracts: name: shell contracts runs-on: ubuntu-latest + env: + # Why: the suites below gate their live fish tests on the binary, which is + # right on a developer machine and wrong here — this job is a required check + # and its fish lane is the only end-to-end guard for #9993, so a skip would + # report green with nothing exercised. Turns those skips into failures. + ORCA_REQUIRE_FISH: '1' steps: - name: Checkout @@ -186,8 +192,46 @@ jobs: # Why fish: shell-ready.test.ts gates its live fish test on the binary being # present, so without this the fish barrier is only covered by config-shape # assertions and never actually exercised. + # Why release-4: DECSET 2031 arming lives in the fish 4.0 Rust tty_handoff, and + # fish-color-scheme-child-stdin.node-pty.test.ts (#9993) needs it. Noble ships + # 3.7, so the PPA is what makes that lane real. - name: Install zsh and fish - run: sudo apt-get update && sudo apt-get install -y zsh fish + run: | + # Why the update/PPA/fish steps are tolerant: a repo the runner image already + # ships can lack a Release file for this suite, and a failed add-apt-repository + # still leaves its list entry behind — either makes `apt-get update` exit + # non-zero and would red this required check over something unrelated to the + # PR. Every fish outcome is judged by the version gate below instead, so only + # the zsh install (which has no such gate) stays fatal here. + sudo apt-get update || true + # Why retry only here: adding the PPA is the network-flaky step, and the + # version gate below is fatal, so a transient Launchpad blip would + # otherwise red a required check on PRs unrelated to shells. + for attempt in 1 2 3; do + sudo add-apt-repository -y ppa:fish-shell/release-4 && break + echo "add-apt-repository attempt ${attempt} failed; retrying" >&2 + sudo add-apt-repository -y -r ppa:fish-shell/release-4 || true + sleep 5 + done + sudo apt-get update || true + # Why both shells on one line: pr-workflow-parallelism.test.mjs parses only the + # first install command in this step to prove the lane really installs them. + sudo apt-get install -y zsh fish + + # Separate from the install so the failure names the contract, not an apt error. + # ORCA_REQUIRE_FISH re-checks this at test time; this step just fails in seconds + # instead of after a full dependency install. + - name: Require fish 4+ + run: | + version="$(fish --version 2>/dev/null || true)" + major="${version##*version }" + major="${major%%.*}" + case "$major" in '' | *[!0-9]*) major=0 ;; esac + echo "${version:-}" + if [ "$major" -lt 4 ]; then + echo "::error::shell contracts needs fish 4+ (DECSET 2031 arming, #9993) but got '${version:-none}'. Fix the ppa:fish-shell/release-4 install rather than letting the fish lane skip." >&2 + exit 1 + fi - uses: ./.github/actions/install-node-dependencies with: @@ -195,12 +239,14 @@ jobs: - name: Test real shell contracts run: | - pnpm exec vitest run --config config/vitest.config.ts \ + pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 \ + src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts \ src/main/daemon/shell-ready.test.ts \ src/main/daemon/node-pty-fd-leak.test.ts \ src/main/providers/local-pty-shell-ready.test.ts \ src/main/providers/__tests__/shell-ready-framework-example.test.ts \ src/main/pty/omp-shell-wrapper.node-pty.test.ts \ + src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts \ src/shared/posix-command-path-lookup.test.ts test: @@ -230,11 +276,13 @@ jobs: - name: Test shard run: | pnpm exec vitest run --config config/vitest.config.ts \ + --exclude=src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts \ --exclude=src/main/daemon/shell-ready.test.ts \ --exclude=src/main/daemon/node-pty-fd-leak.test.ts \ --exclude=src/main/providers/local-pty-shell-ready.test.ts \ --exclude=src/main/providers/__tests__/shell-ready-framework-example.test.ts \ --exclude=src/main/pty/omp-shell-wrapper.node-pty.test.ts \ + --exclude=src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts \ --exclude=src/shared/posix-command-path-lookup.test.ts \ --exclude=tests/e2e/cross-version-wire/** \ --shard=${{ matrix.shard }}/${{ matrix.shard_total }} @@ -378,8 +426,12 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Test Windows PowerShell CLI boundary - run: pnpm exec vitest run --config config/vitest.config.ts src/main/cli/wsl-cli-powershell-boundary.test.ts + - name: Test Windows-specific boundaries + run: >- + pnpm exec vitest run --config config/vitest.config.ts + src/main/cli/wsl-cli-powershell-boundary.test.ts + src/main/orca-profiles/profile-index-store.test.ts + src/shared/secure-file-fsync-flags.test.ts - name: Build package inputs run: pnpm run build:release diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index 6dba5ac1ff6..370fbcc0a32 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -783,7 +783,7 @@ jobs: { echo "## Release E2E Signal" echo "" - echo "- Terminal rendering golden is release-blocking." + echo "- Platform golden E2E is release-blocking: terminal rendering and restrictive-umask profile writes on Linux/macOS, plus fresh startup on Windows." echo "- Full E2E runs separately after publication and cannot change the release result." echo "- Terminal rendering release evidence is diagnostic/non-blocking." echo "" @@ -817,7 +817,7 @@ jobs: terminal-rendering-golden: needs: cut if: needs.cut.outputs.should_release == 'true' - name: terminal rendering golden ${{ matrix.platform }} + name: golden e2e ${{ matrix.platform }} runs-on: ${{ matrix.os }} timeout-minutes: 30 env: @@ -830,10 +830,10 @@ jobs: platform: linux - os: macos-15 platform: mac - # Why: Windows terminal rendering golden is temporarily disabled on - # CI while its flaky runner-only failures are investigated. - # - os: windows-latest - # platform: windows + # Windows terminal rendering remains flaky; keep its blocking signal + # scoped to the fresh-profile startup regression from #14130. + - os: windows-2022 + platform: windows steps: - name: Checkout @@ -866,22 +866,34 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Build Electron app for terminal rendering golden + - name: Build Electron app for platform golden run: npx electron-vite build --mode e2e - name: Run terminal rendering golden on Linux if: runner.os == 'Linux' - run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden + run: | + xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden + xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:posix-profile-index-golden - name: Run terminal rendering golden on macOS if: runner.os == 'macOS' - run: env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden + run: | + env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden + env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:posix-profile-index-golden + + - name: Run fresh-startup golden on Windows + if: runner.os == 'Windows' + shell: pwsh + run: | + $env:SKIP_BUILD = '1' + $env:ORCA_E2E_FORWARD_APP_LOGS = '1' + pnpm run test:e2e:windows-fresh-startup-golden - name: Upload Playwright traces if: failure() uses: actions/upload-artifact@v7 with: - name: terminal-rendering-golden-${{ matrix.platform }}-playwright-traces + name: golden-e2e-${{ matrix.platform }}-playwright-traces path: test-results/ retention-days: 7 if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 17bb18529af..f5ffbfd5f3c 100644 --- a/.gitignore +++ b/.gitignore @@ -102,7 +102,12 @@ docs/** !docs/reference/linux-glibc-compatibility.md !docs/reference/relay-grace-time-reconfiguration.md !docs/reference/remote-wire-compatibility.md +!docs/reference/terminal-session-behavior-contract.md +!docs/reference/terminal-session-correctness-handoff-2026-08-07/ +!docs/reference/terminal-session-correctness-handoff-2026-08-07/** +!docs/reference/renderer-agent-status-performance.md !docs/reference/windows-setup-shell.md +!docs/reference/worktree-scan-fingerprint.md # Stably CLI (only docs/ are tracked) .stably/* @@ -125,6 +130,10 @@ playwright-report/ /.agents/skills/ /skills-lock.json +# Generated Clawpatch state includes machine-local paths and review records. +/.clawpatch/ +/mobile/.clawpatch/ + # Agent hook runtime endpoints (machine-local secrets) /agent-hooks/ validation-screenshots/ diff --git a/.oxlintrc.json b/.oxlintrc.json index 0f679f17d52..97a2b68701a 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -56,6 +56,7 @@ "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn", "typescript/array-type": "error", + "typescript/consistent-generic-constructors": "error", "typescript/consistent-indexed-object-style": "error", "typescript/consistent-type-assertions": "error", "typescript/consistent-type-definitions": ["error", "type"], @@ -68,12 +69,16 @@ "typescript/prefer-function-type": "error", "typescript/prefer-includes": "error", "typescript/prefer-optional-chain": "error", + "typescript/prefer-ts-expect-error": "error", "typescript/switch-exhaustiveness-check": [ "error", { "allowDefaultCaseForExhaustiveSwitch": false } ], "curly": "error", "no-unneeded-ternary": "error", + "no-else-return": "error", + "prefer-exponentiation-operator": "error", + "prefer-object-has-own": "error", "no-restricted-imports": [ "error", { @@ -90,11 +95,16 @@ "no-useless-return": "error", "prefer-template": "error", "unicorn/consistent-empty-array-spread": "error", + "unicorn/consistent-existence-index-check": "error", + "unicorn/empty-brace-spaces": "error", "unicorn/error-message": "error", "unicorn/no-array-fill-with-reference-type": "warn", "unicorn/no-array-reverse": "error", "unicorn/no-instanceof-builtins": "error", + "unicorn/no-typeof-undefined": "error", + "unicorn/no-unnecessary-array-splice-count": "error", "unicorn/no-useless-promise-resolve-reject": "error", + "unicorn/no-zero-fractions": "error", "unicorn/prefer-array-find": "error", "unicorn/prefer-array-flat-map": "warn", "unicorn/prefer-array-index-of": "error", diff --git a/config/electron-vite-target.config.ts b/config/electron-vite-target.config.ts index 60651dd6590..490fa654f5b 100644 --- a/config/electron-vite-target.config.ts +++ b/config/electron-vite-target.config.ts @@ -8,7 +8,7 @@ const configByTarget = { renderer: { renderer: electronViteConfig.renderer } } -if (!target || !Object.prototype.hasOwnProperty.call(configByTarget, target)) { +if (!target || !Object.hasOwn(configByTarget, target)) { throw new Error(`Invalid ORCA_ELECTRON_VITE_TARGET: ${target ?? ''}`) } diff --git a/config/max-lines-baseline.txt b/config/max-lines-baseline.txt index 59368273624..a9c03d1b9d6 100644 --- a/config/max-lines-baseline.txt +++ b/config/max-lines-baseline.txt @@ -10,7 +10,6 @@ inline src/main/agent-hooks/server.test.ts inline src/main/agent-hooks/server.ts inline src/main/amp/hook-service.ts inline src/main/antigravity/hook-service.ts -inline src/main/attribution/terminal-attribution.ts inline src/main/automations/external-manager.ts inline src/main/automations/hermes-cron-output.ts inline src/main/browser/agent-browser-bridge.test.ts diff --git a/config/oxlint-code-quality-native-plugins.json b/config/oxlint-code-quality-native-plugins.json index 5d9cd118e74..5f2fb031a51 100644 --- a/config/oxlint-code-quality-native-plugins.json +++ b/config/oxlint-code-quality-native-plugins.json @@ -16,6 +16,7 @@ "import/namespace": "warn", "import/no-cycle": ["warn", { "maxDepth": 3 }], "import/no-duplicates": "warn", + "import/no-empty-named-blocks": "warn", "import/no-self-import": "warn" }, "overrides": [ diff --git a/config/oxlint-code-quality-type-aware.json b/config/oxlint-code-quality-type-aware.json index 4c0e01fa748..8ae3cbab60e 100644 --- a/config/oxlint-code-quality-type-aware.json +++ b/config/oxlint-code-quality-type-aware.json @@ -12,6 +12,7 @@ }, "rules": { "typescript/await-thenable": "warn", + "typescript/no-redundant-type-constituents": "warn", "typescript/restrict-plus-operands": "warn", "typescript/restrict-template-expressions": "warn", "typescript/switch-exhaustiveness-check": [ diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index f5e5a39caeb..81f587046f0 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "updatedAt": "2026-08-10", + "updatedAt": "2026-08-12", "policy": { "maturityLevels": ["experimental", "soak", "blocking", "accepted-gap", "deprecated"], "blockingPromotion": { @@ -10,6 +10,176 @@ } }, "gates": [ + { + "id": "terminal-session.shell-ready-exec-prompt-fallback", + "title": "Startup exec falls back to the identified shell's line editor", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-session-readiness", + "layer": "posix-pty-and-shell-startup", + "surfaces": ["queued terminal startup commands", "zsh, bash, and Fish startup output"], + "platforms": ["macos", "linux"], + "providers": ["local", "local-daemon", "ssh-daemon", "ssh-relay", "paired-runtime"], + "coveredPlatforms": ["macos", "linux"], + "coveredProviders": ["local", "local-daemon", "ssh-relay", "paired-runtime"], + "coverageNotes": "Real macOS node-pty integration covers zsh 5.9 .zshenv/.zprofile and bash 3.2 profile replacement shells, including exec -a names, same-shell and child-process silent reads, a blocking zle-line-init hook, non-shell readline replacements, and a non-shell image renamed zsh. A real Fish PTY proves marker stripping is byte-exact and does not render bracketed-paste control text. An Ubuntu 20.04 container confirms compatible zsh/bash termios. Deterministic owner contracts cover local, daemon, and SSH relay identity/readiness composition plus provider-owned delivery; explicit terminal-paste remains renderer-owned. Live isolated journeys cover a macOS headed desktop owner with paired web client, headless orca serve with paired web client, and a Docker Linux OpenSSH/Bash target with one readiness-time reconnect. Linux desktop, WSL/Windows, live zsh-over-SSH, and physical remote hosts remain gaps.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/13767", + "https://linear.app/stably/issue/STA-4067", + "https://linear.app/stably/issue/STA-4068", + "https://github.com/stablyai/orca/pull/14161" + ], + "invariant": "Shell startup scanning preserves every non-Orca output byte in order across arbitrary PTY chunk boundaries. Before user startup files run, the wrapper publishes its shell PID. If a later exec discards the ready marker, proof-based recovery releases queued startup input only after the launched shell's actual executable image with that exact PID owns the PTY foreground, emits its post-hook line-editor enable sequence, and exposes zle/readline termios; startup reads, line-init hooks, child foreground processes, and non-shell readline replacements cannot trigger that proof. The existing bounded compatibility timeout may enqueue input without proof, but must not publish readiness, lose or duplicate that input across reconnect, or execute it before the replacement shell can accept it.", + "oracle": "Split Fish output immediately after the ready marker and after the following ESC introducer; local and daemon owners must emit the exact ESC [ ? 2004 h bytes and headless xterm must not render literal control text. Run the real generated wrappers under node-pty with disposable zsh, bash, and Fish startup files. Plain and exec -a replacement shells must receive one queued command at their first completed line editor without waiting for the 15-second timeout. The identical oracle must time out without the startup identity and prompt fallback. Same-shell reads, child-process reads, a blocking zle-line-init hook, sqlite3, and sqlite3 renamed zsh must not trigger prompt fallback. Relay owner coverage must use the same lossless scanner composition and release through the same prompt contract.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/line-editor-ready-output-scanner.test.ts src/main/shell-startup-identity-scanner.test.ts src/main/shell-startup-output-scanner.test.ts src/main/shell-prompt-readiness-probe.test.ts src/shared/pty-slave-line-discipline-echo.test.ts src/shared/shell-process-readiness.test.ts src/main/daemon/session.test.ts src/main/daemon/shell-ready.test.ts src/main/providers/local-pty-shell-ready.test.ts src/main/providers/local-pty-provider.test.ts src/relay/pty-shell-launch.test.ts src/relay/pty-handler.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-ready.test.ts src/main/shell-startup-output-scanner.test.ts", + "ORCA_E2E_SSH_DOCKER=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/ssh-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", + "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1" + ], + "testFiles": [ + "src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts", + "src/main/line-editor-ready-output-scanner.test.ts", + "src/main/shell-startup-identity-scanner.test.ts", + "src/main/shell-startup-output-scanner.test.ts", + "src/main/shell-prompt-readiness-probe.test.ts", + "src/shared/pty-slave-line-discipline-echo.test.ts", + "src/shared/shell-process-readiness.test.ts", + "src/main/daemon/session.test.ts", + "src/main/daemon/shell-ready.test.ts", + "src/main/providers/local-pty-shell-ready.test.ts", + "src/main/providers/local-pty-provider.test.ts", + "src/relay/pty-shell-launch.test.ts", + "src/relay/pty-handler.test.ts", + "tests/e2e/ssh-startup-exec-readiness.spec.ts", + "tests/e2e/paired-startup-exec-readiness.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/main/shell-startup-output-scanner.test.ts", + "assertions": [ + "Fish bracketed-paste output stays byte-exact across marker and ESC chunk splits", + "every byte after readiness is preserved across every chunk boundary, even when it resembles an identity marker", + "pre-ready identity and readiness markers strip across every chunk boundary without reordering prompt output", + "incomplete scanner prefixes drain in byte order" + ] + }, + { + "file": "src/main/daemon/session.test.ts", + "assertions": [ + "daemon output is byte-exact for both Fish chunk splits", + "headless xterm never renders literal bracketed-paste control text" + ] + }, + { + "file": "src/main/providers/local-pty-provider.test.ts", + "assertions": ["local PTY output is byte-exact for both Fish chunk splits"] + }, + { + "file": "src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts", + "assertions": [ + "real zsh .zshenv/.zprofile and bash profile replacement shells receive queued input exactly once", + "same-shell raw silent reads retain queued input", + "child-process raw silent reads retain queued input while the identified shell is not foreground", + "a blocking zle-line-init read retains queued input until the hook completes", + "sqlite3 and a sqlite3 image renamed zsh cannot impersonate the launched shell executable path", + "zsh configurations without a line-editor enable sequence retain the existing timeout backstop" + ] + }, + { + "file": "src/relay/pty-handler.test.ts", + "assertions": [ + "the SSH relay owner strips startup identity and releases provider-delivered input through prompt readiness", + "renderer-owned SSH delivery receives the existing ready marker after authoritative relay prompt readiness", + "normal renderer-owned ready markers pass through unchanged and retain no readiness state" + ] + }, + { + "file": "tests/e2e/ssh-startup-exec-readiness.spec.ts", + "assertions": [ + "a Docker Linux OpenSSH/Bash replacement shell retains one compatibility-fallback input across reconnect without executing it before the blocked replacement can accept it", + "the owning terminal handle and raw PTY identity remain singular and stable", + "painted output, authoritative terminal output, and the first interactive input each appear exactly once" + ] + }, + { + "file": "tests/e2e/paired-startup-exec-readiness.spec.ts", + "assertions": [ + "a headed desktop owner and paired client recover startup exec on one stable owning PTY", + "an isolated headless orca serve owner provides the same exact-once output and input contract" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "manual", + "platform": "linux", + "command": "pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-ready.test.ts src/main/shell-startup-output-scanner.test.ts", + "result": "passed", + "durationSeconds": 7, + "summary": "A clean Debian 12 arm64 container with real Fish 3.6 and node-pty passed exact marker-stripped output plus headless-xterm rendering." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/line-editor-ready-output-scanner.test.ts src/main/shell-startup-identity-scanner.test.ts src/main/shell-startup-output-scanner.test.ts src/main/shell-prompt-readiness-probe.test.ts src/shared/pty-slave-line-discipline-echo.test.ts src/shared/shell-process-readiness.test.ts src/main/daemon/session.test.ts src/main/daemon/shell-ready.test.ts src/main/providers/local-pty-shell-ready.test.ts src/main/providers/local-pty-provider.test.ts src/relay/pty-shell-launch.test.ts src/relay/pty-handler.test.ts", + "result": "passed", + "durationSeconds": 6, + "summary": "473 tests passed with one local Fish skip, including every-boundary scanner composition, real exec, silent-read, line-init-hook, renamed-image, disabled-bracketed-paste, and relay-owner oracles." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "linux", + "command": "ORCA_E2E_SSH_DOCKER=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/ssh-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", + "result": "passed", + "durationSeconds": 17, + "summary": "The live OpenSSH/Bash relay journey crossed the bounded compatibility fallback while rc-file exec was blocked, proved one queued command echo with no command execution, then passed a disconnect/reconnect with exact-once startup output/input and stable pane plus owner PTY identities." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1", + "result": "passed", + "durationSeconds": 14, + "summary": "The shared oracle passed a headed desktop owner plus paired web client and an isolated headless orca serve owner plus paired web client." + } + ], + "runtimeBudget": { + "p95Seconds": 120, + "scope": "focused local wrapper contracts plus isolated SSH and paired live journeys" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "Fresh deterministic and isolated live runs pass locally; CI and soak history have not started." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "Daemon oracle SHA-256 b13b08006a38b2adc2acb51ae9342909514e55ab4822fac4fbb76cd49b344cc6 was byte-identical across runs: affected baseline 09ec516ae5 failed 4 of 14, while pre-PR main bc2e30000b and this PR passed 14 of 14. The unchanged live SSH oracle failed on bc2e30000b and with the ownership change reverted because the ledger stayed pending after reconnect, then passed on this PR. Fish chunk oracle patch SHA-256 fd49a4d3d91bd5f0d10c1b1f44f4cfbd92cef9155a5505b415c8680184cdc765 was also byte-identical: scan target e4c278eb52, main 150cc6f50c, and candidate ae7f30318a with shared scanner integration disabled failed only the ESC-introducer split in local and daemon owners, while ae7f30318a passed all 163 cases plus headless-xterm rendering." + }, + "performanceBudget": { + "required": true, + "evidence": "Two bounded linear scans partition identity ownership at the exact ready-marker boundary and retain only the existing bounded prefixes. The normal ready-marker path cancels before external probing. A missing marker triggers a debounced stty read only after a line-editor enable sequence, followed by narrow PID status and executable-image inspection only when termios matches. Slow ordinary startup output triggers zero probes; rejected protocol emissions are capped at four probes per startup. There is no per-command hook or steady-state polling." + }, + "promotionCriteria": [ + "Collect CI and soak history for the Docker SSH and paired live journeys.", + "Collect CI and soak history without unexplained flakes.", + "Keep same-shell, child-process, line-init-hook, and non-shell readline contracts green." + ], + "knownGaps": [ + "The fallback requires a readable POSIX PTY slave; WSL through wsl.exe, ConPTY, and native Windows retain the existing timeout backstop.", + "The live SSH journey covers Docker Linux OpenSSH with Bash, not zsh, WSL, Windows SSH, a Linux desktop renderer, or a physical remote host.", + "An exec integration that forks a replacement shell instead of retaining the identified shell PID retains the existing timeout backstop.", + "A zsh configuration that disables bracketed-paste output emits no safe post-hook protocol signal and retains the existing timeout backstop.", + "The pre-existing timeout backstop can still deliver queued input to a non-shell replacement after it expires; this fallback prevents indefinite startup hangs and is unchanged by the prompt fallback.", + "The fallback restores safe startup-command delivery but cannot recreate OSC 133 hooks or overlay restores already discarded by exec.", + "Startup code running in the launched shell can deliberately spoof the public line-editor enable sequence after configuring matching termios; the existing timeout path already trusts a public OSC marker from the same startup code." + ], + "demotionRule": "Keep experimental or demote if prompt fallback enters a normal, child, or line-init read; a non-shell executable triggers prompt fallback; the identified shell PID is not foreground; delivery duplicates; ordinary startup output spawns probes; probe attempts exceed four; or the focused gate flakes without an identified harness defect." + }, { "id": "editor.restored-sibling-owner-reparent", "title": "Restored sibling tabs migrate filesystem authority before becoming editable", @@ -1361,6 +1531,442 @@ ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, + { + "id": "browser-session.remote-terminal-link-ownership", + "title": "Paired terminal links open one browser on their owning runtime", + "maturity": "experimental", + "protection": "partial", + "owner": "browser-runtime", + "layer": "renderer-paired-runtime-routing", + "surfaces": [ + "paired remote terminal HTTP links", + "terminal link action destinations", + "runtime-owned managed browser creation" + ], + "platforms": ["macos", "linux", "windows"], + "providers": ["remote-runtime", "ssh"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["remote-runtime", "ssh"], + "coverageNotes": "A headed macOS desktop host and separate paired Electron client exercise a real mirrored terminal link, owner-asserted host browser creation, exact host/client page identity, rendered DOM, explicit browser-tab activation, client external-browser suppression, exact host/client close convergence, and continued original-PTY liveness. Unit contracts cover OSC, WebLinksAddon, click fallback, explicit System Browser routing, failed creation, incapable runtimes, and unchanged direct SSH behavior.", + "motivatingLinks": [ + "https://stablygroup.slack.com/archives/C0AK2T3JEF4/p1786567689897109", + "https://github.com/stablyai/orca/issues/12418" + ], + "invariant": "Selecting Orca Browser for an HTTP link in a runtime-owned terminal creates exactly one browser page on that owning runtime and exactly one mirrored client browser workspace, with matching remote page identity and no client external-browser call. Explicit System Browser remains client-owned, direct SSH remains system-browser-only, and unknown or mismatched owners fail closed.", + "oracle": "Use the focused routing contracts as the byte-identical baseline/candidate oracle. Require runtime OSC, WebLinksAddon, click fallback, action-menu, and modifier paths to target the exact owner without client fallback, while direct SSH and generic remote document links stay external. Separately run one byte-identical headed paired Electron journey on the candidate and with only runtime browser registration disabled. Require one new host browser tab, one new client mirror with exact page identity, rendered fixture DOM, explicit browser-tab activation, zero client shell.openExternal calls, exact close convergence, unchanged terminal counts, and continued output on the original PTY.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-runtime-host-link-routing.test.ts src/renderer/src/components/terminal-pane/terminal-link-action-routing.test.ts src/renderer/src/components/terminal-pane/terminal-link-open-hints.test.ts src/renderer/src/lib/http-link-routing.test.ts src/renderer/src/lib/http-link-modifier-routing.test.ts src/renderer/src/lib/workspace-browser-tab-open.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-runtime-host-link-routing.test.ts src/renderer/src/components/terminal-pane/terminal-link-action-routing.test.ts src/renderer/src/lib/workspace-browser-tab-open.test.ts", + "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + ], + "testFiles": [ + "src/renderer/src/components/terminal-pane/terminal-runtime-host-link-routing.test.ts", + "src/renderer/src/components/terminal-pane/terminal-link-action-routing.test.ts", + "src/renderer/src/components/terminal-pane/terminal-link-open-hints.test.ts", + "src/renderer/src/lib/http-link-routing.test.ts", + "src/renderer/src/lib/http-link-modifier-routing.test.ts", + "src/renderer/src/lib/workspace-browser-tab-open.test.ts", + "tests/e2e/paired-remote-terminal-browser-link.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/components/terminal-pane/terminal-runtime-host-link-routing.test.ts", + "assertions": [ + "OSC, WebLinksAddon, and click-fallback activations route through the exact runtime owner", + "direct SSH continues to use only the system browser" + ] + }, + { + "file": "src/renderer/src/lib/workspace-browser-tab-open.test.ts", + "assertions": [ + "an asserted runtime cannot fall back to a client browser", + "mismatched and incapable runtime owners fail closed" + ] + }, + { + "file": "tests/e2e/paired-remote-terminal-browser-link.spec.ts", + "assertions": [ + "one terminal action produces one host page and one client mirror with exact identity", + "the host browser renders the fixture while client external navigation stays empty", + "an explicit browser-tab click reveals the exact mirror", + "closing the mirror returns host and client inventories to baseline", + "the original remote PTY accepts and renders fresh output after browser close" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-runtime-host-link-routing.test.ts src/renderer/src/components/terminal-pane/terminal-link-action-routing.test.ts src/renderer/src/lib/workspace-browser-tab-open.test.ts", + "result": "failed", + "durationSeconds": 2.58, + "summary": "Latest main e4c278eb523 failed 6/25 owner-routing assertions: runtime terminal links called the viewing client's external browser and the managed-browser helper did not enforce an asserted runtime owner." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-runtime-host-link-routing.test.ts src/renderer/src/components/terminal-pane/terminal-link-action-routing.test.ts src/renderer/src/components/terminal-pane/terminal-link-open-hints.test.ts src/renderer/src/lib/http-link-routing.test.ts src/renderer/src/lib/http-link-modifier-routing.test.ts src/renderer/src/lib/workspace-browser-tab-open.test.ts", + "result": "passed", + "durationSeconds": 1.83, + "summary": "Candidate passed 84/84 across six focused routing, modifier, availability, owner assertion, failure, SSH, and system-browser contract files." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 32.9, + "summary": "Candidate created one host browser and one client mirror with matching page identity, rendered the fixture, activated on an explicit tab click, made zero client external-browser calls, converged both inventories after exact UI close, and delivered fresh output on the original remote PTY." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "failed", + "durationSeconds": 60, + "summary": "The byte-identical final Electron oracle failed at its exact host/client identity barrier when the sole source delta replaced src/renderer/src/store/index.ts registration lines 110-113 with registerRuntimeHttpLinkBrowserOpener(null); no host-owned browser appeared within the deterministic 60-second bound." + } + ], + "runtimeBudget": { + "p95Seconds": 45, + "scope": "six focused renderer contract files plus one isolated headed paired-runtime journey" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "The focused contracts are deterministic and the headed paired-runtime journey passed locally after its PTY namespace oracle was corrected; longer CI and soak history is not yet available." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The focused owner-routing oracle is red on latest main e4c278eb523 and green on the candidate. The byte-identical headed Electron oracle is green on the candidate and red when the sole source delta replaces the runtime browser opener registration with registerRuntimeHttpLinkBrowserOpener(null); candidate evidence proves exact host/client identity, rendered content, explicit activation, exact close convergence, original-PTY survival, and absence of client external navigation." + }, + "performanceBudget": { + "required": true, + "evidence": "The production change adds no timer, polling, retry, subprocess, stream opcode, RPC method, or host publication. Each link hover or activation performs bounded in-memory owner and capability lookups; an Orca Browser action issues the same single browser creation and snapshot reconciliation already used by the tab bar." + }, + "promotionCriteria": [ + "Collect Linux and physical Windows paired-server evidence.", + "Collect a live headless-serve terminal-link journey.", + "Collect 100 consecutive focused CI passes or 14 days without an unexplained flake." + ], + "knownGaps": [ + "Live paired-server validation currently covers macOS only.", + "A live headless-serve journey and multiple simultaneous viewers are not exercised by the Electron journey.", + "Direct SSH intentionally retains its existing system-browser-only semantics.", + "Terminal-link activation does not change the existing asynchronous host/client focus policy." + ], + "demotionRule": "Demote if one runtime terminal link creates a client-owned or duplicate browser, targets a runtime other than the pane owner, invokes the client external browser for Orca Browser, or removes the source terminal." + }, + { + "id": "browser-session.remote-html-preview-ownership", + "title": "Paired HTML previews keep one host page and one stable client split", + "maturity": "experimental", + "protection": "partial", + "owner": "browser-runtime", + "layer": "renderer-paired-runtime-reconciliation", + "surfaces": [ + "paired remote HTML file preview", + "background preview creation and explicit browser activation", + "client-only split placement", + "capability-unknown and mixed-version preview rejection cleanup", + "post-create reconciliation failure and compensating rollback", + "remote browser close convergence" + ], + "platforms": ["macos", "linux", "windows"], + "providers": ["remote-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["remote-runtime"], + "coverageNotes": "A headed macOS desktop host and separate paired client exercise the Explorer eye-button path with a real remote file URL, host browser DOM, renderer split layout, background preview creation, explicit browser activation, browser close, forced capability rejection after caller preflight, and a forced post-create reconciliation timeout. The same fault oracles pass against a live headless server. Unit contracts cover absent, unknown, and mixed-version capabilities, visible rejection, empty-split cleanup, owning-runtime routing, exact client materialization, confirmed rollback, ambiguous cleanup, and teardown. Linux and Windows live journeys remain gaps.", + "motivatingLinks": [ + "https://linear.app/stably/issue/STA-3872/unable-to-open-html-files-in-remote-server", + "https://linear.app/stably/issue/STA-4025/p1-browser-create-reports-success-when-tab-reconcile-fails-after-pr", + "https://linear.app/stably/issue/STA-4063/p1-paired-html-preview-rejects-outside-cleanup-after-pr-13909", + "https://github.com/stablyai/orca/pull/13876" + ], + "invariant": "Opening one HTML preview from a paired client succeeds only after exactly one browser page on the worktree-owning runtime materializes as exactly one client browser workspace and unified tab in the requested group. Capability rejection before host mutation must preserve the original error, issue no RPC, surface a failure toast, and remove only a caller-declared newly-created empty split. Post-create reconciliation failure requires exact rollback; ambiguous rollback rejects without local fallback. Preview focus and close preserve the source editor and terminal.", + "oracle": "Run one unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host. Require the original unsupported error or visible toast, zero RPCs, and no retained new split. Run it on the scan target, latest main, candidate, and candidate with the cleanup boundary disabled. In headed paired Electron, arm capability rejection after the caller preflight, invoke the visible HTML side-preview action, require the failure toast, and compare exact host/client browser, editor, terminal, and group inventories to baseline. Repeat against headless serve. Retain the separate exact-page reconciliation rollback oracle.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-browser.test.ts src/main/runtime/rpc/methods/browser.test.ts src/renderer/src/lib/file-preview.test.ts src/renderer/src/runtime/web-session-browser-placement.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/runtime/remote-server-parity.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-runtime-browser-materialization.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-runtime-browser-capability-cleanup.test.ts src/renderer/src/lib/file-preview-capability-cleanup.test.ts", + "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3", + "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" + ], + "testFiles": [ + "src/main/runtime/orca-runtime-browser.test.ts", + "src/main/runtime/rpc/methods/browser.test.ts", + "src/renderer/src/lib/file-preview.test.ts", + "src/renderer/src/lib/file-preview-capability-cleanup.test.ts", + "src/renderer/src/runtime/web-session-browser-placement.test.ts", + "src/renderer/src/runtime/web-runtime-browser-materialization.test.ts", + "src/renderer/src/runtime/web-runtime-browser-capability-cleanup.test.ts", + "src/renderer/src/runtime/web-runtime-session.test.ts", + "src/renderer/src/runtime/web-session-tabs-sync.test.ts", + "src/renderer/src/runtime/remote-server-parity.test.ts", + "tests/e2e/paired-remote-html-browser-focus.spec.ts", + "tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/runtime/web-runtime-browser-capability-cleanup.test.ts", + "assertions": [ + "absent status, unknown capabilities, and mixed-version hosts preserve the unsupported rejection", + "direct creation removes the caller-declared new split without issuing an RPC" + ] + }, + { + "file": "src/renderer/src/lib/file-preview-capability-cleanup.test.ts", + "assertions": [ + "known unavailability reports visibly without creating a split", + "capability loss after caller preflight reports visibly without duplicating transaction cleanup" + ] + }, + { + "file": "src/renderer/src/lib/file-preview.test.ts", + "assertions": [ + "a failed side preview reports visibly without caller-owned split cleanup", + "overlapping side previews reuse the split without the first failure deleting it" + ] + }, + { + "file": "src/renderer/src/runtime/web-runtime-browser-materialization.test.ts", + "assertions": [ + "success requires the exact environment and remote page handle plus a unified browser tab", + "a requested client group must contain the materialized browser tab" + ] + }, + { + "file": "src/renderer/src/runtime/web-runtime-session.test.ts", + "assertions": [ + "a post-create timeout returns false only after exact host close and a confirming snapshot", + "unconfirmed cleanup rejects so callers cannot create a competing local fallback", + "the canonical placement and a newly-created empty split are released on rollback", + "one failed preview cannot remove a shared split still reserved after an environment ownership change", + "if every overlapping creation fails, the last reservation closes the caller-created empty split" + ] + }, + { + "file": "src/renderer/src/runtime/web-session-browser-placement.test.ts", + "assertions": [ + "pending page placements are bounded and reserve worktree groups across environment ownership changes", + "caller-created cleanup transfers to the last failed overlapping reservation", + "capacity rejects a new placement without evicting an active reservation or its cleanup ownership", + "worktree and environment teardown clear only their own placement state" + ] + }, + { + "file": "src/renderer/src/runtime/web-session-tabs-sync.test.ts", + "assertions": [ + "a host browser page stays in its exact client-owned preview group", + "a reserved empty split survives a pre-publication host snapshot", + "later client moves supersede initial preview placement" + ] + }, + { + "file": "src/renderer/src/runtime/remote-server-parity.test.ts", + "assertions": [ + "a caller-created browser gains focus when the exact predecessor tab is still visible" + ] + }, + { + "file": "tests/e2e/paired-remote-html-browser-focus.spec.ts", + "assertions": [ + "one HTML open produces one client workspace, one client unified tab, and one host page", + "the source editor and remote frame remain visible in separate groups", + "preview creation leaves the editor active, an explicit browser click is authoritative, and close preserves the editor and terminal" + ] + }, + { + "file": "tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts", + "assertions": [ + "the exact created page exists on the host while publication is held and no browser tab materializes on the client", + "a forced post-create reconciliation timeout closes the exact host page and removes only the reserved empty split", + "a forced capability rejection after caller preflight shows a toast and restores exact host and client inventories", + "headed and headless hosts preserve the unrelated editor and terminal without local fallback" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-runtime-browser-capability-cleanup.test.ts src/renderer/src/lib/file-preview-capability-cleanup.test.ts", + "result": "failed", + "durationSeconds": 0.72, + "summary": "The unchanged STA-4063 oracle failed 5/5 on scan e4c278eb52 and latest main bc2e30000b: direct create never closed the new split, and side-preview rejection produced neither cleanup nor a toast. Pre-fix PR #14100 passed the two caller cases but still failed all three direct transaction cases." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-runtime-browser-capability-cleanup.test.ts src/renderer/src/lib/file-preview-capability-cleanup.test.ts", + "result": "passed", + "durationSeconds": 0.7, + "summary": "Rebased candidate 14b5877a75 passed 5/5: absent, unknown, mixed-version, preflight-known, and post-preflight capability failures all reported failure and retained no new empty split." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 18.3, + "summary": "The full headed spec passed 2/2. A visible desktop host and separate paired Electron client proved both reconciliation rollback and capability rejection with a failure toast and exact host/client browser, group, editor, and terminal inventory restoration." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 9.1, + "summary": "The full isolated headless-serve journey passed 1/1, applying both reconciliation and capability faults to the same live host while preserving the visible-toast and exact inventory-restoration oracle." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-runtime-browser-materialization.test.ts", + "result": "passed", + "durationSeconds": 0.11, + "summary": "The exact environment, remote page, client workspace, unified browser tab, and requested group materialization contract passed 1/1 on the final rebased candidate." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 24.3, + "summary": "A visible desktop host and separate paired Electron client held one exact host page before client materialization, forced the post-create timeout, then proved exact host rollback, empty-split removal, failure UI, no local fallback, and surviving editor and terminal." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 18.5, + "summary": "The same exact-page hold, timeout, rollback, client cleanup, no-fallback, editor, and terminal oracle passed against isolated headless serve." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-browser.test.ts src/main/runtime/rpc/methods/browser.test.ts src/renderer/src/lib/file-preview.test.ts src/renderer/src/runtime/web-session-browser-placement.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/runtime/remote-server-parity.test.ts", + "result": "passed", + "durationSeconds": 3.48, + "summary": "Seven focused host and renderer contract files passed 183/183 tests, covering owning-runtime routing, focused and unfocused creation, placement, reconciliation, failure cleanup, and teardown." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3", + "result": "passed", + "durationSeconds": 16.1, + "summary": "The candidate passed exact host/client cardinality, split stability, rendered DOM, focus authority, close convergence, and surviving editor and terminal." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "failed", + "durationSeconds": 11.6, + "summary": "Latest-main a90a18d43da333e1cc327779a3f9912a78308848 failed the byte-identical 5806b23f oracle because the HTML preview collapsed into the source editor group instead of retaining its requested split." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 6.5, + "summary": "Rebased candidate b7de9c0961a4edf389a29079b2b4d5250184b57e passed the byte-identical 5806b23f oracle: one host page, one client workspace, requested split, rendered DOM, stable focus, and browser-only close." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "failed", + "durationSeconds": 10.9, + "summary": "Rebased candidate b7de9c0961a4edf389a29079b2b4d5250184b57e with only the side-preview owning-runtime routing seam disabled failed the byte-identical 5806b23f oracle with two client workspaces." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 7.6, + "summary": "Final candidate d5767481b982b736e7cc5b4653b2a32a61280638 on merge-base 36d45af062ec4022265aabac8fc6a9d36eecedf1 passed the byte-identical 5806b23f oracle after final review and rebase: one host page, one client workspace, requested split, rendered DOM, stable focus, and browser-only close." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "failed", + "durationSeconds": 11.8, + "summary": "Latest-main 346e59c879 failed the byte-identical 2ec1dcf1 oracle with two client HTML browser workspaces instead of one." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 8.4, + "summary": "Candidate d05217c40d passed the byte-identical 2ec1dcf1 oracle: one host page, one client workspace, stable split, rendered DOM, editor focus after creation, explicit-click browser focus, and browser-only close." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-browser-focus.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "failed", + "durationSeconds": 12.3, + "summary": "Candidate d05217c40d with only the side-preview focusOnCreate:false call disabled failed the byte-identical 2ec1dcf1 oracle because preview creation activated the browser instead of preserving editor focus." + } + ], + "runtimeBudget": { + "p95Seconds": 90, + "scope": "focused host/renderer contracts plus normal and faulted headed/headless paired-runtime journeys" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "The candidate passed isolated local macOS Electron runs before and after the final rebase; longer CI and soak history is not yet available." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The unchanged STA-4063 five-assertion oracle is red 5/5 on scan e4c278eb52 and latest main bc2e30000b, partially green 2/5 on pre-fix PR #14100, green 5/5 on candidate 14b5877a75, and red 3/5 when only the new transaction cleanup boundary is disabled on final candidate a9e6fb7716. The earlier STA-4025 transaction oracle remains red on the post-#13909 base and green on this candidate. The byte-identical 2ec1dcf1 Electron oracle remains red on latest main 346e59c879, green on candidate d05217c40d, and red with only side-preview focus disabled; historical 5806b23f evidence separately proves owning-runtime routing." + }, + "performanceBudget": { + "required": true, + "evidence": "The transaction adds no timer, polling, retry, subprocess, RPC method, stream opcode, or host publication. Capability rejection performs zero RPCs and one bounded empty-group close. Successful creation adds one post-operation list; known-page failure adds one exact close and one confirming list. The E2E-only one-shot faults are build-gated, retain one promise/flag and a bounded page-id set, and reset after each run. Pending client placements remain capped at 128 and clear on adoption, failure, or teardown." + }, + "promotionCriteria": [ + "Collect Linux and physical Windows paired-server evidence.", + "Collect 100 consecutive focused CI passes or 14 days without an unexplained flake." + ], + "knownGaps": [ + "Live paired-server validation currently covers macOS only.", + "Multiple simultaneous viewers are not exercised by the Electron journey.", + "Direct SSH remote file URLs remain intentionally unsupported and local file previews retain their existing path." + ], + "demotionRule": "Demote if one paired HTML action can create duplicate client or host browser identities, lose the requested split, steal editor focus before an explicit browser click, lose browser focus after that click, or remove unrelated editor or terminal state on close." + }, { "id": "browser-stream.bounded-reconnect", "title": "Remote browser streams recover within a bounded retry budget", @@ -2440,7 +3046,7 @@ "platform": "macos", "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts", "result": "passed", - "durationSeconds": 0.4, + "durationSeconds": 0.34, "summary": "1 test file passed, 58 tests passed; covers cwdFallback forwarding only for local fresh spawns and metadata handoff." }, { @@ -2686,6 +3292,130 @@ ], "demotionRule": "Demote or quarantine if identity-mismatched completion can retire newer work, cleanup retains compact authority, or the focused gate flakes without a product or harness bug." }, + { + "id": "agent-launch.discovery-authority", + "title": "Agent discovery and launch use the same workspace authority", + "maturity": "experimental", + "protection": "partial", + "owner": "agent-session", + "layer": "renderer-store-contract", + "surfaces": ["Quick Launch agent inventory", "agent launch", "Floating Workspace"], + "platforms": ["macos", "linux", "windows"], + "providers": ["local", "wsl", "ssh", "remote-runtime"], + "coveredPlatforms": ["macos", "windows"], + "coveredProviders": ["local", "wsl"], + "coverageNotes": "A deterministic Windows-mode renderer oracle keeps an active WSL project and explicit-local Floating Workspace mounted together with disjoint agent inventories, then independently asserts discovery and launch authority. A headed physical Windows 2 journey with real Ubuntu WSL2 independently verified the rendered inventory and native PowerShell launch; SSH and paired-runtime behavior retain their existing contract coverage.", + "motivatingLinks": [ + "https://linear.app/stably/issue/STA-4027/p1-floating-workspace-agent-detection-still-uses-active-wsl-project", + "https://github.com/stablyai/orca/pull/13995" + ], + "invariant": "Every agent launch surface must advertise the provider set detected on its explicit execution authority and launch on that same authority; a local Floating Workspace must never inherit an unrelated active project's WSL, SSH, or paired-runtime context.", + "oracle": "Model an active WSL project and a native-Windows Floating Workspace with WSL-only Claude and host-only Codex. Keep both detection consumers mounted, require their advertised sets to stay disjoint through refresh, require the legacy active-project inventory to remain unchanged, then independently assert the Floating launch call and PTY transport select local IPC with no WSL project runtime.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useDetectedAgents.test.tsx src/renderer/src/hooks/useAgentDetectionTarget.test.ts src/renderer/src/store/slices/detected-agents.test.ts src/renderer/src/store/slices/local-detected-agent-state.test.ts src/renderer/src/store/slices/repos-remove-project-purge-leak.test.ts src/renderer/src/lib/local-preflight-context.test.ts src/renderer/src/lib/launch-agent-in-new-tab.test.ts --reporter=verbose", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts --reporter=dot", + "Headed Electron/CDP STA-4027 journey on Orca environment windows 2 with a selected Ubuntu-24.04 WSL project and local Floating Workspace" + ], + "testFiles": [ + "src/renderer/src/hooks/useDetectedAgents.test.tsx", + "src/renderer/src/hooks/useAgentDetectionTarget.test.ts", + "src/renderer/src/store/slices/detected-agents.test.ts", + "src/renderer/src/store/slices/local-detected-agent-state.test.ts", + "src/renderer/src/store/slices/repos-remove-project-purge-leak.test.ts", + "src/renderer/src/lib/local-preflight-context.test.ts", + "src/renderer/src/lib/launch-agent-in-new-tab.test.ts", + "src/renderer/src/components/terminal-pane/pty-connection.test.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/hooks/useDetectedAgents.test.tsx", + "assertions": [ + "the active WSL project advertises only its WSL agent while Floating advertises only the native-host agent", + "Floating refresh preserves both scoped inventories and does not overwrite the legacy active-project inventory" + ] + }, + { + "file": "src/renderer/src/store/slices/local-detected-agent-state.test.ts", + "assertions": [ + "same-context callers deduplicate without cached broadcast fanout", + "refresh supersedes stale detection and failed cold refresh remains retryable", + "project removal evicts settled and in-flight context state" + ] + }, + { + "file": "src/renderer/src/store/slices/repos-remove-project-purge-leak.test.ts", + "assertions": [ + "removing one project evicts its authority-scoped agent inventory without disturbing another project" + ] + }, + { + "file": "src/renderer/src/lib/launch-agent-in-new-tab.test.ts", + "assertions": [ + "the advertised Floating agent launches in a Floating tab with null runtime ownership and no paired-runtime create call" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-connection.test.ts", + "assertions": [ + "the Floating agent's actual PTY selects local IPC, carries executionHostId local, and omits the active project's WSL runtime" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useDetectedAgents.test.tsx src/renderer/src/hooks/useAgentDetectionTarget.test.ts src/renderer/src/store/slices/detected-agents.test.ts src/renderer/src/store/slices/local-detected-agent-state.test.ts src/renderer/src/store/slices/repos-remove-project-purge-leak.test.ts src/renderer/src/lib/local-preflight-context.test.ts src/renderer/src/lib/launch-agent-in-new-tab.test.ts --reporter=verbose", + "result": "passed", + "durationSeconds": 2, + "summary": "Seven focused files passed independent WSL/local inventory, refresh isolation, cache lifecycle, project eviction, and Floating launch-call assertions." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts --reporter=dot", + "result": "passed", + "durationSeconds": 20, + "summary": "The full PTY connection suite passed the independent Floating native-host transport oracle." + }, + { + "date": "2026-08-12", + "runner": "manual", + "platform": "windows", + "command": "Headed Electron/CDP STA-4027 journey on Orca environment windows 2 with a selected Ubuntu-24.04 WSL project and local Floating Workspace", + "result": "passed", + "durationSeconds": 22.3, + "summary": "Environment abfee683-80eb-4ac3-ada0-da5d1b6303a6, runtime b3bea13e-f6b7-41e7-b850-0a118f7eda38: Floating advertised native Claude/Codex without WSL-only Gemini and launched Claude through native PowerShell with local host ownership while the WSL project remained active." + } + ], + "runtimeBudget": { + "p95Seconds": 40, + "scope": "eight focused renderer authority, cache, eviction, and launch test files" + }, + "flakeHistory": { + "status": "soaking", + "evidence": "The deterministic oracle uses mocked provider results and React effect barriers. Exact-head PR run 31644438349 passed the full Node 24/26 matrix; an earlier patch-identical run's transient shard failures passed on rerun, but long-term soak history is not yet available." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The byte-identical oracle fails on merged PR #13995 and the tested latest-main snapshot ebe5125476 because Floating receives the WSL-only Claude inventory while launch remains local. The candidate passes; disabling the scoped Floating target reproduces the mismatch." + }, + "performanceBudget": { + "required": true, + "evidence": "Floating uses one stable host context key, retained tab bars do not rescan worktree indexes on store writes, concurrent probes deduplicate per context, and in-flight promise entries are deleted on settlement." + }, + "promotionCriteria": [ + "Collect 100 consecutive focused CI passes or 14 days of soak history.", + "Keep the physical Windows/WSL inventory and launch journey green when authority routing changes.", + "Keep disjoint provider inventories, refresh isolation, launch authority, and bounded in-flight state green." + ], + "knownGaps": [ + "Live SSH and paired-runtime launch journeys are covered by existing authority contracts rather than this focused oracle." + ], + "demotionRule": "Demote if discovery and launch can resolve different authorities, a scoped Floating probe overwrites the active-project inventory, or local context selection adds recurring scans or retained in-flight entries." + }, { "id": "agent-session.provider-ownership", "title": "Provider sessions are resumed once per workspace ownership claim", @@ -3226,16 +3956,22 @@ "providers": ["local", "remote-runtime", "ssh", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "remote-runtime", "ssh", "wsl"], - "coverageNotes": "Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, Add Project, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, Add Project owner capture and stale-result fencing, host-qualified group/folder/worktree identity, and restart reset of transient routing are covered. A visible macOS Orca desktop server plus a separate paired Electron client proves real Git, plain-folder, Clone, Create, nested import, runtime-switch, disconnect, reconnect, concurrently visible same-ID local/runtime repo/worktree/group/folder rows, reversed catalog order, reversed refresh completion, local-after-runtime catalog refresh routing, and first paired-terminal activation without local fallback; hidden-window parity also passed. Live Linux, Windows, WSL, and SSH Add Project journeys remain uncollected.", - "motivatingLinks": ["https://github.com/stablyai/orca/pull/9687"], - "invariant": "Only an explicit user change in Settings > Remote Orca Servers > Advanced > Active Server may mutate activeRuntimeEnvironmentId. Connecting, pairing, disconnecting, selecting or revealing a workspace or terminal, browser/mobile handoff, remote navigation, and reconnect must use transient or target-owner routing and must never rewrite the durable preference. Every Add Project scan, add, import, catalog refresh, and worktree refresh must stay on the host selected when that operation began, even if the durable preference changes or the repo catalog is not hydrated. Generic settings mutation cannot bypass the dedicated preference IPC.", - "oracle": "Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat with multiple clients and servers, browser host switches, remote-owned and local-owned workspaces, pairing/connect/disconnect, and generic settings writes. In a separate paired Electron client, select a non-default headed runtime and add a real Git repo, plain folder, clone, created project, and nested repos while switching the preference and disconnecting/reconnecting. Before Git Add, plain-folder Add, Clone, and Create completion, insert a same-ID local repo/worktree decoy; require final activation to remain on the captured runtime. Merge same-ID local/runtime repo, worktree, group, and folder rows, reverse same-host refresh completions, overlap refresh with reconnect, issue ordinary unqualified local refreshes, then create the first paired runtime terminal while the same-ID local/runtime worktrees remain visible. Require only the selected server inventory to change, exact runtime ownership in the client store, preserved host-qualified catalogs, authoritative direct-SSH pruning without runtime sibling loss, visible projects, and zero direct SSH fallback. Assert only the dedicated validated preference method changes activeRuntimeEnvironmentId and stale host-operation completions cannot overwrite the newly selected transient host.", + "coverageNotes": "Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, Add Project, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, Add Project eligibility/owner capture/stale-result fencing, host-qualified group/folder/worktree identity, and restart reset of transient routing are covered. A visible macOS Orca desktop server plus separate paired Electron and web clients prove selected-runtime Add Project operations and disabled creation when the only listed host is blocked or unavailable; headless-server parity also passed. Live Linux, Windows, WSL, and SSH Add Project journeys remain uncollected.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/pull/9687", + "https://linear.app/stably/issue/STA-4024/p1-paired-web-add-project-enables-unavailable-host-fallback-after-pr" + ], + "invariant": "Only an explicit user change in Settings > Remote Orca Servers > Advanced > Active Server may mutate activeRuntimeEnvironmentId. Connecting, pairing, disconnecting, selecting or revealing a workspace or terminal, browser/mobile handoff, remote navigation, and reconnect must use transient or target-owner routing and must never rewrite the durable preference. Every Add Project selected host must satisfy canSelectAddRepoHost; paired web has no local filesystem fallback, so no valid host means Browse, Clone, and Create remain disabled. Every operation stays on the host selected when it began, even if preference or catalog state changes. Generic settings mutation cannot bypass the dedicated preference IPC.", + "oracle": "Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat transient routing and selected-runtime Add Project operations with exact-ID host decoys and completion reordering. Separately pair the real web client to an isolated headed host, then make its sole still-listed runtime compatibility-blocked and unavailable. Require a null authoritative selection, a disabled host option, and disabled Browse, Clone, and Create actions with no local fallback. Repeat against headless serve. Run the byte-identical selector/action contract on latest main, candidate, and candidate with the eligibility seam disabled.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/settings.test.ts src/main/ipc/runtime-environments.test.ts src/renderer/src/store/slices/settings.test.ts src/renderer/src/store/slices/browser.test.ts src/renderer/src/components/settings/browser-session-host-selection.test.ts src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts src/renderer/src/components/status-bar/SshStatusSegment.test.ts src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts src/renderer/src/hooks/useIpcEvents.test.ts src/renderer/src/web/web-preload-api.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list-host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts src/renderer/src/components/sidebar/add-repo-browse-authority.test.ts src/renderer/src/components/sidebar/AddRepoDialogStepContent.test.tsx src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/runtime/runtime-server-directory-browser.test.ts src/renderer/src/store/slices/repos-paired-runtime-add.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list-host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees.test.ts src/renderer/src/runtime/web-runtime-session.test.ts --maxWorkers=1", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", - "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" + "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", + "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-web-add-project-unavailable-host.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-web-add-project-unavailable-host.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" ], "testFiles": [ "src/main/ipc/settings.test.ts", @@ -3246,11 +3982,14 @@ "src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts", "src/renderer/src/components/status-bar/SshStatusSegment.test.ts", "src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts", + "src/renderer/src/components/sidebar/add-repo-browse-authority.test.ts", "src/renderer/src/hooks/useIpcEvents.test.ts", "src/renderer/src/web/web-preload-api.test.ts", "src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx", "src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx", "src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts", + "src/renderer/src/components/sidebar/AddRepoDialogStepContent.test.tsx", + "src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx", "src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts", "src/renderer/src/components/sidebar/project-added-default-checkout.test.ts", "src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts", @@ -3262,15 +4001,46 @@ "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", "src/renderer/src/lib/worktree-runtime-owner.test.ts", "src/renderer/src/store/selectors.test.ts", + "src/renderer/src/store/slices/repos-paired-runtime-add.test.ts", "src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts", "src/renderer/src/store/slices/repos-project-groups.test.ts", "src/renderer/src/store/slices/repos-selected-owner-routing.test.ts", "src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts", "src/renderer/src/store/slices/worktrees.test.ts", "src/renderer/src/runtime/web-runtime-session.test.ts", - "tests/e2e/pr11346-selected-runtime-add.spec.ts" + "tests/e2e/pr11346-selected-runtime-add.spec.ts", + "tests/e2e/paired-web-add-project-unavailable-host.spec.ts" ], "assertionRefs": [ + { + "file": "src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts", + "assertions": [ + "paired web hides the viewing computer as an Add Project filesystem authority and selects only an eligible paired runtime", + "a sole blocked or errored runtime remains listed but produces no selected Add Project host" + ] + }, + { + "file": "src/renderer/src/components/sidebar/add-repo-browse-authority.test.ts", + "assertions": [ + "paired runtime browsing opens the host browser without invoking native pickFolders while desktop local and SSH routes remain intact" + ] + }, + { + "file": "src/renderer/src/components/sidebar/AddRepoDialogStepContent.test.tsx", + "assertions": ["paired runtime browsing renders the in-app host filesystem browser"] + }, + { + "file": "src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx", + "assertions": [ + "host-scoped Add Project actions remain disabled until a paired runtime is selectable" + ] + }, + { + "file": "src/renderer/src/store/slices/repos-paired-runtime-add.test.ts", + "assertions": [ + "an explicitly selected paired runtime submits repo.add to that runtime without native repo or folder-picker calls" + ] + }, { "file": "src/main/ipc/settings.test.ts", "assertions": [ @@ -3378,9 +4148,35 @@ "keeps every expanded selected-runtime Add Project path in hidden-window desktop parity", "creates the first paired runtime terminal while same-ID local/runtime worktrees remain visible without clearing the selected runtime owner" ] + }, + { + "file": "tests/e2e/paired-web-add-project-unavailable-host.spec.ts", + "assertions": [ + "a version-blocked sole host stays visible and non-selectable while Browse, Clone, and Create are disabled", + "an unavailable sole host has the same disabled action contract without a local fallback", + "the rendered contract passes against headed desktop and headless serve hosts" + ] } ], "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-web-add-project-unavailable-host.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 12.3, + "summary": "A real paired web client against a visible desktop host kept the sole blocked and unavailable runtime listed but non-selectable, with Browse, Clone, and Create disabled and no local host fallback." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-web-add-project-unavailable-host.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 5.8, + "summary": "The same present-but-blocked and present-but-unavailable Add Project action oracle passed against isolated headless serve." + }, { "date": "2026-07-22", "runner": "local", @@ -3455,7 +4251,7 @@ }, "redGreenEvidence": { "status": "complete", - "evidence": "The byte-identical focused oracle (SHA-256 6de18c140a86801460e58f52287e27a58b97f1576f9f387fa82e1bd4eb378f7b) fails 2/3 on review baseline aa6f945001a5f78a07663c854fabb95c55d8b40b and on the r5-disabled parent e21f4ca58e: local-first lookup returns /local/repo and folder activation has no runtime host. It passes 3/3 on the candidate. Main later advanced to 94cf2f1422f30fc309cb47c5e864a831d516fa8b without changing any of the candidate's 68 files or the focused oracle production boundary; the rebased disabled parent f247d961cab15237bc7fcf0598fe76007f78ec7c has the same stable patch ID as e21f4ca58e. The final paired spec and fixture have SHA-256 bd6d9014d1bed2715397bcd2121d5d7e01792347b13ff14778ccf608bf98789c and d1d78a82f868e2f3152777550825c0ca2d4dc3cba5c6de548e066d2931751fc7. With the final runtime-session owner fix disabled, the focused session test fails 3/43 and the byte-identical hidden paired oracle deterministically creates the host terminal but reports null active client owner while same-ID local/runtime worktrees remain. The integrated candidate passes the same focused test and both headed/hidden paired oracles with exact runtime ownership, server inventory, local exclusion, preserved catalogs, visible rows, and zero direct SSH fallback. Earlier Active Server preference paths retain deterministic coverage but do not yet have a saved intentional-break artifact." + "evidence": "The Add Project selector file from fix-disabled overlay 17a612c819 and candidate 8abf0f5d20 is byte-identical (SHA-256 f34c3c69c8adba23811c3a3b6a0efb669f787666c5ada086df8a167e785eea20): its blocked and unavailable sole-host cases fail with the production fix disabled on latest main ebe5125476 after PR #13909 and pass on the candidate. The focused combined selector/transaction invocation was 3 failed with 69 skipped on the red overlay and 3 passed with 75 skipped on the candidate; the different totals come from supplemental browser-transaction cases, not this selector file. The originating/latest affected main 1136503c6a and its fix-disabled overlay were also red before the provider-gating rebase. The byte-identical focused oracle (SHA-256 6de18c140a86801460e58f52287e27a58b97f1576f9f387fa82e1bd4eb378f7b) fails 2/3 on review baseline aa6f945001a5f78a07663c854fabb95c55d8b40b and on the r5-disabled parent e21f4ca58e: local-first lookup returns /local/repo and folder activation has no runtime host. It passes 3/3 on the candidate. Main later advanced to 94cf2f1422f30fc309cb47c5e864a831d516fa8b without changing any of the candidate's 68 files or the focused oracle production boundary; the rebased disabled parent f247d961cab15237bc7fcf0598fe76007f78ec7c has the same stable patch ID as e21f4ca58e. The final paired spec and fixture have SHA-256 bd6d9014d1bed2715397bcd2121d5d7e01792347b13ff14778ccf608bf98789c and d1d78a82f868e2f3152777550825c0ca2d4dc3cba5c6de548e066d2931751fc7. With the final runtime-session owner fix disabled, the focused session test fails 3/43 and the byte-identical hidden paired oracle deterministically creates the host terminal but reports null active client owner while same-ID local/runtime worktrees remain. The integrated candidate passes the same focused test and both headed/hidden paired oracles with exact runtime ownership, server inventory, local exclusion, preserved catalogs, visible rows, and zero direct SSH fallback. Earlier Active Server preference paths retain deterministic coverage but do not yet have a saved intentional-break artifact." }, "performanceBudget": { "required": true, @@ -6005,7 +6801,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-provider-reattach-incarnation.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/startup/ssh-startup-reconnect.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts src/shared/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/TerminalPaneDisconnectedBanner.test.tsx src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts src/shared/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/direct-ssh-terminal-retry.test.ts src/renderer/src/store/slices/direct-ssh-pane-detach-ledger.test.ts src/renderer/src/store/slices/direct-ssh-terminal-recovery.test.ts src/renderer/src/store/slices/direct-ssh-terminal-workspace-scope.test.ts src/renderer/src/store/slices/terminals-hydration.test.ts src/renderer/src/store/slices/repos-ssh-host-reconciliation.test.ts src/renderer/src/hooks/direct-ssh-reconnect-coordinator.test.ts src/renderer/src/hooks/direct-ssh-host-hydration.test.ts src/renderer/src/hooks/direct-ssh-state-routing.test.ts src/renderer/src/hooks/remote-workspace-target-sync.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/repos-remote.test.ts src/main/ipc/ssh.test.ts src/main/ipc/worktrees.test.ts src/main/runtime/public-ssh-state.test.ts src/main/ssh/ssh-connection-manager.test.ts src/main/ssh/ssh-connection.test.ts src/main/ssh/ssh-provider-authority.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/runtime-client-events.test.ts src/renderer/src/runtime/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts src/shared/ssh-types.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", @@ -6026,7 +6822,7 @@ "src/renderer/src/components/terminal-pane/pty-transport.test.ts", "src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts", "src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts", - "src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx", + "src/renderer/src/components/terminal-pane/TerminalPaneDisconnectedBanner.test.tsx", "src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts", "src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts", "src/renderer/src/runtime/web-session-terminal-handle-events.test.ts", @@ -6108,7 +6904,7 @@ ] }, { - "file": "src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx", + "file": "src/renderer/src/components/terminal-pane/TerminalPaneDisconnectedBanner.test.tsx", "assertions": [ "automatic recovery renders as a quiet bounded status without a button", "the disconnected state exposes one explicit Reconnect action" @@ -6383,7 +7179,7 @@ "date": "2026-07-21", "runner": "local", "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts src/shared/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/TerminalPaneDisconnectedBanner.test.tsx src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts src/shared/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts", "result": "passed", "durationSeconds": 5, "summary": "Eleven fault-injection and recovery-UI files and 127 tests passed, covering suspended heartbeat clocks, stale socket, PTY, and create generations, canonical pre-ready close recovery with one replacement subscription, cold and repeated PTY reattachment, authoritative health, bounded PTY and terminal-create recovery, post-probe timeout clipping, manually retryable create cutoff, accurate capability-probe failures, same-PTY manual reconnect, pane-state cleanup, fatal error deduplication, stable create identity, cross-process PTY adoption, and fail-closed legacy inventory." @@ -6701,7 +7497,7 @@ }, { "id": "terminal-input.ime-and-synthetic-forwarding", - "title": "IME, native text, and synthetic input commit exactly once and do not leak preedit bytes", + "title": "IME, native text, and synthetic input commit exactly once, do not leak preedit bytes, and pair every claimed press with one release", "maturity": "experimental", "protection": "partial", "owner": "terminal-input", @@ -6718,18 +7514,19 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, and Electron/CDP live-PTY Sogou-style repros. Real Linux/Sogou OS IME automation, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps.", + "coverageNotes": "Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, Electron/CDP live-PTY Sogou-style repros, and a macOS renderer/main slice for Preview kitty commits: claimed press/release pairing in both keyup orderings, and snapshot flag provenance where a proven 0, a proven non-zero, and an absent field stay three distinct facts from daemon through the sequenced remote SnapshotStart frame. Real Linux/Sogou OS IME automation, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6699", "https://github.com/stablyai/orca/pull/6682", "https://github.com/stablyai/orca/pull/6513", "https://github.com/stablyai/orca/pull/6999" ], - "invariant": "Composition, native text forwarding, synthetic input, paste, and platform keyboard bypass paths must not send preedit/control bytes before commit and must commit text exactly once to the intended PTY.", - "oracle": "The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and Linux/Sogou candidate Space/digit selectors do not leak keydown/keypress/keyup while ordinary and long-held letter-to-digit typing remains available. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit selectors submit only the committed Chinese text, while the legacy orphaned-letter-keyup sequence sends no selector byte to the PTY. Real legacy IME commit preservation and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", + "invariant": "Composition, native text forwarding, synthetic input, paste, and platform keyboard bypass paths must not send preedit/control bytes before commit and must commit text exactly once to the intended PTY. When the snapshot source proves kitty state, macOS Preview commits must use the application's effective flags after the sequenced snapshot and every proven replay/live transition, and a claimed press delivered under report_event_types must produce exactly one matching release regardless of whether keyup arrives before or after insertText and regardless of xterm's defensive internal reset.", + "oracle": "Exact outbound bytes from the REAL native-text forwarder behind installPreviewImeBridge after initial snapshot restore, replacement resync, live transitions, and both keydown->insertText->keyup and keydown->keyup->insertText orderings; a wiring-only mock is supporting evidence, not the oracle. The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and Linux/Sogou candidate Space/digit selectors do not leak keydown/keypress/keyup while ordinary and long-held letter-to-digit typing remains available. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit selectors submit only the committed Chinese text, while the legacy orphaned-letter-keyup sequence sends no selector byte to the PTY. Real legacy IME commit preservation and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-linux-candidate-state.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/renderer/src/runtime/remote-runtime-terminal-snapshot-kitty-flags.test.ts src/main/daemon/daemon-pty-adapter.test.ts", "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts" ], "testFiles": [ @@ -6742,6 +7539,14 @@ "src/renderer/src/components/terminal-pane/terminal-ime-linux-candidate-state.test.ts", "src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts", "src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts", + "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts", + "src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts", + "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx", + "src/shared/terminal-kitty-keyboard-mode-tracker.test.ts", + "src/main/ipc/terminal-preview.test.ts", + "src/main/ipc/terminal-preview-output-stream.test.ts", + "src/renderer/src/runtime/remote-runtime-terminal-snapshot-kitty-flags.test.ts", + "src/main/daemon/daemon-pty-adapter.test.ts", "tests/e2e/chinese-ime-chat-input-repro.spec.ts" ], "assertionRefs": [ @@ -6806,6 +7611,65 @@ "macOS standalone Process key behavior and composition-owned key suppression stay intact" ] }, + { + "file": "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts", + "assertions": [ + "the real forwarder behind the Preview bridge encodes the commit from the snapshot-proven flags before any live output", + "flags 0/1 commit raw text, flags 2 add one CSI-u release, flags 8 emit one CSI-u press, and flags 10 emit a CSI-u press followed by exactly one release", + "both keydown->insertText->keyup and keydown->keyup->insertText orderings produce the same bytes", + "the release is emitted by the forwarder while xterm's internal kitty flags stay 0", + "the mutable flags getter is read exactly once, at commit time, never on keydown or keyup", + "auto-repeat, two-key rollover, a swallowed commit, a retired claim, blur, and disposal each emit at most one release and never synthesize one" + ] + }, + { + "file": "src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts", + "assertions": [ + "a Preview opened on a snapshot carrying flags 8 adopts 8 before any live output", + "a replacement snapshot whose ANSI carries no kitty bytes keeps its proven flags, and a proven 0 clears an earlier 8", + "a missing field leaves the mirror unproven at the raw-text fallback and a later live negotiation still upgrades it", + "restored flags land on the screen the snapshot scan selected", + "a proven post-snapshot suffix advances the stack while redelivered bytes apply idempotently" + ] + }, + { + "file": "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx", + "assertions": [ + "the Preview hands the forwarder the live kitty mirror seeded from the snapshot's proven flags" + ] + }, + { + "file": "src/shared/terminal-kitty-keyboard-mode-tracker.test.ts", + "assertions": [ + "a fresh PTY's known 0 is distinguishable from a snapshot's unproven 0 fallback", + "restoreSnapshotFlags proves only the active screen and rejects non-safe-integer values", + "provenance survives absolute sets, screen switches, RIS and DECSTR, but a pop past omitted push history returns to unknown rather than a manufactured 0" + ] + }, + { + "file": "src/main/ipc/terminal-preview.test.ts", + "assertions": [ + "terminalPreview:connect returns image, sequence, and kitty flags from the same capture, including after an overflow retry" + ] + }, + { + "file": "src/main/ipc/terminal-preview-output-stream.test.ts", + "assertions": [ + "fully covered chunks are dropped, a sliced or strictly newer sequenced suffix gets live mode semantics, and an unsliceable or metadata-less overlap gets replay semantics" + ] + }, + { + "file": "src/renderer/src/runtime/remote-runtime-terminal-snapshot-kitty-flags.test.ts", + "assertions": [ + "SnapshotStart decodes proven 0 and 8 with their seq into requested and host-pushed snapshot paths", + "negative, fractional, unsafe, and non-numeric values are treated as absent rather than clamped", + "an old host that omits the field stays usable and is never coerced to a proven 0" + ] + }, + { + "file": "src/main/daemon/daemon-pty-adapter.test.ts", + "assertions": ["daemon provider snapshots publish proven kitty flags including a known 0"] + }, { "file": "tests/e2e/chinese-ime-chat-input-repro.spec.ts", "assertions": [ @@ -6817,6 +7681,15 @@ } ], "evidenceRuns": [ + { + "date": "2026-08-11", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/renderer/src/runtime/remote-runtime-terminal-snapshot-kitty-flags.test.ts src/main/daemon/daemon-pty-adapter.test.ts", + "result": "passed", + "durationSeconds": 9.84, + "summary": "8 test file(s) passed, 288 tests, covering the Preview kitty slice: real forwarder bytes at snapshot-proven flags, press/release pairing across both keyup/insertText orderings, and flag provenance where a proven 0, a proven non-zero, and an absent field stay three distinct facts — asserted on the daemon snapshot and on a host-pushed remote snapshot that carries the flags with their sequence. The emitter-side rule that a remote SnapshotStart withholds flags without a seq has no direct assertion yet; the client-side gate is what these files pin." + }, { "date": "2026-08-09", "runner": "local", @@ -6882,7 +7755,7 @@ }, "redGreenEvidence": { "status": "partial", - "evidence": "Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, and live-PTY Sogou-style candidate commits. Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." + "evidence": "Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, live-PTY Sogou-style candidate commits, and the Preview kitty slice (press/release pairing in both keyup orderings, and snapshot flag provenance separating a proven 0 from an absent field). Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." }, "performanceBudget": { "required": true, @@ -6895,7 +7768,9 @@ ], "knownGaps": [ "Current commands include renderer-unit coverage and a CDP-driven Electron repro; real OS IME automation may need manual or soak evidence.", - "Backspace/Enter during composition, JIS yen, Arabic/RTL, paste edge cases, and Windows ConPTY post-agent key reset still need representative gate coverage." + "Backspace/Enter during composition, JIS yen, Arabic/RTL, paste edge cases, and Windows ConPTY post-agent key reset still need representative gate coverage.", + "An older remote host omits the optional SnapshotStart kitty field, so a new client falls back to raw commits until live negotiation is observed.", + "Snapshot authorities expose only the active screen's effective flags, not kitty's complete two-screen push stacks; a pop that crosses the restored boundary degrades to unknown rather than a proven value." ], "demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence." }, @@ -7238,14 +8113,16 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon"], - "coverageNotes": "Runtime and provider-contract tests on macOS cover exact-PTY authorization, local/daemon fresh confirmation, exact ConPTY membership, and unsupported-provider fail-closed behavior. Physical Windows, live Linux, SSH, WSL, and remote-runtime validation remain explicit gaps; providers without confirmation preserve conservative refusal on a shell conflict.", + "coverageNotes": "Runtime and provider-contract tests on macOS cover exact-PTY authorization, verified managed-Claude launch identity, local/daemon fresh confirmation, exact ConPTY membership, and unsupported-provider fail-closed behavior. Physical Windows, live Linux, SSH, WSL, and remote-runtime validation remain explicit gaps; providers without confirmation preserve conservative refusal when no verified launch identity exists.", "motivatingLinks": ["https://github.com/stablyai/orca/issues/8303"], - "invariant": "A guarded note send writes only to the exact PTY binding checked by the guard and only while permission/wait evidence allows input; fresh hook state conflicting with an ordinary shell foreground requires fresh provider confirmation of a recognized agent in that PTY.", - "oracle": "Fresh explicit state plus ordinary PowerShell plus confirmed recognized agent is sendable on the same PTY. Confirmed shell/non-agent, unavailable confirmation, PTY exit, handle rebind, or a callback PTY mismatch returns a refusal or not-writable result and writes zero bytes.", + "invariant": "A guarded note send writes only to the exact PTY binding checked by the guard and only while permission/wait evidence allows input; a generic busy title requires independent agent identity from the title, a verified managed launch bound to the current PTY incarnation, or the foreground process; fresh hook state conflicting with an ordinary shell foreground requires fresh provider confirmation of a recognized agent in that PTY.", + "oracle": "A quarter-circle Claude task title authorizes without a provider lookup only on the exact PTY incarnation carrying verified managed-Claude launch identity; the same title in a bare pane, with an unverified launch hint, or after PTY incarnation replacement is refused while current Claude activity remains a working signal. Fresh explicit state plus ordinary PowerShell plus confirmed recognized agent is sendable on the same PTY. Confirmed shell/non-agent, unavailable confirmation, PTY exit, handle rebind, or a callback PTY mismatch returns a refusal or not-writable result and writes zero bytes.", "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/quarter-circle-title-send-authorization.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send.test.ts src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx" ], "testFiles": [ + "src/main/runtime/quarter-circle-title-send-authorization.test.ts", "src/main/runtime/orca-runtime.test.ts", "src/main/runtime/rpc/terminal-send.test.ts", "src/main/ipc/pty.test.ts", @@ -7258,6 +8135,14 @@ "src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx" ], "assertionRefs": [ + { + "file": "src/main/runtime/quarter-circle-title-send-authorization.test.ts", + "assertions": [ + "a verified managed-Claude launch authorizes a task-text quarter-circle title without foreground-process work", + "a bare pane, an unverified launch hint, and a replacement PTY incarnation remain refused", + "quarter circles remain working signals and braille authorization is unchanged" + ] + }, { "file": "src/main/runtime/orca-runtime.test.ts", "assertions": [ @@ -7325,6 +8210,15 @@ } ], "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/quarter-circle-title-send-authorization.test.ts", + "result": "passed", + "durationSeconds": 20.9, + "summary": "The focused file passed 9 tests, including current-incarnation managed-Claude authorization with zero foreground calls and fail-closed bare, unverified, and replacement-incarnation quarter-circle titles." + }, { "date": "2026-07-11", "runner": "local", @@ -7345,11 +8239,11 @@ }, "redGreenEvidence": { "status": "partial", - "evidence": "Removing strong confirmation fails the shell-conflict success oracle, while removing either exact-binding comparison fails zero-write rebind coverage; saved intentional-break and physical Windows evidence remain missing." + "evidence": "Before the verified-launch fallback, the managed-Claude unavailable-foreground case failed with isRunningAgent false; the focused file passed 7 tests after the fix. Removing the launch-incarnation comparison makes the replacement-incarnation refusal fail. Removing strong confirmation fails the shell-conflict success oracle, while removing either exact-binding comparison fails zero-write rebind coverage; physical Windows evidence remains missing." }, "performanceBudget": { "required": true, - "evidence": "Confirmation is invoked at most once per status evaluation and only for fresh explicit hook state whose ordinary foreground result is a shell. Count tests prove permission/title blockers and ordinary recognized-agent evidence add zero confirmations; no polling, retry, session listing, provider fanout, or runtime-global cache is added, and existing provider snapshot dedup remains authoritative." + "evidence": "Confirmation is invoked at most once per status evaluation and only for fresh explicit hook state whose ordinary foreground result is a shell. Count tests prove verified managed-Claude launch identity, permission/title blockers, and ordinary recognized-agent evidence add zero provider calls; no polling, retry, session listing, provider fanout, or runtime-global cache is added, and existing provider snapshot dedup remains authoritative." }, "promotionCriteria": [ "Run the browser annotation existing-agent and repeat-send path in Electron on Windows ConPTY without a recognition refusal.", @@ -7362,7 +8256,7 @@ "SSH, WSL, legacy daemon, and remote-runtime providers without confirmation remain intentionally fail-closed on an ordinary-shell conflict; no live artifacts cover those degraded paths.", "No live Linux PTY, paired-web, mobile/relay, restore/replay, or multi-window artifact is attached; those surfaces receive no renderer, persistence, or protocol change." ], - "demotionRule": "Keep non-blocking or demote to protection none if provider confirmation becomes unconditional, exact-PTY mismatch can write bytes, unsupported providers fail open, or the focused gate flakes without an actionable product or harness defect." + "demotionRule": "Keep non-blocking or demote to protection none if a generic busy title authorizes without exact title, verified-launch, or foreground identity; provider confirmation becomes unconditional; exact-PTY mismatch can write bytes; unsupported providers fail open; or the focused gate flakes without an actionable product or harness defect." }, { "id": "terminal-input.agent-prompt-injection", @@ -7507,19 +8401,25 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh"], - "coverageNotes": "A deterministic service-state-machine oracle now models a current-contract worker and coordinator whose renderer graph identities disappear across an app/runtime update. It exercises the production verifier with restored PTY and hydrated hook commitments, proves authenticated completion replay across a fresh runtime, explicit takeover, ordinary mail routing, remote-attachment process fencing, retained Task/Dispatch/terminal identity, and unchanged fixture marker bytes, and rejects foreign pane evidence. Other deterministic units cover authority-aware legacy formatting, exact legacy worker identity planning, local worker presentation, retained-output reads after adoption, reveal-failure warnings, stable-pane Run/Dispatch routing, creator pane/process/Run-generation fencing, indexed retained-Run lookup scaling, the SSH in-process CLI fallback, and federated non-reveal. Two isolated macOS Electron journeys launch fake Codex workers through the real RPC path and record append-only spawn/interruption ledgers. They assert immediate inactive presentation, one live agent PID, stable PTY/incarnation/tab/leaf/worktree/Task/Dispatch identity, and no interruption after workspace re-entry; the restart journey additionally removes renderer ownership, marks the Dispatch legacy, retains the daemon process across an app restart, and proves exact background adoption with readable ACK output and no resume replay. Distinct A/B artifacts plus live SSH, WSL, folder, remote-runtime, Linux, and Windows cutover journeys remain explicit gaps.", - "motivatingLinks": ["https://github.com/stablyai/orca/pull/11107#discussion_r3663321387"], - "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata. A nested worker's creator edge requires the current creator pane, process incarnation, and owning Run generation; reminting and rebinding that pane to another Run must remove the stale edge. Explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", + "coverageNotes": "A deterministic service-state-machine oracle now models a current-contract worker and coordinator whose renderer graph identities disappear across an app/runtime update. It exercises the production verifier with restored PTY and hydrated hook commitments, proves authenticated completion replay across a fresh runtime, explicit takeover, ordinary mail routing, remote-attachment process fencing, retained Task/Dispatch/terminal identity, and unchanged fixture marker bytes, and rejects foreign pane evidence. Other deterministic units cover authority-aware legacy formatting, exact legacy worker identity planning, local worker presentation, retained-output reads after adoption, reveal-failure warnings, stable-pane Run/Dispatch routing, creator pane/process/Run-generation fencing, indexed retained-Run lookup scaling, the SSH in-process CLI fallback, exact legacy Task/Dispatch/report-receipt verification, JSON rejection envelopes, and capability-negotiated Run-home settlement with lost-ack replay. Three isolated macOS Electron journeys launch fake Codex workers through the real RPC path. The compiled-CLI journey spawns fresh out/cli processes for rejected and accepted worker_done plus worker-release, then independently verifies runtime and SQLite state. The presentation and restart journeys assert immediate inactive presentation, one live agent PID, stable PTY/incarnation/tab/leaf/worktree/Task/Dispatch identity, and no interruption after workspace re-entry; the restart journey additionally proves exact background adoption with readable ACK output and no resume replay. Distinct A/B artifacts plus live SSH, WSL, folder, remote-runtime, Linux, and Windows cutover journeys remain explicit gaps.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/pull/11107#discussion_r3663321387", + "https://github.com/stablyai/orca/issues/13858" + ], + "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. A worker_done caller may report success only after the owning runtime returns an explicit lifecycle verdict or authoritative reads prove that the exact Task, Dispatch, and worker report receipt settled the expected outcome. A federated worker may accept only the Run-home runtime's settlement verdict. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata. A nested worker's creator edge requires the current creator pane, process incarnation, and owning Run generation; reminting and rebinding that pane to another Run must remove the stale edge. Explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", "oracle": "Drive Run create, Task create, and worker-start through production Electron runtimes with a deterministic Codex fixture. Require append-only ledgers with one still-live PID and no interruption, a visible inactive worker tab while the coordinator stays active, Run delivery through stable pane identity, and stable PTY/incarnation, tab, leaf, worktree, Task, and Dispatch across workspace re-entry. In a restart journey, retain the original daemon PTY and PID, remove renderer ownership, retain sleeping-session evidence, mark the Dispatch legacy, relaunch, and require exact inactive tab adoption, readable ACK output, cleared resume state, one spawn, and no resume argv or Conversation interrupted text after another workspace round trip. The service oracle removes renderer lookup identity from current-contract callers while retaining real restored-PTY and hook commitments, replays authenticated completion and takeover across fresh runtimes, and requires one Task, Dispatch, terminal authority, message, mutation, ordinary-mail delivery, remote process fencing, and unchanged fixture marker bytes while foreign pane evidence remains rejected. Unit tests separately remint a creator pane and process from Run A into Run B, require the nested Run A worker to fall back to its current coordinator, require indexed query plans, and bound 300 Task reads with 50,000 retained Runs. They also assert authority-specific legacy affordances, exact identity and owner matching, retained-output fallback, pane-stable routing, federated non-activation, and SSH fallback parity.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/ssh/ssh-remote-orca-cli.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts src/cli/handlers/orchestration-migration.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/formatter.test.ts src/main/runtime/rpc/methods/orchestration-federation.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/orchestration-creator-authority-performance.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts", "pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1", - "pnpm run test:e2e -- tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts --workers=1" + "pnpm run test:e2e -- tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts --workers=1", + "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ "src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts", @@ -7528,13 +8428,18 @@ "src/main/runtime/orchestration/orchestration-creator-authority-performance.test.ts", "src/main/runtime/orca-runtime.test.ts", "src/cli/handlers/orchestration.test.ts", + "src/cli/handlers/orchestration-lifecycle-rejection.test.ts", + "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", + "src/cli/handlers/orchestration-migration.test.ts", "src/cli/handlers/orchestration-check-identity.test.ts", "src/cli/handlers/orchestration-worker-cli.test.ts", "src/main/runtime/rpc/methods/orchestration.test.ts", "src/main/runtime/rpc/methods/orchestration-federation.test.ts", + "src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts", "src/main/ssh/ssh-remote-orca-cli.test.ts", "tests/e2e/orchestration-worker-terminal-visibility.spec.ts", - "tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts" + "tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts", + "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts" ], "assertionRefs": [ { @@ -7577,6 +8482,27 @@ "current formatting remains unchanged" ] }, + { + "file": "src/cli/handlers/orchestration-lifecycle-rejection.test.ts", + "assertions": [ + "an explicit current worker_done verdict completes without a compatibility read", + "a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt", + "legacy succeeded and failed reports require matching terminal Task and Dispatch state", + "stopped or stale Dispatches cannot impersonate report settlement", + "an idempotent retry accepts the first authoritative report from the same worker", + "a Run-home relay rejection reaches the CLI error boundary" + ] + }, + { + "file": "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", + "assertions": ["a rejected lifecycle verdict is emitted as a JSON ok=false envelope"] + }, + { + "file": "src/cli/handlers/orchestration-migration.test.ts", + "assertions": [ + "first and replayed legacy worker_done settlements are accepted from their authoritative runtime verdict" + ] + }, { "file": "src/cli/handlers/orchestration-check-identity.test.ts", "assertions": [ @@ -7600,6 +8526,20 @@ "a live handle cannot be retargeted by mismatched pane metadata" ] }, + { + "file": "src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts", + "assertions": [ + "a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint", + "older negotiated federation protocols reject before queueing", + "a committed settlement is replayed after an acknowledgment is lost", + "an aborted settlement wait returns operation_unknown instead of accepted success", + "an already-aborted signal registers no settlement waiter", + "a Run-home terminal verdict settles the remote attachment and revokes its capability", + "a terminal verdict cannot settle an unrelated relay item", + "a terminal verdict cannot contradict the exact queued worker report outcome", + "a rejected report replays its exact verdict without mutating durable rejection mail twice" + ] + }, { "file": "src/main/runtime/rpc/methods/orchestration-federation.test.ts", "assertions": ["federated worker placement explicitly sets activate=false"] @@ -7630,9 +8570,27 @@ "sleeping-session, resume-claim, and pending-startup state are cleared after adoption", "no second spawn, resume argv, input, signal, interruption, or duplicate tab occurs after workspace re-entry" ] + }, + { + "file": "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts", + "assertions": [ + "a compiled CLI worker_done with the wrong identity exits nonzero with ok=false", + "the exact Task and Dispatch remain dispatched after rejection", + "the correct worker identity receives an explicit completed lifecycle verdict", + "an independent runtime read observes the Dispatch completed" + ] } ], "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 20, + "summary": "The combined candidate passed one real Electron and compiled-CLI journey: wrong worker identity exited nonzero with ok=false while Dispatch stayed dispatched, the exact worker received an explicit completed verdict, and runtime state independently reached completed." + }, { "date": "2026-08-03", "runner": "local", @@ -7678,6 +8636,24 @@ "durationSeconds": 5.27, "summary": "Five focused files passed with 216 tests, covering visible inactive local worker creation, reveal-failure warnings, stable-pane mailbox routing, live-handle precedence, and SSH fallback parity." }, + { + "date": "2026-08-11", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts src/cli/handlers/orchestration-migration.test.ts", + "result": "passed", + "durationSeconds": 0.4, + "summary": "Three focused files passed 12 deterministic tests covering explicit current and Run-home verdicts, JSON failure output, exact report and terminal-state verification for stripped responses, stale/stopped rejection, idempotent retry, and first/replayed attested legacy settlements." + }, + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts --reporter=dot", + "result": "passed", + "durationSeconds": 4.58, + "summary": "Nine deterministic tests passed for protocol negotiation, Run-home completion and rejection, already-aborted waits, authoritative remote-attachment settlement bound to the exact queued worker_done outcome, and exact verdict replay after lost acknowledgments without mutating durable rejection mail twice." + }, { "date": "2026-07-28", "runner": "local", @@ -7712,11 +8688,11 @@ }, "flakeHistory": { "status": "unknown", - "evidence": "The deterministic units and two isolated Electron journeys pass locally; CI and soak history are not yet available." + "evidence": "The deterministic units and three isolated Electron journeys pass locally; CI and soak history are not yet available." }, "redGreenEvidence": { - "status": "partial", - "evidence": "The byte-identical 5f45c270f1 service oracle is red as the sole overlay 063340a8ba on origin/main@34291f07e9, green on candidate@2748b0b29b, red with current-authority propagation actually disabled in child 08a7db37bf, and green again after revert d2a4e2e024. The focused presentation and stale-handle tests failed against the earlier pre-fix implementation. The restart journey additionally failed first on empty retained output while the original PTY/PID remained live, then passed after the scoped recovered-worker snapshot fallback. The live incident and pre-fix Electron topology showed workspace re-entry replaying provider resume against a worker whose tab binding was missing. Distinct installed A/B and CI artifacts are still needed." + "status": "complete", + "evidence": "The byte-identical compiled-CLI Electron oracle failed on latest main 5ea7df1a5b because a wrong worker identity exited zero with ok=true while Dispatch stayed dispatched, passed on combined candidate d697666ce8 with a nonzero ok=false rejection and explicit completed verdict for the exact worker, and reproduced the main failure when the claimed production files were disabled at merge-base 64aec94cb2. The earlier byte-identical service oracle was also red on main, green on candidate, red with authority propagation disabled, and green after restore. Distinct installed A/B and CI artifacts are still needed." }, "performanceBudget": { "required": true, @@ -7877,24 +8853,42 @@ "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "Deterministic service tests cover release-versus-reuse ordering, transactional retain and takeover cancellation, exact host/pane/process identity, conservative schema-v23 backfill, immutable transcript and bounded terminal archives, mutation restart, reset cleanup, replay idempotency, and 50-resource accounting. Live SSH, WSL, Windows, paired-runtime, and provider-close lost-ack journeys remain explicit gaps.", - "motivatingLinks": ["https://github.com/stablyai/orca/pull/12355", "STA-905"], - "invariant": "A settled Dispatch may close only its one coordinator-created terminal lease. Explicit reuse, real user input, retain, identity or host change, ambiguity, and another resource for the same exact host/pane/process must fence closure. Output preservation and the requested-to-releasing transition are atomic, archives remain readable without the provider file, retries resume idempotently, and orchestration reset removes archive and authority state.", - "oracle": "Record release intent for a settled owner, attempt exact reuse before close, and require worker-start to fail with terminal_release_in_progress while the terminal stays open; then release the original owner exactly once. Race retain and real user input against a controlled archive promise and require no committed archive or close. Change host or process identity and inject duplicate resource evidence to require retention. Freeze a structured transcript, delete its source file, and require archived worker-read to return the same bounded redacted messages. Restart a pending mutation, reset orchestration state, and create 50 resources while asserting replay convergence, zero orphan rows, two-query worker listing, and no unrelated close.", + "coveredProviders": ["local", "ssh"], + "coverageNotes": "Deterministic service tests cover release-versus-reuse ordering, transactional retain and takeover cancellation, exact host/pane/process identity, dead external/user-owned/transferred/stopped/abandoned reconciliation, conservative unknown provider and legacy metadata handling, immutable transcript and bounded terminal archives, mutation restart, reset cleanup, replay idempotency, and 50-resource accounting. A macOS Electron journey invokes the freshly compiled worker-release CLI after the worker process disappears, then independently checks released SQLite state and coordinator liveness. Injected inventories cover local and SSH provider routing; live SSH, WSL, Windows, paired-runtime, and provider-close lost-ack journeys remain explicit gaps.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/pull/12355", + "https://github.com/stablyai/orca/issues/13860", + "STA-905", + "STA-3932" + ], + "invariant": "A settled Dispatch may close only its one coordinator-created terminal lease. Explicit reuse, real user input, retain, identity or host change, ambiguity, and another resource for the same exact host/pane/process must fence closure. Once the authoritative owning provider positively excludes the resource's exact immutable process incarnation, even an external, user-owned, or transferred dead resource must converge to released without any process close. Unknown host scope, missing incarnation metadata, or unavailable inventory must remain retained. Output preservation and the requested-to-releasing transition are atomic, archives remain readable without the provider file, retries resume idempotently, and orchestration reset removes archive and authority state.", + "oracle": "Record release intent for a settled owner, attempt exact reuse before close, and require worker-start to fail with terminal_release_in_progress while the terminal stays open; then release the original owner exactly once. Race retain and real user input against a controlled archive promise and require no committed archive or close. For retained external, user-owned, transferred, stopped, and abandoned resources, run one fresh inventory against the exact local/WSL or SSH provider: an exact live incarnation and every unknown inventory shape stay retained, while positive absence atomically sets ownership_state and release_state to released with processAction none and zero closeTerminal calls. Change host or process identity and inject duplicate resource evidence to require retention. Freeze a structured transcript, delete its source file, and require archived worker-read to return the same bounded redacted messages. Restart a pending mutation, reset orchestration state, and create 50 resources while asserting replay convergence, zero orphan rows, two-query worker listing, and no unrelated close.", "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts src/main/runtime/rpc/methods/orchestration-worker-release.test.ts src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/worker-transcript-read.test.ts src/renderer/src/lib/worker-terminal-takeover-report.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-worker-release.test.ts src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/worker-transcript-read.test.ts src/renderer/src/lib/worker-terminal-takeover-report.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts --reporter=verbose" + "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts --reporter=verbose", + "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ + "src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts", "src/main/runtime/rpc/methods/orchestration-worker-release.test.ts", "src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts", "src/main/runtime/rpc/orchestration-mutation-ledger.test.ts", "src/main/runtime/orchestration/worker-transcript-read.test.ts", "src/renderer/src/lib/worker-terminal-takeover-report.test.ts", - "tests/e2e/completed-worker-retirement-resume.unit.test.ts" + "tests/e2e/completed-worker-retirement-resume.unit.test.ts", + "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts" ], "assertionRefs": [ + { + "file": "src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts", + "assertions": [ + "classifies only an exact incarnation as live on its owning provider", + "keeps missing or malformed identity and unavailable inventory unknown", + "does not inspect an unproven host scope", + "uses the local provider inventory for local and WSL scopes" + ] + }, { "file": "tests/e2e/completed-worker-retirement-resume.unit.test.ts", "assertions": [ @@ -7904,6 +8898,10 @@ { "file": "src/main/runtime/rpc/methods/orchestration-worker-release.test.ts", "assertions": [ + "reconciles a dead external terminal without closing a process", + "reconciles a dead user-taken-over terminal without closing a process", + "reconciles a dead stopped or abandoned worker without closing a process", + "reconciles dead transferred ownership after the current owner settles", "rejects exact reuse after release intent instead of closing the new worker", "lets an explicit retain cancel a release while output capture is pending", "retains when the terminal host scope changed instead of closing", @@ -7923,9 +8921,36 @@ "coalesces overlapping reconciliation passes and closes each resource once", "keeps live terminals bounded across 50 settled workers while controls survive" ] + }, + { + "file": "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts", + "assertions": [ + "compiled worker-release reconciles a dead external retained resource to released", + "the CLI reports processAction none instead of closing a process", + "SQLite independently records released ownership and release state", + "the unrelated coordinator terminal remains live" + ] } ], "evidenceRuns": [ + { + "date": "2026-08-12", + "runner": "local", + "platform": "macos", + "command": "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "durationSeconds": 20, + "summary": "The combined candidate's compiled worker-release returned released with processAction none after positive process absence; an independent SQLite read showed both states released and the coordinator terminal remained live." + }, + { + "date": "2026-08-11", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts src/main/runtime/rpc/methods/orchestration-worker-release.test.ts src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts src/main/runtime/rpc/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/worker-transcript-read.test.ts src/renderer/src/lib/worker-terminal-takeover-report.test.ts --reporter=dot", + "result": "passed", + "durationSeconds": 4.98, + "summary": "Six focused files passed 67 tests on the rebased candidate, covering dead external, user-owned, stopped, abandoned, and transferred reconciliation; exact local/WSL/SSH provider routing; malformed, missing, and unavailable inventory retention; zero process closes; existing lease, archive, recovery, mutation, and renderer-input contracts." + }, { "date": "2026-08-03", "runner": "local", @@ -7937,20 +8962,20 @@ } ], "runtimeBudget": { - "p95Seconds": 8, - "scope": "deterministic runtime, SQLite, transcript, renderer-input, and mutation contracts" + "p95Seconds": 45, + "scope": "deterministic runtime, SQLite, transcript, renderer-input, mutation contracts, and one compiled-CLI Electron journey" }, "flakeHistory": { "status": "unknown", - "evidence": "First local deterministic run only; focused CI and soak history are not yet available." + "evidence": "Repeated local deterministic runs pass; focused CI and soak history are not yet available." }, "redGreenEvidence": { "status": "complete", - "evidence": "The byte-identical 56-test oracle produced 12 deterministic failures and 44 passes with production restored to exact PR head 4aa66b62e3, including ready reuse during release, unsafe migration, stale archives, mutable transcript output, host/identity close gaps, and mutation replay loss. Candidate 457bc4edd1 passed all 56; restoring the same five production files to 4aa66b62e3 reproduced the same red state." + "evidence": "The byte-identical compiled-CLI Electron oracle left the dead resource external/retained on latest main 5ea7df1a5b, passed on combined candidate d697666ce8 with released/released SQLite state and processAction none, and reproduced external/retained after disabling the claimed production files at merge-base 64aec94cb2. The earlier unchanged three-case dead external/user-owned/transferred service oracle likewise failed 3/3 on main, passed 3/3 on candidate, and failed 3/3 with production restored; every run asserted durable state and zero terminal close calls." }, "performanceBudget": { "required": true, - "evidence": "Release performs constant-count indexed resource and identity queries plus one bounded archive capture. Worker-list uses two set queries rather than one resource lookup per worker. Reconciliation remains serial and adds no polling, timers, subprocesses, renderer subscriptions, or provider-wide listing." + "evidence": "Normal owned release performs constant-count indexed resource and identity queries plus one bounded archive capture. A retained release performs exactly one bounded inventory against its authoritative local/WSL or specific SSH provider, with no retry, polling, timer, subprocess, renderer subscription, or per-session follow-up fanout. Worker-list uses two set queries rather than one resource lookup per worker." }, "promotionCriteria": [ "Collect 100 consecutive focused CI passes or 14 days of soak history.", @@ -7961,7 +8986,7 @@ "knownGaps": [ "Provider close has no durable cross-process operation receipt, so a crash after host mutation but before SQLite settlement remains release_pending until exact inventory returns.", "Federated release remains explicitly unsupported and retained.", - "Mobile/direct remote input takeover and live Linux, Windows, WSL, SSH, headed, and headless paired-runtime release are not exercised." + "Mobile/direct remote input takeover and live Linux, Windows, WSL, SSH, headed, and headless paired-runtime release are not exercised; the current fix changes provider inventory classification and SQLite state only, not ConPTY, filesystem, update, sleep, firewall, or window lifecycle semantics." ], "demotionRule": "Keep experimental or demote if release can overlap exact reuse, close a conflicting lease, lose immutable output, retain reset archives, fan out per worker, or any focused ordering test flakes without a product or harness defect." }, diff --git a/config/scripts/build-notification-status-macos.mjs b/config/scripts/build-notification-status-macos.mjs index e8150e32b6f..41d4c84a4af 100644 --- a/config/scripts/build-notification-status-macos.mjs +++ b/config/scripts/build-notification-status-macos.mjs @@ -79,7 +79,7 @@ try { function readArg(name) { const index = args.indexOf(name) - return index >= 0 ? args[index + 1] : undefined + return index !== -1 ? args[index + 1] : undefined } function embeddedInfoPlist(identifier) { diff --git a/config/scripts/build-windows-cli-launcher.mjs b/config/scripts/build-windows-cli-launcher.mjs index 6f9b86bdb4b..27c17b3d15c 100644 --- a/config/scripts/build-windows-cli-launcher.mjs +++ b/config/scripts/build-windows-cli-launcher.mjs @@ -56,5 +56,5 @@ function findFrameworkCompiler(env) { function readArg(name) { const index = process.argv.indexOf(name) - return index >= 0 ? process.argv[index + 1] : undefined + return index !== -1 ? process.argv[index + 1] : undefined } diff --git a/config/scripts/computer-use-modifier-safety.test.mjs b/config/scripts/computer-use-modifier-safety.test.mjs index 725f17fdf4c..2a3234d3d9c 100644 --- a/config/scripts/computer-use-modifier-safety.test.mjs +++ b/config/scripts/computer-use-modifier-safety.test.mjs @@ -11,7 +11,7 @@ function source(path) { function sourceBetween(contents, startMarker, endMarker) { const start = contents.indexOf(startMarker) const end = contents.indexOf(endMarker, start + startMarker.length) - if (start < 0 || end < 0) { + if (start === -1 || end === -1) { throw new Error(`Missing source boundary: ${startMarker} → ${endMarker}`) } return contents.slice(start, end) diff --git a/config/scripts/electron-vite-output-contract.test.ts b/config/scripts/electron-vite-output-contract.test.ts index f59f4a80f88..818b380fc2f 100644 --- a/config/scripts/electron-vite-output-contract.test.ts +++ b/config/scripts/electron-vite-output-contract.test.ts @@ -196,7 +196,8 @@ describe('Electron Vite output contract', () => { }) it('rejects prototype properties as build targets', () => { - expect(targetConfig).toContain('Object.prototype.hasOwnProperty.call(configByTarget, target)') + // Own-property check only: an inherited key like `constructor` must not select a build target. + expect(targetConfig).toContain('Object.hasOwn(configByTarget, target)') }) it('gives the dev terminal daemon helper the TCC identity watched by Orca', () => { diff --git a/config/scripts/ensure-native-runtime.mjs b/config/scripts/ensure-native-runtime.mjs index 98b064cd30d..44261e968a9 100644 --- a/config/scripts/ensure-native-runtime.mjs +++ b/config/scripts/ensure-native-runtime.mjs @@ -45,7 +45,7 @@ function readRuntimeArg() { } const runtimeIndex = process.argv.indexOf('--runtime') - if (runtimeIndex >= 0) { + if (runtimeIndex !== -1) { return process.argv[runtimeIndex + 1] } diff --git a/config/scripts/generate-skill-bundle-manifest.mjs b/config/scripts/generate-skill-bundle-manifest.mjs index 899cb6436df..226ea74c4fb 100644 --- a/config/scripts/generate-skill-bundle-manifest.mjs +++ b/config/scripts/generate-skill-bundle-manifest.mjs @@ -227,7 +227,7 @@ function readGitBlobs(objectShas) { let offset = 0 for (const requestedSha of uniqueShas) { const headerEnd = output.indexOf(10, offset) - if (headerEnd < 0) { + if (headerEnd === -1) { throw new Error(`Missing git cat-file header for ${requestedSha}`) } const header = output.subarray(offset, headerEnd).toString('utf8') @@ -648,8 +648,8 @@ async function main() { const argv = process.argv.slice(2) const rebuildFromTags = argv.includes('--rebuild-from-tags') const releaseIndex = argv.indexOf('--release') - const releaseVersion = releaseIndex >= 0 ? argv[releaseIndex + 1] : null - if (releaseIndex >= 0 && !releaseVersion) { + const releaseVersion = releaseIndex !== -1 ? argv[releaseIndex + 1] : null + if (releaseIndex !== -1 && !releaseVersion) { throw new Error('--release requires a version argument, e.g. --release 1.4.160') } diff --git a/config/scripts/idle-cpu-process-sampling.mjs b/config/scripts/idle-cpu-process-sampling.mjs new file mode 100644 index 00000000000..81f9218e5ad --- /dev/null +++ b/config/scripts/idle-cpu-process-sampling.mjs @@ -0,0 +1,323 @@ +import { execFileSync, spawnSync } from 'node:child_process' + +function parseCpuTimeSeconds(value) { + const trimmed = String(value || '').trim() + if (!trimmed) { + return null + } + const [dayOrTime, maybeTime] = trimmed.includes('-') ? trimmed.split('-', 2) : [null, trimmed] + const days = dayOrTime === null ? 0 : Number(dayOrTime) + const parts = maybeTime.split(':').map(Number) + if (!Number.isFinite(days) || parts.some((part) => !Number.isFinite(part))) { + return null + } + if (parts.length === 3) { + return days * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2] + } + if (parts.length === 2) { + return days * 86400 + parts[0] * 60 + parts[1] + } + if (parts.length === 1) { + return days * 86400 + parts[0] + } + return null +} + +function parseUnixProcesses(stdout) { + const rows = [] + for (const raw of stdout.split('\n')) { + const line = raw.trim() + if (!line) { + continue + } + const match = line.match(/^(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(\S+)\s+(.+)$/) + if (!match) { + continue + } + rows.push({ + pid: Number(match[1]), + ppid: Number(match[2]), + percentCpu: Number(match[3]), + rssBytes: Number(match[4]) * 1024, + cpuTimeSeconds: parseCpuTimeSeconds(match[5]), + command: match[6] + }) + } + return rows +} + +function readUnixProcesses() { + const stdout = execFileSync('ps', ['-axo', 'pid=,ppid=,pcpu=,rss=,cputime=,command='], { + encoding: 'utf8', + env: { ...process.env, LC_ALL: 'C', LANG: 'C' }, + maxBuffer: 20 * 1024 * 1024 + }) + return parseUnixProcesses(stdout) +} + +function readWindowsProcesses() { + const script = + 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,CommandLine | ConvertTo-Json -Compress' + const result = spawnSync('powershell.exe', ['-NoProfile', '-Command', script], { + encoding: 'utf8', + maxBuffer: 20 * 1024 * 1024 + }) + if (result.status !== 0) { + throw new Error(result.stderr || 'PowerShell process enumeration failed') + } + const parsed = JSON.parse(result.stdout || '[]') + const entries = Array.isArray(parsed) ? parsed : [parsed] + return entries.map((entry) => ({ + pid: Number(entry.ProcessId), + ppid: Number(entry.ParentProcessId), + percentCpu: 0, + cpuTimeSeconds: null, + rssBytes: Number(entry.WorkingSetSize) || 0, + command: String(entry.CommandLine || '') + })) +} + +export function readProcessRows() { + return process.platform === 'win32' ? readWindowsProcesses() : readUnixProcesses() +} + +export function descendantsOf(rows, rootPid) { + const children = new Map() + for (const row of rows) { + const list = children.get(row.ppid) ?? [] + list.push(row) + children.set(row.ppid, list) + } + const result = [] + const stack = [rootPid] + const seen = new Set() + while (stack.length > 0) { + const pid = stack.pop() + if (seen.has(pid)) { + continue + } + seen.add(pid) + const row = rows.find((candidate) => candidate.pid === pid) + if (row) { + result.push(row) + } + for (const child of children.get(pid) ?? []) { + stack.push(child.pid) + } + } + return result +} + +export function classify(row, rootPid) { + const command = row.command.toLowerCase() + if (row.pid === rootPid) { + return 'main' + } + if (command.includes('daemon-entry')) { + return 'daemon' + } + if (command.includes('--type=gpu-process')) { + return 'gpu' + } + if (command.includes('--type=renderer')) { + return 'renderer' + } + if (command.includes('--type=utility')) { + return 'utility' + } + if (command.includes('--type=')) { + return 'electron-other' + } + if (command.includes('node') || command.includes('/pi') || command.endsWith(' pi')) { + return 'agent-or-node' + } + return 'other-descendant' +} + +const DEFAULT_WORKLOAD_OVERRUN_LIMIT_MS = 120_000 + +export async function sampleProcessTreeUntilWorkloadsComplete({ + rootPid, + requestedDurationMs, + intervalMs, + workloadPromise, + maxWorkloadOverrunMs = DEFAULT_WORKLOAD_OVERRUN_LIMIT_MS, + readRows = readProcessRows, + now = Date.now, + wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) +}) { + const samplingStartedAt = now() + const requestedDeadline = samplingStartedAt + requestedDurationMs + const hardDeadline = requestedDeadline + maxWorkloadOverrunMs + let workloadSettled = false + let workloadResult + let workloadError + let workloadSettledAt = null + void workloadPromise.then( + (result) => { + workloadResult = result + workloadSettled = true + workloadSettledAt = now() + }, + (error) => { + workloadError = error + workloadSettled = true + workloadSettledAt = now() + } + ) + const samples = [] + let previousSnapshot = null + const needsFinalWorkloadSample = () => + workloadSettledAt !== null && (previousSnapshot?.at ?? -Infinity) < workloadSettledAt + while ( + now() <= requestedDeadline || + samples.length === 0 || + !workloadSettled || + needsFinalWorkloadSample() + ) { + const sampledAt = now() + if (workloadError) { + throw workloadError + } + if ( + (!workloadSettled && sampledAt >= hardDeadline) || + (workloadSettledAt !== null && workloadSettledAt > hardDeadline) + ) { + throw new Error( + `Benchmark workload exceeded the ${maxWorkloadOverrunMs}ms sampling overrun limit` + ) + } + const processRows = descendantsOf(readRows(), rootPid) + const rawProcesses = processRows.map((row) => ({ ...row, kind: classify(row, rootPid) })) + if (previousSnapshot) { + const elapsedSeconds = Math.max(0.001, (sampledAt - previousSnapshot.at) / 1000) + const previousByPid = new Map(previousSnapshot.processes.map((proc) => [proc.pid, proc])) + const processes = rawProcesses.map((row) => { + const previous = previousByPid.get(row.pid) + const canComputeDelta = + typeof row.cpuTimeSeconds === 'number' && typeof previous?.cpuTimeSeconds === 'number' + const cpu = canComputeDelta + ? Math.max(0, ((row.cpuTimeSeconds - previous.cpuTimeSeconds) / elapsedSeconds) * 100) + : row.percentCpu + return { ...row, cpu } + }) + samples.push({ + at: sampledAt, + elapsedMs: sampledAt - previousSnapshot.at, + totalCpuPercent: processes.reduce((sum, proc) => sum + proc.cpu, 0), + totalRssBytes: processes.reduce((sum, proc) => sum + proc.rssBytes, 0), + processes + }) + } + previousSnapshot = { at: sampledAt, processes: rawProcesses } + await wait(intervalMs) + } + if (workloadError) { + throw workloadError + } + const measuredDurationMs = Math.max( + 0, + (previousSnapshot?.at ?? samplingStartedAt) - samplingStartedAt + ) + return { + samples, + workloadResult, + samplingWindow: { + requestedDurationMs, + measuredDurationMs, + maxWorkloadOverrunMs, + extendedForWorkload: workloadSettledAt !== null && workloadSettledAt > requestedDeadline, + workloadSettledElapsedMs: + workloadSettledAt === null ? null : Math.max(0, workloadSettledAt - samplingStartedAt), + workloadSettledBeforeStop: workloadSettled + } + } +} + +function mean(values) { + return values.length === 0 ? 0 : values.reduce((sum, value) => sum + value, 0) / values.length +} + +function percentile(sorted, fraction) { + if (sorted.length === 0) { + return 0 + } + const index = Math.min(sorted.length - 1, Math.ceil(sorted.length * fraction) - 1) + return sorted[index] +} + +export function summarizeSamples(samples) { + const byKind = new Map() + for (const sample of samples) { + for (const proc of sample.processes) { + const bucket = byKind.get(proc.kind) ?? { cpuValues: [], rssValues: [], maxProcessCount: 0 } + bucket.cpuValues.push(proc.cpu) + bucket.rssValues.push(proc.rssBytes) + byKind.set(proc.kind, bucket) + } + const counts = new Map() + for (const proc of sample.processes) { + counts.set(proc.kind, (counts.get(proc.kind) ?? 0) + 1) + } + for (const [kind, count] of counts) { + byKind.get(kind).maxProcessCount = Math.max(byKind.get(kind).maxProcessCount, count) + } + } + const summary = {} + for (const [kind, values] of byKind) { + const cpuSorted = [...values.cpuValues].sort((a, b) => a - b) + const rssSumBySample = samples.map((sample) => + sample.processes + .filter((proc) => proc.kind === kind) + .reduce((sum, proc) => sum + proc.rssBytes, 0) + ) + summary[kind] = { + meanCpuPercent: mean(values.cpuValues), + p95CpuPercent: percentile(cpuSorted, 0.95), + maxCpuPercent: Math.max(0, ...values.cpuValues), + meanRssBytes: mean(rssSumBySample), + maxProcessCount: values.maxProcessCount + } + } + summary.total = { + meanCpuPercent: mean(samples.map((sample) => sample.totalCpuPercent)), + p95CpuPercent: percentile( + samples.map((sample) => sample.totalCpuPercent).sort((a, b) => a - b), + 0.95 + ), + meanRssBytes: mean(samples.map((sample) => sample.totalRssBytes)) + } + return summary +} + +export function summarizeProcessInventory(samples) { + const inventory = {} + for (const sample of samples) { + const counts = new Map() + for (const proc of sample.processes) { + counts.set(proc.kind, (counts.get(proc.kind) ?? 0) + 1) + const entry = inventory[proc.kind] ?? { + maxProcessCount: 0, + maxCpuPercent: 0, + commandSamples: [] + } + entry.maxCpuPercent = Math.max(entry.maxCpuPercent, proc.cpu) + if (!entry.commandSamples.includes(proc.command) && entry.commandSamples.length < 6) { + entry.commandSamples.push(proc.command) + } + inventory[proc.kind] = entry + } + for (const [kind, count] of counts) { + inventory[kind].maxProcessCount = Math.max(inventory[kind].maxProcessCount, count) + } + } + return inventory +} + +export function terminateProcesses(processes) { + for (const proc of processes) { + try { + process.kill(proc.pid) + } catch {} + } +} diff --git a/config/scripts/idle-cpu-process-sampling.test.mjs b/config/scripts/idle-cpu-process-sampling.test.mjs new file mode 100644 index 00000000000..d452c6e3ce0 --- /dev/null +++ b/config/scripts/idle-cpu-process-sampling.test.mjs @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { sampleProcessTreeUntilWorkloadsComplete } from './idle-cpu-process-sampling.mjs' + +function createClock(workloadCompletesAt) { + let currentMs = 0 + let resolveWorkload + const workloadPromise = new Promise((resolve) => { + resolveWorkload = resolve + }) + const wait = async (durationMs) => { + currentMs += durationMs + if (currentMs >= workloadCompletesAt) { + resolveWorkload('complete') + } + await Promise.resolve() + } + const readRows = () => [ + { + pid: 10, + ppid: 0, + percentCpu: 0, + rssBytes: 1_024, + cpuTimeSeconds: currentMs / 2_000, + command: 'electron' + } + ] + return { now: () => currentMs, readRows, wait, workloadPromise } +} + +describe('idle CPU process sampling window', () => { + it('extends through a slow workload and captures a final CPU delta', async () => { + const clock = createClock(40) + const result = await sampleProcessTreeUntilWorkloadsComplete({ + rootPid: 10, + requestedDurationMs: 20, + intervalMs: 10, + maxWorkloadOverrunMs: 100, + ...clock + }) + + expect(result.workloadResult).toBe('complete') + expect(result.samples.map((sample) => sample.at)).toEqual([10, 20, 30, 40]) + expect(result.samplingWindow).toEqual({ + requestedDurationMs: 20, + measuredDurationMs: 40, + maxWorkloadOverrunMs: 100, + extendedForWorkload: true, + workloadSettledElapsedMs: 40, + workloadSettledBeforeStop: true + }) + }) + + it('invalidates a run that reaches the workload overrun guard', async () => { + const clock = createClock(Infinity) + await expect( + sampleProcessTreeUntilWorkloadsComplete({ + rootPid: 10, + requestedDurationMs: 20, + intervalMs: 10, + maxWorkloadOverrunMs: 20, + ...clock + }) + ).rejects.toThrow('exceeded the 20ms sampling overrun limit') + }) +}) diff --git a/config/scripts/idle-cpu-renderer-scale-fixture.mjs b/config/scripts/idle-cpu-renderer-scale-fixture.mjs new file mode 100644 index 00000000000..4759b768e27 --- /dev/null +++ b/config/scripts/idle-cpu-renderer-scale-fixture.mjs @@ -0,0 +1,202 @@ +export async function configureRendererScaleFixture(page, options, repoPath) { + return page.evaluate( + ({ agentsPerWorktree, lineageDepth, repoPath }) => { + const store = window.__store + if (!store) { + throw new Error('window.__store is not available') + } + const normalizePath = (value) => + String(value ?? '') + .replaceAll('\\', '/') + .toLowerCase() + const primaryPath = normalizePath(repoPath) + const compare = (left, right) => (left < right ? -1 : left > right ? 1 : 0) + const state = store.getState() + const worktrees = Object.values(state.worktreesByRepo) + .flat() + .filter((worktree) => !worktree.isArchived) + .sort((left, right) => { + const primaryOrder = + Number(normalizePath(right.path) === primaryPath) - + Number(normalizePath(left.path) === primaryPath) + return ( + primaryOrder || + compare(normalizePath(left.path), normalizePath(right.path)) || + compare(left.id, right.id) + ) + }) + const appliedLineageDepth = Math.min(lineageDepth, Math.max(0, worktrees.length - 1)) + if (lineageDepth === 0 && agentsPerWorktree === 0) { + return { + applied: false, + requestedLineageDepth: lineageDepth, + appliedLineageDepth, + agentsPerWorktree, + seededAgentRows: 0 + } + } + + state.setActiveView('terminal') + state.setSidebarOpen(true) + state.setGroupBy('none') + state.setSortBy('recent') + state.setShowActiveOnly(false) + state.setShowSleepingWorkspaces(true) + state.setHideDefaultBranchWorkspace(false) + state.setFilterRepoIds([]) + + const lineageById = { ...store.getState().worktreeLineageById } + const lineageParentIds = new Set() + if (appliedLineageDepth > 0) { + for (const worktree of worktrees) { + delete lineageById[worktree.id] + if (!worktree.instanceId) { + throw new Error(`Worktree ${worktree.id} has no instanceId for lineage seeding`) + } + } + for (let index = 1; index < worktrees.length; index += 1) { + const child = worktrees[index] + const parent = worktrees[Math.min(index - 1, appliedLineageDepth - 1)] + lineageParentIds.add(parent.id) + lineageById[child.id] = { + worktreeId: child.id, + worktreeInstanceId: child.instanceId, + parentWorktreeId: parent.id, + parentWorktreeInstanceId: parent.instanceId, + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1_700_000_000_000 + index + } + } + } + const collapsedGroups = new Set(store.getState().collapsedGroups) + for (const parentId of lineageParentIds) { + collapsedGroups.delete(`lineage:${parentId}`) + } + store.setState({ worktreeLineageById: lineageById, collapsedGroups }) + + let seededAgentRows = 0 + if (agentsPerWorktree > 0) { + store.getState().setWorktreeCardMode('Default') + store.getState().setAgentActivityDisplayMode('full') + const fixtureNow = Date.now() + worktrees.forEach((worktree, worktreeIndex) => { + const next = store.getState() + const tab = + next.tabsByWorktree[worktree.id]?.[0] ?? + next.createTab(worktree.id, undefined, undefined, { + activate: false, + id: `idle-cpu-tab-${worktreeIndex}` + }) + for (let agentIndex = 0; agentIndex < agentsPerWorktree; agentIndex += 1) { + const agentType = agentIndex % 2 === 0 ? 'codex' : 'claude' + const leafSequence = + BigInt(worktreeIndex) * BigInt(agentsPerWorktree) + BigInt(agentIndex + 1) + const leafId = `00000000-0000-4000-8000-${leafSequence.toString(16).padStart(12, '0')}` + store.getState().setAgentStatus( + `${tab.id}:${leafId}`, + { + state: 'working', + prompt: `Idle CPU agent ${worktreeIndex + 1}.${agentIndex + 1}`, + agentType + }, + agentType, + { updatedAt: fixtureNow, stateStartedAt: fixtureNow }, + { tabId: tab.id, worktreeId: worktree.id } + ) + seededAgentRows += 1 + } + }) + } + return { + applied: true, + requestedLineageDepth: lineageDepth, + appliedLineageDepth, + lineageEdges: appliedLineageDepth > 0 ? Math.max(0, worktrees.length - 1) : 0, + expandedLineageGroups: lineageParentIds.size, + agentsPerWorktree, + seededAgentRows, + orderedWorktreeIds: worktrees.map((worktree) => worktree.id) + } + }, + { agentsPerWorktree: options.agentsPerWorktree, lineageDepth: options.lineageDepth, repoPath } + ) +} + +export async function collectRendererCensus(page, configuredLineageDepth) { + return page.evaluate((configuredDepth) => { + const state = window.__store?.getState() + if (!state) { + throw new Error('window.__store is not available') + } + const worktrees = Object.values(state.worktreesByRepo).flat() + const worktreeIds = new Set(worktrees.map((worktree) => worktree.id)) + const lineageDepthById = new Map() + const getDepth = (worktreeId, trail = new Set()) => { + if (lineageDepthById.has(worktreeId)) { + return lineageDepthById.get(worktreeId) + } + const lineage = state.worktreeLineageById[worktreeId] + if (!lineage || !worktreeIds.has(lineage.parentWorktreeId) || trail.has(worktreeId)) { + return 0 + } + const nextTrail = new Set(trail) + nextTrail.add(worktreeId) + const depth = 1 + getDepth(lineage.parentWorktreeId, nextTrail) + lineageDepthById.set(worktreeId, depth) + return depth + } + const logicalDepths = worktrees.map((worktree) => getDepth(worktree.id)) + const lineageParentIds = new Set( + Object.values(state.worktreeLineageById) + .filter((lineage) => worktreeIds.has(lineage.worktreeId)) + .map((lineage) => lineage.parentWorktreeId) + ) + const sidebar = document.querySelector('[data-worktree-sidebar]') + const mountedWorktreeIds = [ + ...new Set( + [...(sidebar?.querySelectorAll('[data-worktree-id]') ?? [])] + .map((element) => element.getAttribute('data-worktree-id')) + .filter(Boolean) + ) + ] + const mountedAgentRows = [...(sidebar?.querySelectorAll('*') ?? [])].filter( + (element) => + element.classList.contains('group/agent-row') || + element.classList.contains('compact-agent-row') + ).length + let diagnosticCensus = null + try { + diagnosticCensus = window.__orcaTypingDiagnostic?.report().census ?? null + } catch {} + const collapsedLineageGroups = [...lineageParentIds].filter((parentId) => + state.collapsedGroups.has(`lineage:${parentId}`) + ).length + return { + capturedAt: new Date().toISOString(), + worktrees: { + store: worktrees.length, + mountedCards: sidebar?.querySelectorAll('[data-worktree-card-surface]').length ?? 0, + mountedUnique: mountedWorktreeIds.length, + mountedIds: mountedWorktreeIds.slice(0, 100), + mountedIdsTruncated: Math.max(0, mountedWorktreeIds.length - 100) + }, + agentRows: { + storeLive: Object.keys(state.agentStatusByPaneKey ?? {}).length, + storeRetained: Object.keys(state.retainedAgentsByPaneKey ?? {}).length, + mounted: mountedAgentRows, + diagnosticMounted: diagnosticCensus?.agentRows.mountedDom ?? null + }, + storeListeners: diagnosticCensus?.storeListeners ?? null, + lineage: { + configuredDepth, + measuredMaxDepth: Math.max(0, ...logicalDepths), + edges: logicalDepths.filter((depth) => depth > 0).length, + groups: lineageParentIds.size, + expandedGroups: lineageParentIds.size - collapsedLineageGroups, + collapsedGroups: collapsedLineageGroups + }, + diagnostic: diagnosticCensus + } + }, configuredLineageDepth) +} diff --git a/config/scripts/idle-cpu-renderer-timing-probe.mjs b/config/scripts/idle-cpu-renderer-timing-probe.mjs new file mode 100644 index 00000000000..b010bcb3433 --- /dev/null +++ b/config/scripts/idle-cpu-renderer-timing-probe.mjs @@ -0,0 +1,191 @@ +const RENDERER_TIMER_INTERVAL_MS = 100 + +export async function startRendererTimingProbe(page) { + await page.evaluate((timerIntervalMs) => { + const maxSamples = 5_000 + const maxEntries = 80 + let phaseStartedAt = performance.now() + let phaseStartedAtIso = new Date().toISOString() + let timerId = null + let driftCount = 0 + let driftSamples = [] + let longTaskEntries = [] + let observer = null + let longTaskSupported = false + + const round = (value) => Math.round(value * 100) / 100 + const summarize = (values, totalCount = values.length) => { + const sorted = [...values].sort((left, right) => left - right) + const percentile = (fraction) => + sorted.length === 0 + ? null + : sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * fraction) - 1)] + return { + count: totalCount, + retainedCount: sorted.length, + mean: + sorted.length === 0 + ? null + : round(sorted.reduce((sum, value) => sum + value, 0) / sorted.length), + p50: sorted.length === 0 ? null : round(percentile(0.5)), + p95: sorted.length === 0 ? null : round(percentile(0.95)), + max: sorted.length === 0 ? null : round(sorted.at(-1)) + } + } + const recordLongTasks = (entries) => { + for (const entry of entries) { + longTaskEntries.push({ + startTime: entry.startTime, + duration: entry.duration, + name: entry.name + }) + if (longTaskEntries.length > maxSamples) { + longTaskEntries.shift() + } + } + } + try { + longTaskSupported = PerformanceObserver.supportedEntryTypes?.includes('longtask') === true + if (longTaskSupported) { + observer = new PerformanceObserver((list) => recordLongTasks(list.getEntries())) + observer.observe({ type: 'longtask', buffered: true }) + } + } catch { + observer = null + longTaskSupported = false + } + const scheduleTimer = () => { + const expectedAt = performance.now() + timerIntervalMs + timerId = setTimeout(() => { + driftCount += 1 + driftSamples.push(Math.max(0, performance.now() - expectedAt)) + if (driftSamples.length > maxSamples) { + driftSamples.shift() + } + scheduleTimer() + }, timerIntervalMs) + } + const snapshot = (reset) => { + if (observer) { + recordLongTasks(observer.takeRecords()) + } + const capturedAt = performance.now() + const phaseLongTasks = longTaskEntries.filter((entry) => entry.startTime >= phaseStartedAt) + const durations = phaseLongTasks.map((entry) => entry.duration) + const result = { + startedAt: phaseStartedAtIso, + capturedAt: new Date().toISOString(), + durationMs: round(capturedAt - phaseStartedAt), + timerIntervalMs, + timerDriftMs: summarize(driftSamples, driftCount), + longTasks: { + supported: longTaskSupported, + ...summarize(durations), + totalDurationMs: round(durations.reduce((sum, value) => sum + value, 0)), + entries: phaseLongTasks.slice(-maxEntries).map((entry) => ({ + startMs: round(entry.startTime - phaseStartedAt), + durationMs: round(entry.duration), + name: entry.name + })), + entriesTruncated: Math.max(0, phaseLongTasks.length - maxEntries) + } + } + if (reset) { + phaseStartedAt = capturedAt + phaseStartedAtIso = new Date().toISOString() + driftCount = 0 + driftSamples = [] + longTaskEntries = [] + } + return result + } + scheduleTimer() + window.__orcaIdleCpuTimingProbe = { + snapshot: () => snapshot(true), + stop: () => { + if (timerId !== null) { + clearTimeout(timerId) + } + const result = snapshot(false) + observer?.disconnect() + return result + } + } + }, RENDERER_TIMER_INTERVAL_MS) +} + +export async function snapshotRendererTimingProbe(page) { + return page.evaluate(() => window.__orcaIdleCpuTimingProbe?.snapshot() ?? null) +} + +export async function stopRendererTimingProbe(page) { + return page.evaluate(() => window.__orcaIdleCpuTimingProbe?.stop() ?? null) +} + +export async function runZustandPublications(page, count, intervalMs) { + return page.evaluate( + ({ count, intervalMs }) => + new Promise((resolve, reject) => { + const store = window.__store + if (!store) { + reject(new Error('window.__store is not available')) + return + } + const maxSamples = 5_000 + const startedAt = performance.now() + const startedAtIso = new Date().toISOString() + const schedulingDriftMs = [] + let completed = 0 + const finish = () => { + const sorted = [...schedulingDriftMs].sort((left, right) => left - right) + const percentile = (fraction) => + sorted.length === 0 + ? null + : sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * fraction) - 1)] + const round = (value) => Math.round(value * 100) / 100 + resolve({ + requested: count, + completed, + intervalMs, + startedAt: startedAtIso, + completedAt: new Date().toISOString(), + durationMs: round(performance.now() - startedAt), + schedulingDriftMs: { + retainedCount: sorted.length, + p50: sorted.length === 0 ? null : round(percentile(0.5)), + p95: sorted.length === 0 ? null : round(percentile(0.95)), + max: sorted.length === 0 ? null : round(sorted.at(-1)) + } + }) + } + const publish = () => { + const publishedAt = performance.now() + const scheduledAt = startedAt + completed * intervalMs + schedulingDriftMs.push(Math.max(0, publishedAt - scheduledAt)) + if (schedulingDriftMs.length > maxSamples) { + schedulingDriftMs.shift() + } + try { + // Why: an empty partial notifies every subscriber without changing domain state. + store.setState({}) + } catch (error) { + reject(error) + return + } + completed += 1 + if (completed >= count) { + finish() + return + } + const nextAt = startedAt + completed * intervalMs + setTimeout(publish, Math.max(0, nextAt - performance.now())) + } + if (count === 0) { + finish() + } else { + setTimeout(publish, 0) + } + }), + { count, intervalMs } + ) +} diff --git a/config/scripts/install-electron-package-binary.mjs b/config/scripts/install-electron-package-binary.mjs index f75d1eae30a..314cd31710f 100644 --- a/config/scripts/install-electron-package-binary.mjs +++ b/config/scripts/install-electron-package-binary.mjs @@ -28,6 +28,8 @@ const transientDownloadErrorCodes = new Set([ 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', + // GitHub release CDN can refuse HTTP/2 streams under load; retry like socket resets. + 'ERR_HTTP2_STREAM_ERROR', 'ENETDOWN', 'ENETRESET', 'ENETUNREACH', @@ -185,7 +187,9 @@ async function downloadElectronArtifactWithRetry(downloadOptions) { function getDownloadRetryDelays() { const configured = process.env.ORCA_ELECTRON_PACKAGE_RETRY_DELAYS_MS if (!configured) { - return [1_000, 3_000] + // Why: GitHub release CDN returns intermittent 503 / HTTP2 stream refusals + // under CI fan-out; a few short attempts still exhaust during outages. + return [1_000, 3_000, 5_000, 10_000] } const delays = configured.split(',').map(Number) @@ -200,7 +204,7 @@ function isTransientDownloadError(error) { if (transientDownloadErrorCodes.has(candidate?.code)) { return true } - const statusCode = candidate?.statusCode ?? candidate?.response?.statusCode + const statusCode = getDownloadErrorStatusCode(candidate) if ( statusCode === 408 || statusCode === 425 || @@ -213,6 +217,13 @@ function isTransientDownloadError(error) { return false } +function getDownloadErrorStatusCode(error) { + // @electron/get FetchDownloader uses Fetch Response.status; older got uses statusCode. + return ( + error?.statusCode ?? error?.status ?? error?.response?.statusCode ?? error?.response?.status + ) +} + function getErrorChain(error) { const errors = [] let candidate = error @@ -225,7 +236,7 @@ function getErrorChain(error) { function formatDownloadError(error) { for (const candidate of getErrorChain(error)) { - const statusCode = candidate?.statusCode ?? candidate?.response?.statusCode + const statusCode = getDownloadErrorStatusCode(candidate) if (statusCode) { return `HTTP ${statusCode}` } diff --git a/config/scripts/install-electron-package-binary.test.mjs b/config/scripts/install-electron-package-binary.test.mjs index 2c37f95cfbe..ad04336e8e7 100644 --- a/config/scripts/install-electron-package-binary.test.mjs +++ b/config/scripts/install-electron-package-binary.test.mjs @@ -118,6 +118,58 @@ describe('install-electron-package-binary', () => { } }) + it('retries HTTP/2 stream refusal Electron download failures', () => { + const projectDir = mkTempProject() + + try { + writeFakeElectronPackage(projectDir) + writeFakeElectronGet(projectDir, { + downloadFailures: 1, + downloadErrorCode: 'ERR_HTTP2_STREAM_ERROR' + }) + writeFakeExtractor(projectDir, { createExecutable: true }) + + const result = runInstallScript(projectDir, { + ORCA_ELECTRON_PACKAGE_RETRY_DELAYS_MS: '0,0' + }) + + expect(result.status, result.stderr).toBe(0) + expect( + readFileSync(join(projectDir, 'electron-get.log'), 'utf8').trim().split('\n') + ).toHaveLength(2) + expect(result.stderr).toContain( + 'Transient Electron download failure (ERR_HTTP2_STREAM_ERROR)' + ) + } finally { + rmSync(projectDir, { recursive: true, force: true }) + } + }) + + it('retries Electron download HTTP 503 failures from Fetch Response.status', () => { + const projectDir = mkTempProject() + + try { + writeFakeElectronPackage(projectDir) + writeFakeElectronGet(projectDir, { + downloadFailures: 1, + downloadHttpStatus: 503 + }) + writeFakeExtractor(projectDir, { createExecutable: true }) + + const result = runInstallScript(projectDir, { + ORCA_ELECTRON_PACKAGE_RETRY_DELAYS_MS: '0,0' + }) + + expect(result.status, result.stderr).toBe(0) + expect( + readFileSync(join(projectDir, 'electron-get.log'), 'utf8').trim().split('\n') + ).toHaveLength(2) + expect(result.stderr).toContain('Transient Electron download failure (HTTP 503)') + } finally { + rmSync(projectDir, { recursive: true, force: true }) + } + }) + it('fails after exhausting transient Electron download retries', () => { const projectDir = mkTempProject() @@ -279,7 +331,12 @@ module.exports = path.join(__dirname, 'dist', fs.readFileSync(pathFile, 'utf8')) function writeFakeElectronGet( projectDir, - { downloadNeverSettles = false, downloadFailures = 0, downloadErrorCode = 'ECONNRESET' } = {} + { + downloadNeverSettles = false, + downloadFailures = 0, + downloadErrorCode = 'ECONNRESET', + downloadHttpStatus = null + } = {} ) { const getDir = join(projectDir, 'node_modules', 'electron', 'node_modules', '@electron', 'get') mkdirSync(getDir, { recursive: true }) @@ -299,6 +356,11 @@ exports.downloadArtifact = async function downloadArtifact(details) { return new Promise(() => {}) } if (downloadAttempt <= ${JSON.stringify(downloadFailures)}) { + if (${JSON.stringify(downloadHttpStatus)} != null) { + const error = new Error('Response code ' + ${JSON.stringify(downloadHttpStatus)}) + error.response = { status: ${JSON.stringify(downloadHttpStatus)} } + throw error + } const cause = Object.assign(new Error('download failed'), { code: ${JSON.stringify(downloadErrorCode)} }) diff --git a/config/scripts/legacy-worker-recovery-persistence-benchmark.mjs b/config/scripts/legacy-worker-recovery-persistence-benchmark.mjs index 5f4160600cc..76555d4e78e 100644 --- a/config/scripts/legacy-worker-recovery-persistence-benchmark.mjs +++ b/config/scripts/legacy-worker-recovery-persistence-benchmark.mjs @@ -30,8 +30,8 @@ const recoveryEnd = runtimeSource.indexOf( ) const recoverySource = runtimeSource.slice(recoveryStart, recoveryEnd) if ( - recoveryStart < 0 || - recoveryEnd < 0 || + recoveryStart === -1 || + recoveryEnd === -1 || !recoverySource.includes('await this.flushWorkspaceSessionOrThrowAsync()') || recoverySource.includes('flushOrThrow()') ) { diff --git a/config/scripts/locale-ko-key-overrides.json b/config/scripts/locale-ko-key-overrides.json index bd0c3c15aee..aacf053926e 100644 --- a/config/scripts/locale-ko-key-overrides.json +++ b/config/scripts/locale-ko-key-overrides.json @@ -2273,12 +2273,6 @@ "auto.components.settings.GitPane.976afc6b3e": { "ko": "워크스페이스를 만들면 Orca가 원격 기준 브랜치를 새로고침하고, 일치하는 로컬 브랜치를 안전하게 fast-forward합니다. 예:" }, - "auto.components.settings.GitPane.b5f534717a": { - "ko": "공동 작성" - }, - "auto.components.settings.GitPane.b9b5771bb1": { - "ko": "표기" - }, "auto.components.settings.GitPane.b9c011fbc2": { "ko": "속도 제한" }, @@ -2288,9 +2282,6 @@ "auto.components.settings.GitPane.db3a127eb1": { "ko": "이렇게 하면 다음과 같은 명령이 유지됩니다" }, - "auto.components.settings.GitPane.e02ea23a32": { - "ko": "Orca 표기" - }, "auto.components.settings.GitPane.f35007e6e8": { "ko": "git-username" }, diff --git a/config/scripts/locale-ko-value-overrides.mjs b/config/scripts/locale-ko-value-overrides.mjs index 19db7c753ec..5dac8b29a0d 100644 --- a/config/scripts/locale-ko-value-overrides.mjs +++ b/config/scripts/locale-ko-value-overrides.mjs @@ -44,7 +44,6 @@ export const KO_VALUE_OVERRIDES = { 'Issue #{{value0}}': '이슈 #{{value0}}', 'Linked issue #{{value0}}': '연결된 이슈 #{{value0}}', 'Issue # or GitHub URL': '이슈 # 또는 GitHub URL', - 'Add Orca attribution to commits, PRs, and issues.': '커밋, PR 및 이슈에 Orca 속성을 추가합니다.', 'Paste an issue URL, or enter a number. Leave blank to remove the link.': '이슈 URL을 붙여넣거나 숫자를 입력하세요. 링크를 제거하려면 비워두세요.', 'Connect Linear in Settings to search issues.': '이슈를 검색하려면 설정에서 Linear를 연결하세요.', @@ -157,8 +156,7 @@ export const KO_VALUE_OVERRIDES = { '저장되지 않은 Git AI Author 변경사항이 있습니다. 떠나면 폐기됩니다.', 'Discard unsaved Git AI Author changes?': '저장되지 않은 Git AI Author 변경사항을 삭제하시겠습니까?', - 'Branch naming, base refs, attribution, and Git AI Author.': - '브랜치 이름 지정, 기본 참조, 속성 및 Git AI Author.', + 'Branch naming, base refs, and Git AI Author.': '브랜치 이름 지정, 기본 참조 및 Git AI Author.', 'Used by repositories that inherit global hosted-review defaults.': '전역 호스팅 PR 기본값을 상속하는 저장소에서 사용됩니다.', 'Defaults used when the hosted-review composer opens.': diff --git a/config/scripts/locale-search-keyword-overrides.mjs b/config/scripts/locale-search-keyword-overrides.mjs index 2a9d6266f5d..352199c1f7e 100644 --- a/config/scripts/locale-search-keyword-overrides.mjs +++ b/config/scripts/locale-search-keyword-overrides.mjs @@ -164,7 +164,6 @@ export const SEARCH_KEYWORD_OVERRIDES = { gitlab: 'GitLab', gitea: 'Gitea', oauth: 'OAuth', - attribution: '归因', skill: '技能', skills: '技能', phone: '手机', diff --git a/config/scripts/locale-translation-policy.es-pr.test.mjs b/config/scripts/locale-translation-policy.es-pr.test.mjs index a3c046ce895..389f914c86b 100644 --- a/config/scripts/locale-translation-policy.es-pr.test.mjs +++ b/config/scripts/locale-translation-policy.es-pr.test.mjs @@ -25,10 +25,10 @@ describe('locale-translation-policy es PR glossary', () => { it('rewrites PR inside longer sentences', () => { expect( repairEs( - 'Add Orca attribution to commits, PRs, and issues.', - 'Agregue la atribución de Orca a commits, relaciones públicas y problemas.' + 'Split a large change into smaller PRs', + 'Dividir un cambio grande en relaciones públicas más pequeños' ) - ).toBe('Agregue la atribución de Orca a commits, PR y problemas.') + ).toBe('Dividir un cambio grande en PR más pequeños') expect( repairEs( 'Open the PR details to view current reviewers.', diff --git a/config/scripts/locale-translation-policy.zh-round5.test.mjs b/config/scripts/locale-translation-policy.zh-round5.test.mjs index 28901fba8d4..622b3c5c31c 100644 --- a/config/scripts/locale-translation-policy.zh-round5.test.mjs +++ b/config/scripts/locale-translation-policy.zh-round5.test.mjs @@ -44,22 +44,14 @@ describe('locale-translation-policy zh round 5', () => { locale: 'zh' }) ).toBe('显示 Orca Mobile 按钮') - expect( - repairTranslatedValue({ - key: 'auto.components.settings.GitPane.e02ea23a32', - enValue: 'Orca Attribution', - localeValue: 'Orca归属', - locale: 'zh' - }) - ).toBe('Orca 归因') expect( repairTranslatedValue({ key: 'auto.hooks.useSettingsNavigationMetadata.ab4b21b58e', - enValue: 'Branch naming, base refs, attribution, and Git AI Author.', - localeValue: '分支命名、基本引用、归属和 Git AI 作者。', + enValue: 'Branch naming, base refs, and Git AI Author.', + localeValue: '分支命名、基本引用和 Git AI 作者。', locale: 'zh' }) - ).toBe('分支命名、基础引用、归因和 Git AI Author。') + ).toBe('分支命名、基础引用和 Git AI Author。') expect( repairTranslatedValue({ key: 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.1b18868569', diff --git a/config/scripts/locale-zh-phrase-fixes-round5.mjs b/config/scripts/locale-zh-phrase-fixes-round5.mjs index 1aa117395e8..23fcc6d32a5 100644 --- a/config/scripts/locale-zh-phrase-fixes-round5.mjs +++ b/config/scripts/locale-zh-phrase-fixes-round5.mjs @@ -3,7 +3,6 @@ export const ZH_PHRASE_FIXES_ROUND5 = [ { pattern: /Orca集成开发环境/g, replacement: 'Orca IDE', whenEnIncludes: 'Orca IDE' }, { pattern: /Orca第一/g, replacement: 'Orca 优先', whenEnIncludes: 'Orca first' }, { pattern: /Orca移动/g, replacement: 'Orca Mobile', whenEnIncludes: 'Orca Mobile' }, - { pattern: /Orca归属/g, replacement: 'Orca 归因', whenEnIncludes: 'Orca Attribution' }, { pattern: /Orca标志/g, replacement: 'Orca 标志', whenEnIncludes: 'Orca logo' }, { pattern: /喜欢Orca/g, replacement: '喜欢 Orca', whenEnIncludes: 'Enjoying Orca' }, { pattern: /认识Orca/g, replacement: '了解 Orca', whenEnIncludes: 'Get to know Orca' }, diff --git a/config/scripts/locale-zh-value-overrides.mjs b/config/scripts/locale-zh-value-overrides.mjs index 087091a3f3e..b53fb1d2248 100644 --- a/config/scripts/locale-zh-value-overrides.mjs +++ b/config/scripts/locale-zh-value-overrides.mjs @@ -144,7 +144,6 @@ export const ZH_VALUE_OVERRIDES = { 'Expand Orca': '展开 Orca', 'Support Orca': '支持 Orca', 'Restarting Orca…': '正在重启 Orca…', - 'Orca Attribution': 'Orca 归因', 'Show Orca Mobile Button': '显示 Orca Mobile 按钮', 'Codex Accounts': 'Codex 账户', 'Codex Account': 'Codex 账户', @@ -186,8 +185,7 @@ export const ZH_VALUE_OVERRIDES = { "Give agents direct access to Orca's browser so they can test pages, capture screenshots, and act on what they see.": '让代理直接访问 Orca 的浏览器,以便测试页面、捕获屏幕截图并根据所见内容执行操作。', 'X finishes, send it the review task.”': 'X 完成后,把评审任务发给它。”', - 'Branch naming, base refs, attribution, and Git AI Author.': - '分支命名、基础引用、归因和 Git AI Author。', + 'Branch naming, base refs, and Git AI Author.': '分支命名、基础引用和 Git AI Author。', 'You have unsaved Git AI Author changes. Leaving will discard them.': '您有未保存的 Git AI Author 更改。离开将丢弃它们。', 'Discard unsaved Git AI Author changes?': '放弃未保存的 Git AI Author 更改?', diff --git a/config/scripts/macos-computer-helper-owner-loss-benchmark.mjs b/config/scripts/macos-computer-helper-owner-loss-benchmark.mjs index 8724cf8faf4..b6f1d9571a5 100644 --- a/config/scripts/macos-computer-helper-owner-loss-benchmark.mjs +++ b/config/scripts/macos-computer-helper-owner-loss-benchmark.mjs @@ -210,7 +210,7 @@ function connectInvalidPeer(socketPath) { const onData = (chunk) => { buffer += chunk const newline = buffer.indexOf('\n') - if (newline < 0) { + if (newline === -1) { return } let response diff --git a/config/scripts/mjpeg-frame-parser-alloc-benchmark.mjs b/config/scripts/mjpeg-frame-parser-alloc-benchmark.mjs index 86791745c10..5e350bb24f8 100644 --- a/config/scripts/mjpeg-frame-parser-alloc-benchmark.mjs +++ b/config/scripts/mjpeg-frame-parser-alloc-benchmark.mjs @@ -54,7 +54,7 @@ function extractOld(pending, chunk, maxPendingBytes = 2 * 1024 * 1024) { const frames = [] while (cursor.length > 0) { const frameStart = cursor.indexOf(JPEG_START) - if (frameStart < 0) { + if (frameStart === -1) { const keepLastByte = cursor.at(-1) === 0xff return { frames, pending: keepLastByte ? Buffer.from([0xff]) : Buffer.alloc(0) } } @@ -62,7 +62,7 @@ function extractOld(pending, chunk, maxPendingBytes = 2 * 1024 * 1024) { cursor = cursor.subarray(frameStart) } const frameEnd = cursor.indexOf(JPEG_END, JPEG_START.length) - if (frameEnd < 0) { + if (frameEnd === -1) { const tail = cursor.length <= maxPendingBytes ? cursor : cursor.subarray(-maxPendingBytes) return { frames, pending: trackedCopy(tail) } } @@ -79,7 +79,7 @@ function extractNew(pending, chunk, maxPendingBytes = 2 * 1024 * 1024) { const frames = [] while (cursor.length > 0) { const frameStart = cursor.indexOf(JPEG_START) - if (frameStart < 0) { + if (frameStart === -1) { const keepLastByte = cursor.at(-1) === 0xff return { frames, pending: keepLastByte ? Buffer.from([0xff]) : Buffer.alloc(0) } } @@ -87,7 +87,7 @@ function extractNew(pending, chunk, maxPendingBytes = 2 * 1024 * 1024) { cursor = cursor.subarray(frameStart) } const frameEnd = cursor.indexOf(JPEG_END, JPEG_START.length) - if (frameEnd < 0) { + if (frameEnd === -1) { const tail = cursor.length <= maxPendingBytes ? cursor : cursor.subarray(-maxPendingBytes) return { frames, pending: trackedCopy(tail) } } diff --git a/config/scripts/orchestration-skill-guidance.test.mjs b/config/scripts/orchestration-skill-guidance.test.mjs index 080cb4fa785..b9a88ae12ad 100644 --- a/config/scripts/orchestration-skill-guidance.test.mjs +++ b/config/scripts/orchestration-skill-guidance.test.mjs @@ -281,7 +281,7 @@ describe('orchestration skill guidance', () => { expect(workerLoop).toContain('opaque provider model id with `--model`') expect(workerLoop).toContain('`--effort` requires `--model`') expect(workerLoop).toContain('neither option can combine with `--terminal`') - expect(workerLoop).toContain('--agent claude --model aws-bedrock-opus-5 --effort high --json') + expect(workerLoop).toContain('--agent claude --model opus --effort high --json') expect(workerLoop).toContain('`launch.requested` and `launch.effective`') }) diff --git a/config/scripts/package-electron-runtime-contract.test.mjs b/config/scripts/package-electron-runtime-contract.test.mjs index 1b695086808..c6e96c88b2c 100644 --- a/config/scripts/package-electron-runtime-contract.test.mjs +++ b/config/scripts/package-electron-runtime-contract.test.mjs @@ -80,6 +80,7 @@ describe('Electron runtime package contract', () => { 'build:linux', 'test:e2e', 'test:e2e:terminal-rendering-golden', + 'test:e2e:posix-profile-index-golden', 'test:e2e:terminal-rendering-release-evidence', 'test:e2e:headful' ] @@ -492,7 +493,7 @@ describe('Electron runtime package contract', () => { expect(uploadStep.with.path).toBe('${{ env.ORCA_E2E_TERMINAL_PERF_REPORT_PATH }}') }) - it('keeps terminal rendering regressions in the manual golden E2E workflow', () => { + it('keeps platform golden regressions in the manual and release workflows', () => { const packageScripts = packageJson.scripts const goldenWorkflow = parse( readFileSync(join(projectDir, '.github/workflows/golden-e2e-experiment.yml'), 'utf8') @@ -506,17 +507,19 @@ describe('Electron runtime package contract', () => { ['mac', 'macOS'], ['windows', 'Windows'] ]) - const goldenPlatforms = goldenWorkflow.jobs['golden-e2e'].strategy.matrix.include - .map(({ platform }) => platform) - .sort() - const goldenRunSteps = goldenPlatforms.map((platform) => { - const label = goldenPlatformLabels.get(platform) + const goldenMatrix = goldenWorkflow.jobs['golden-e2e'].strategy.matrix.include + const goldenPlatforms = goldenMatrix.map(({ platform }) => platform).sort() + const goldenRunSteps = new Map( + goldenPlatforms.map((platform) => { + const label = goldenPlatformLabels.get(platform) - expect(label, platform).toBeDefined() + expect(label, platform).toBeDefined() - return steps.find((step) => step.name === `Run golden E2E tests on ${label}`) - }) + return [platform, steps.find((step) => step.name === `Run golden E2E tests on ${label}`)] + }) + ) const releaseGoldenJob = releaseWorkflow.jobs['terminal-rendering-golden'] + const releaseGoldenMatrix = releaseGoldenJob.strategy.matrix.include const releaseEvidenceJob = releaseWorkflow.jobs['terminal-rendering-release-evidence'] const releaseBuildNeeds = releaseWorkflow.jobs.build.needs const publishReleaseNeeds = releaseWorkflow.jobs['publish-release'].needs @@ -535,15 +538,47 @@ describe('Electron runtime package contract', () => { expect(packageScripts['test:e2e:terminal-rendering-golden']).not.toContain( 'terminal-long-table-scroll-restore.spec.ts' ) + expect(packageScripts['test:e2e:windows-fresh-startup-golden']).toContain( + 'golden-windows-fresh-startup.spec.ts' + ) + expect(packageScripts['test:e2e:windows-fresh-startup-golden']).toContain( + '@windows-fresh-startup-golden' + ) + expect(packageScripts['test:e2e:posix-profile-index-golden']).toContain( + 'golden-posix-profile-index-fsync.spec.ts' + ) + expect(packageScripts['test:e2e:posix-profile-index-golden']).toContain( + 'golden-posix-fresh-startup.spec.ts' + ) + expect(packageScripts['test:e2e:posix-profile-index-golden']).toContain( + '@posix-profile-index-golden' + ) expect(packageScripts['test:e2e:terminal-rendering-release-evidence']).toContain( 'terminal-opencode-emoji-table-rendering.spec.ts' ) expect(packageScripts['test:e2e:terminal-rendering-release-evidence']).toContain( 'terminal-long-table-scroll-restore.spec.ts' ) - for (const runStep of goldenRunSteps) { - expect(runStep?.run).toContain('pnpm run test:e2e:terminal-rendering-golden') - } + expect(goldenMatrix).toEqual([ + { os: 'ubuntu-latest', platform: 'linux' }, + { os: 'macos-15', platform: 'mac' }, + { os: 'windows-2022', platform: 'windows' } + ]) + expect(goldenRunSteps.get('linux')?.run).toContain( + 'pnpm run test:e2e:terminal-rendering-golden' + ) + expect(goldenRunSteps.get('linux')?.run).toContain( + 'pnpm run test:e2e:posix-profile-index-golden' + ) + expect(goldenRunSteps.get('mac')?.run).toContain('pnpm run test:e2e:terminal-rendering-golden') + expect(goldenRunSteps.get('mac')?.run).toContain('pnpm run test:e2e:posix-profile-index-golden') + expect(goldenRunSteps.get('windows')).toMatchObject({ + if: "runner.os == 'Windows'", + shell: 'pwsh' + }) + expect(goldenRunSteps.get('windows').run).toContain( + 'pnpm run test:e2e:windows-fresh-startup-golden' + ) expect(goldenWorkflow.on.pull_request).toBeUndefined() expect(goldenWorkflow.on.workflow_dispatch).toBeDefined() expect(releaseBuildNeeds).not.toContain('terminal-rendering-golden') @@ -552,12 +587,25 @@ describe('Electron runtime package contract', () => { expect(publishReleaseNeeds).toContain('build') expect(publishReleaseNeeds).not.toContain('terminal-rendering-release-evidence') expect(releaseGoldenJob['continue-on-error']).toBeUndefined() - expect(releaseGoldenJob.strategy.matrix.include.map(({ platform }) => platform).sort()).toEqual( - goldenPlatforms + expect(releaseGoldenMatrix).toEqual(goldenMatrix) + const releaseLinuxRunStep = releaseGoldenJob.steps.find( + (step) => step.name === 'Run terminal rendering golden on Linux' ) - expect(releaseGoldenJob.steps.map((step) => step.run ?? '')).toContain( - 'xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden' + expect(releaseLinuxRunStep.run).toContain('pnpm run test:e2e:terminal-rendering-golden') + expect(releaseLinuxRunStep.run).toContain('pnpm run test:e2e:posix-profile-index-golden') + const releaseMacRunStep = releaseGoldenJob.steps.find( + (step) => step.name === 'Run terminal rendering golden on macOS' ) + expect(releaseMacRunStep.run).toContain('pnpm run test:e2e:terminal-rendering-golden') + expect(releaseMacRunStep.run).toContain('pnpm run test:e2e:posix-profile-index-golden') + const releaseWindowsRunStep = releaseGoldenJob.steps.find( + (step) => step.name === 'Run fresh-startup golden on Windows' + ) + expect(releaseWindowsRunStep).toMatchObject({ + if: "runner.os == 'Windows'", + shell: 'pwsh' + }) + expect(releaseWindowsRunStep.run).toContain('pnpm run test:e2e:windows-fresh-startup-golden') expect(releaseEvidenceJob['continue-on-error']).toBe(true) expect( releaseEvidenceJob.strategy.matrix.include.map(({ platform }) => platform).sort() diff --git a/config/scripts/pr-e2e-gate-contract.test.mjs b/config/scripts/pr-e2e-gate-contract.test.mjs index 860e70c892b..d44039a2ca8 100644 --- a/config/scripts/pr-e2e-gate-contract.test.mjs +++ b/config/scripts/pr-e2e-gate-contract.test.mjs @@ -6,6 +6,10 @@ import { parse } from 'yaml' const projectDir = resolve(import.meta.dirname, '../..') const prWorkflow = parse(readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8')) const e2eWorkflow = parse(readFileSync(join(projectDir, '.github/workflows/e2e.yml'), 'utf8')) +const sshDockerRunner = readFileSync( + join(projectDir, 'config/scripts/run-ssh-docker-terminal-parking-e2e.mjs'), + 'utf8' +) const filterStep = prWorkflow.jobs['e2e-paths'].steps.find( (step) => step.name === 'Filter changed E2E specs' @@ -64,14 +68,36 @@ describe('PR E2E gate contract', () => { expect(e2eWorkflow.jobs.e2e.if).toBe("inputs.test_files == ''") expect(e2eWorkflow.jobs['changed-e2e'].if).toBe("inputs.test_files != ''") expect(e2eWorkflow.jobs['changed-e2e'].strategy).toBeUndefined() - expect(e2eWorkflow.jobs['ssh-docker-watcher-isolation'].if).toBe("inputs.test_files == ''") const changedRun = e2eWorkflow.jobs['changed-e2e'].steps.find( (step) => step.name === 'Run changed E2E specs' ) expect(changedRun.env.TEST_FILES_JSON).toBe('${{ inputs.test_files }}') + expect(changedRun.run).toContain('. != "tests/e2e/ssh-startup-exec-readiness.spec.ts"') + expect(changedRun.run).toContain('. != "tests/e2e/paired-startup-exec-readiness.spec.ts"') + expect(changedRun.run).toContain('if [ "${#TEST_FILES[@]}" -eq 0 ]') expect(changedRun.run).toContain('pnpm run test:e2e "${TEST_FILES[@]}" --workers=1') }) + it('keeps startup-exec live parity in the isolated SSH lane', () => { + const sshLaneCondition = e2eWorkflow.jobs['ssh-docker-watcher-isolation'].if + expect(sshLaneCondition).toContain("inputs.test_files == ''") + expect(sshLaneCondition).toContain('tests/e2e/ssh-startup-exec-readiness.spec.ts') + expect(sshLaneCondition).toContain('tests/e2e/paired-startup-exec-readiness.spec.ts') + expect(sshDockerRunner).toContain('tests/e2e/ssh-startup-exec-readiness.spec.ts') + expect(sshDockerRunner).toContain('tests/e2e/paired-startup-exec-readiness.spec.ts') + expect(sshDockerRunner).toContain("'electron-headless'") + expect(sshDockerRunner).toContain("'electron-headful'") + }) + + it('installs zsh in every Linux lane that can run paired startup readiness', () => { + for (const jobName of ['e2e', 'changed-e2e', 'ssh-docker-watcher-isolation']) { + const installStep = e2eWorkflow.jobs[jobName].steps.find((step) => + step.name.startsWith('Install native build') + ) + expect(installStep.run, jobName).toMatch(/\bzsh\b/) + } + }) + it('keeps dedicated E2E workflows out of pull request CI', () => { const dedicatedWorkflows = [ 'golden-e2e-experiment.yml', diff --git a/config/scripts/pr-workflow-parallelism.test.mjs b/config/scripts/pr-workflow-parallelism.test.mjs index 5b3b66dea3f..165931dbeb1 100644 --- a/config/scripts/pr-workflow-parallelism.test.mjs +++ b/config/scripts/pr-workflow-parallelism.test.mjs @@ -8,6 +8,7 @@ const dependencyAction = parse( ) const packageJson = JSON.parse(readFileSync('package.json', 'utf8')) const shellContractFiles = [ + 'src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts', 'src/main/daemon/shell-ready.test.ts', 'src/main/providers/local-pty-shell-ready.test.ts', 'src/main/providers/__tests__/shell-ready-framework-example.test.ts', @@ -75,6 +76,7 @@ describe('PR workflow parallelism', () => { expect(shellStep).toBeDefined() expect(shellInstall).toBeDefined() + expect(shellStep.run.split(/\s+/)).toContain('--maxWorkers=1') // Why the whole workflow, not just the general shards: any other lane installing // these shells would silently start running the real-shell tests twice. expect(jobsInstallingPackages).toEqual(['shell_contracts']) diff --git a/config/scripts/relay-watcher-fault-harness.mjs b/config/scripts/relay-watcher-fault-harness.mjs index b27a1f945d9..784abfc4850 100644 --- a/config/scripts/relay-watcher-fault-harness.mjs +++ b/config/scripts/relay-watcher-fault-harness.mjs @@ -94,7 +94,7 @@ function waitForStdoutSentinel(proc, protocol, stderr) { stdoutBuffer = Buffer.concat([stdoutBuffer, chunk]) const sentinel = Buffer.from(protocol.RELAY_SENTINEL) const index = stdoutBuffer.indexOf(sentinel) - if (index < 0) { + if (index === -1) { return } settled = true @@ -148,7 +148,7 @@ function createRelayClient(entryPath, args, env, protocol) { stdoutBuffer = Buffer.concat([stdoutBuffer, chunk]) const sentinel = Buffer.from(protocol.RELAY_SENTINEL) const index = stdoutBuffer.indexOf(sentinel) - if (index < 0) { + if (index === -1) { return } ready = true diff --git a/config/scripts/remote-shared-control-retirement-probe.ts b/config/scripts/remote-shared-control-retirement-probe.ts index 63abd01e376..30edeb9802a 100644 --- a/config/scripts/remote-shared-control-retirement-probe.ts +++ b/config/scripts/remote-shared-control-retirement-probe.ts @@ -5,7 +5,8 @@ import { resolveEnvironment, resolveEnvironmentPairingOffer } from '../../src/shared/runtime-environment-store' -import type { MemorySnapshot, RuntimeStatus } from '../../src/shared/types' +import type { MemorySnapshot } from '../../src/shared/types' +import type { RuntimeStatus } from '../../src/shared/runtime-types' async function main(): Promise { const environmentName = process.env.ORCA_PROBE_ENVIRONMENT_NAME diff --git a/config/scripts/run-idle-cpu-benchmark.mjs b/config/scripts/run-idle-cpu-benchmark.mjs index 53cabd3380b..3892de8845d 100644 --- a/config/scripts/run-idle-cpu-benchmark.mjs +++ b/config/scripts/run-idle-cpu-benchmark.mjs @@ -1,15 +1,34 @@ #!/usr/bin/env node import { _electron as electron } from '@stablyai/playwright-test' -import { execFileSync, spawnSync } from 'node:child_process' +import { execFileSync } from 'node:child_process' import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' +import { + descendantsOf, + readProcessRows, + sampleProcessTreeUntilWorkloadsComplete, + summarizeProcessInventory, + summarizeSamples, + terminateProcesses +} from './idle-cpu-process-sampling.mjs' +import { + collectRendererCensus, + configureRendererScaleFixture +} from './idle-cpu-renderer-scale-fixture.mjs' +import { + runZustandPublications, + snapshotRendererTimingProbe, + startRendererTimingProbe, + stopRendererTimingProbe +} from './idle-cpu-renderer-timing-probe.mjs' import { installSyntheticVisibleSpinners } from './idle-cpu-synthetic-spinners.mjs' const DEFAULT_WARMUP_MS = 15_000 const DEFAULT_SAMPLE_MS = 30_000 const DEFAULT_INTERVAL_MS = 1_000 const DEFAULT_WORKTREE_COUNT = 1 +const DEFAULT_ZUSTAND_PUBLICATION_INTERVAL_MS = 100 const ONBOARDING_FINAL_STEP = 3 const ONBOARDING_FLOW_VERSION = 2 @@ -19,6 +38,10 @@ function parseArgs(argv) { sampleMs: DEFAULT_SAMPLE_MS, intervalMs: DEFAULT_INTERVAL_MS, worktrees: DEFAULT_WORKTREE_COUNT, + lineageDepth: 0, + agentsPerWorktree: 0, + zustandPublications: 0, + zustandPublicationIntervalMs: DEFAULT_ZUSTAND_PUBLICATION_INTERVAL_MS, skipBuild: false, headful: false, output: null, @@ -47,6 +70,14 @@ function parseArgs(argv) { options.intervalMs = Number(readValue()) } else if (arg === '--worktrees') { options.worktrees = Number(readValue()) + } else if (arg === '--lineage-depth') { + options.lineageDepth = Number(readValue()) + } else if (arg === '--agents-per-worktree') { + options.agentsPerWorktree = Number(readValue()) + } else if (arg === '--zustand-publications') { + options.zustandPublications = Number(readValue()) + } else if (arg === '--zustand-publication-interval-ms') { + options.zustandPublicationIntervalMs = Number(readValue()) } else if (arg === '--output') { options.output = readValue() } else if (arg === '--skip-build') { @@ -73,6 +104,10 @@ function parseArgs(argv) { 'sampleMs', 'intervalMs', 'worktrees', + 'lineageDepth', + 'agentsPerWorktree', + 'zustandPublications', + 'zustandPublicationIntervalMs', 'syntheticVisibleSpinners', 'syntheticSpinnerSteps' ]) { @@ -82,16 +117,33 @@ function parseArgs(argv) { } options.worktrees = Math.max(1, Math.floor(options.worktrees)) options.intervalMs = Math.max(250, Math.floor(options.intervalMs)) + options.lineageDepth = Math.floor(options.lineageDepth) + options.agentsPerWorktree = Math.floor(options.agentsPerWorktree) + options.zustandPublications = Math.floor(options.zustandPublications) + options.zustandPublicationIntervalMs = Math.max( + 1, + Math.floor(options.zustandPublicationIntervalMs) + ) options.syntheticVisibleSpinners = Math.max(0, Math.floor(options.syntheticVisibleSpinners)) options.syntheticSpinnerSteps = Math.max(1, Math.floor(options.syntheticSpinnerSteps)) if (!['smooth', 'steps'].includes(options.syntheticSpinnerAnimation)) { throw new Error(`Invalid --synthetic-spinner-animation: ${options.syntheticSpinnerAnimation}`) } + if (options.lineageDepth > 0 && options.worktrees < 2) { + throw new Error('--lineage-depth requires at least two --worktrees') + } + const publicationSpanMs = + Math.max(0, options.zustandPublications - 1) * options.zustandPublicationIntervalMs + if (publicationSpanMs > options.sampleMs) { + throw new Error( + `Zustand publication span ${publicationSpanMs}ms exceeds --sample-ms ${options.sampleMs}` + ) + } return options } function printUsage() { console.log( - `Usage: node config/scripts/run-idle-cpu-benchmark.mjs [options]\n\nOptions:\n --warmup-ms Time to wait after app readiness before sampling (default ${DEFAULT_WARMUP_MS})\n --sample-ms Sampling window duration (default ${DEFAULT_SAMPLE_MS})\n --interval-ms Sampling cadence (default ${DEFAULT_INTERVAL_MS})\n --worktrees Seed repo worktree count, including primary (default ${DEFAULT_WORKTREE_COUNT})\n --headful Show the Electron window while measuring\n --skip-build Reuse out/main/index.js instead of building first\n --output Write JSON report to this path\n --disable-renderer-animations Inject measurement-only CSS that disables animations/transitions\n --synthetic-visible-spinners Measurement-only: add visible working spinners\n --synthetic-spinner-animation Spinner animation style (default smooth)\n --synthetic-spinner-steps Step count for --synthetic-spinner-animation steps (default 12)\n` + `Usage: node config/scripts/run-idle-cpu-benchmark.mjs [options]\n\nOptions:\n --warmup-ms Time to wait after app readiness before sampling (default ${DEFAULT_WARMUP_MS})\n --sample-ms Sampling window duration (default ${DEFAULT_SAMPLE_MS})\n --interval-ms Sampling cadence (default ${DEFAULT_INTERVAL_MS})\n --worktrees Seed repo worktree count, including primary (default ${DEFAULT_WORKTREE_COUNT})\n --lineage-depth Nest all worktrees under one expanded lineage, up to this depth\n --agents-per-worktree Seed this many visible inline agent rows per worktree\n --zustand-publications Publish exactly this many store updates during sampling\n --zustand-publication-interval-ms Publication cadence (default ${DEFAULT_ZUSTAND_PUBLICATION_INTERVAL_MS})\n --headful Show the Electron window while measuring\n --skip-build Reuse out/main/index.js instead of building first\n --output Write JSON report to this path\n --disable-renderer-animations Inject measurement-only CSS that disables animations/transitions\n --synthetic-visible-spinners Measurement-only: add visible working spinners\n --synthetic-spinner-animation Spinner animation style (default smooth)\n --synthetic-spinner-steps Step count for --synthetic-spinner-animation steps (default 12)\n` ) } function run(command, args, options = {}) { @@ -188,140 +240,6 @@ function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) } -function parseCpuTimeSeconds(value) { - const trimmed = String(value || '').trim() - if (!trimmed) { - return null - } - const [dayOrTime, maybeTime] = trimmed.includes('-') ? trimmed.split('-', 2) : [null, trimmed] - const days = dayOrTime === null ? 0 : Number(dayOrTime) - const parts = maybeTime.split(':').map(Number) - if (!Number.isFinite(days) || parts.some((part) => !Number.isFinite(part))) { - return null - } - if (parts.length === 3) { - return days * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2] - } - if (parts.length === 2) { - return days * 86400 + parts[0] * 60 + parts[1] - } - if (parts.length === 1) { - return days * 86400 + parts[0] - } - return null -} - -function parseUnixProcesses(stdout) { - const rows = [] - for (const raw of stdout.split('\n')) { - const line = raw.trim() - if (!line) { - continue - } - const match = line.match(/^(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(\S+)\s+(.+)$/) - if (!match) { - continue - } - rows.push({ - pid: Number(match[1]), - ppid: Number(match[2]), - percentCpu: Number(match[3]), - rssBytes: Number(match[4]) * 1024, - cpuTimeSeconds: parseCpuTimeSeconds(match[5]), - command: match[6] - }) - } - return rows -} - -function readUnixProcesses() { - const stdout = execFileSync('ps', ['-axo', 'pid=,ppid=,pcpu=,rss=,cputime=,command='], { - encoding: 'utf8', - env: { ...process.env, LC_ALL: 'C', LANG: 'C' }, - maxBuffer: 20 * 1024 * 1024 - }) - return parseUnixProcesses(stdout) -} - -function readWindowsProcesses() { - const script = - 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,CommandLine | ConvertTo-Json -Compress' - const result = spawnSync('powershell.exe', ['-NoProfile', '-Command', script], { - encoding: 'utf8', - maxBuffer: 20 * 1024 * 1024 - }) - if (result.status !== 0) { - throw new Error(result.stderr || 'PowerShell process enumeration failed') - } - const parsed = JSON.parse(result.stdout || '[]') - const entries = Array.isArray(parsed) ? parsed : [parsed] - return entries.map((entry) => ({ - pid: Number(entry.ProcessId), - ppid: Number(entry.ParentProcessId), - percentCpu: 0, - cpuTimeSeconds: null, - rssBytes: Number(entry.WorkingSetSize) || 0, - command: String(entry.CommandLine || '') - })) -} - -function readProcessRows() { - return process.platform === 'win32' ? readWindowsProcesses() : readUnixProcesses() -} - -function descendantsOf(rows, rootPid) { - const children = new Map() - for (const row of rows) { - const list = children.get(row.ppid) ?? [] - list.push(row) - children.set(row.ppid, list) - } - const result = [] - const stack = [rootPid] - const seen = new Set() - while (stack.length > 0) { - const pid = stack.pop() - if (seen.has(pid)) { - continue - } - seen.add(pid) - const row = rows.find((candidate) => candidate.pid === pid) - if (row) { - result.push(row) - } - for (const child of children.get(pid) ?? []) { - stack.push(child.pid) - } - } - return result -} - -function classify(row, rootPid) { - const command = row.command.toLowerCase() - if (row.pid === rootPid) { - return 'main' - } - if (command.includes('daemon-entry')) { - return 'daemon' - } - if (command.includes('--type=gpu-process')) { - return 'gpu' - } - if (command.includes('--type=renderer')) { - return 'renderer' - } - if (command.includes('--type=utility')) { - return 'utility' - } - if (command.includes('--type=')) { - return 'electron-other' - } - if (command.includes('node') || command.includes('/pi') || command.endsWith(' pi')) { - return 'agent-or-node' - } - return 'other-descendant' -} - async function collectRendererIdleState(page) { return page.evaluate(() => { const describeElement = (element) => { @@ -364,93 +282,6 @@ async function collectRendererIdleState(page) { }) } -function summarizeSamples(samples) { - const byKind = new Map() - for (const sample of samples) { - for (const proc of sample.processes) { - const bucket = byKind.get(proc.kind) ?? { cpuValues: [], rssValues: [], maxProcessCount: 0 } - bucket.cpuValues.push(proc.cpu) - bucket.rssValues.push(proc.rssBytes) - byKind.set(proc.kind, bucket) - } - const counts = new Map() - for (const proc of sample.processes) { - counts.set(proc.kind, (counts.get(proc.kind) ?? 0) + 1) - } - for (const [kind, count] of counts) { - byKind.get(kind).maxProcessCount = Math.max(byKind.get(kind).maxProcessCount, count) - } - } - const summary = {} - for (const [kind, values] of byKind) { - const cpuSorted = [...values.cpuValues].sort((a, b) => a - b) - const rssSumBySample = samples.map((sample) => - sample.processes - .filter((proc) => proc.kind === kind) - .reduce((sum, proc) => sum + proc.rssBytes, 0) - ) - summary[kind] = { - meanCpuPercent: mean(values.cpuValues), - p95CpuPercent: percentile(cpuSorted, 0.95), - maxCpuPercent: Math.max(0, ...values.cpuValues), - meanRssBytes: mean(rssSumBySample), - maxProcessCount: values.maxProcessCount - } - } - summary.total = { - meanCpuPercent: mean(samples.map((sample) => sample.totalCpuPercent)), - p95CpuPercent: percentile( - samples.map((sample) => sample.totalCpuPercent).sort((a, b) => a - b), - 0.95 - ), - meanRssBytes: mean(samples.map((sample) => sample.totalRssBytes)) - } - return summary -} - -function summarizeProcessInventory(samples) { - const inventory = {} - for (const sample of samples) { - const counts = new Map() - for (const proc of sample.processes) { - counts.set(proc.kind, (counts.get(proc.kind) ?? 0) + 1) - const entry = inventory[proc.kind] ?? { - maxProcessCount: 0, - maxCpuPercent: 0, - commandSamples: [] - } - entry.maxCpuPercent = Math.max(entry.maxCpuPercent, proc.cpu) - if (!entry.commandSamples.includes(proc.command) && entry.commandSamples.length < 6) { - entry.commandSamples.push(proc.command) - } - inventory[proc.kind] = entry - } - for (const [kind, count] of counts) { - inventory[kind].maxProcessCount = Math.max(inventory[kind].maxProcessCount, count) - } - } - return inventory -} -function mean(values) { - return values.length === 0 ? 0 : values.reduce((sum, value) => sum + value, 0) / values.length -} - -function percentile(sorted, fraction) { - if (sorted.length === 0) { - return 0 - } - const index = Math.min(sorted.length - 1, Math.ceil(sorted.length * fraction) - 1) - return sorted[index] -} - -function terminateProcesses(processes) { - for (const proc of processes) { - try { - process.kill(proc.pid) - } catch {} - } -} - async function main() { const options = parseArgs(process.argv.slice(2)) const root = path.resolve(import.meta.dirname, '..', '..') @@ -491,6 +322,11 @@ async function main() { const page = await app.firstWindow({ timeout: 120_000 }) await page.waitForLoadState('domcontentloaded') await page.waitForFunction(() => Boolean(window.__store), null, { timeout: 30_000 }) + await page.waitForFunction( + () => window.__store?.getState().workspaceSessionReady === true, + null, + { timeout: 60_000 } + ) const measurementCss = [] if (options.disableRendererAnimations) { measurementCss.push( @@ -506,63 +342,111 @@ async function main() { options.syntheticSpinnerAnimation, options.syntheticSpinnerSteps ) - await page.evaluate(async (repoPath) => { - await window.api.repos.add({ path: repoPath }) + const fixtureState = await page.evaluate(async (repoPath) => { + const added = await window.api.repos.add({ path: repoPath }) + if ('error' in added) { + return { error: added.error } + } const store = window.__store await store?.getState().fetchRepos() - const repo = store?.getState().repos.find((candidate) => candidate.path === repoPath) + const repo = store?.getState().repos.find((candidate) => candidate.id === added.repo.id) if (repo) { - await store.getState().updateRepo(repo.id, { externalWorktreeVisibility: 'show' }) - await store.getState().fetchWorktrees(repo.id) + const detected = await store + .getState() + .fetchWorktrees(repo.id, { requireAuthoritative: true }) + const importedWorktreePaths = ( + store.getState().detectedWorktreesByRepo[repo.id]?.worktrees ?? [] + ) + .filter((worktree) => !worktree.selectedCheckout) + .map((worktree) => worktree.path) + const updated = await store.getState().updateRepo(repo.id, { + externalWorktreeVisibility: 'show', + importedExternalWorktreePaths: importedWorktreePaths, + externalWorktreeInboxBaselinePaths: importedWorktreePaths + }) + const refreshed = await store + .getState() + .fetchWorktrees(repo.id, { requireAuthoritative: true }) + return { + detected, + updated, + refreshed, + detectedCount: store.getState().detectedWorktreesByRepo[repo.id]?.worktrees.length ?? 0, + importedCount: importedWorktreePaths.length, + visibleCount: store.getState().worktreesByRepo[repo.id]?.length ?? 0 + } } + return { error: 'repo-not-found' } }, repoDir) + console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`) await page.waitForFunction( - () => window.__store?.getState().workspaceSessionReady === true, + (expectedWorktrees) => { + const state = window.__store?.getState() + return ( + state?.workspaceSessionReady === true && + Object.values(state.worktreesByRepo).flat().length === expectedWorktrees + ) + }, + options.worktrees, + { timeout: 180_000 } + ) + const scaleFixtureState = await configureRendererScaleFixture(page, options, repoDir) + if (scaleFixtureState.applied) { + console.log(`[idle-cpu] scale fixture ${JSON.stringify(scaleFixtureState)}`) + } + await page.waitForFunction( + (expectedAgentRows) => { + const state = window.__store?.getState() + return ( + state !== undefined && + Object.keys(state.agentStatusByPaneKey ?? {}).length >= expectedAgentRows + ) + }, + scaleFixtureState.seededAgentRows, + { timeout: 30_000 } + ) + await page.waitForFunction( + () => Boolean(document.querySelector('[data-worktree-sidebar] [data-worktree-id]')), null, - { timeout: 60_000 } + { timeout: 30_000 } ) console.log( - `[idle-cpu] root pid=${rootPid}; warmup=${options.warmupMs}ms sample=${options.sampleMs}ms interval=${options.intervalMs}ms worktrees=${options.worktrees}` + `[idle-cpu] root pid=${rootPid}; warmup=${options.warmupMs}ms sample=${options.sampleMs}ms interval=${options.intervalMs}ms worktrees=${options.worktrees} lineage-depth=${options.lineageDepth} agents/worktree=${options.agentsPerWorktree} publications=${options.zustandPublications}` ) + await startRendererTimingProbe(page) await sleep(options.warmupMs) const rendererIdleState = await collectRendererIdleState(page) - const deadline = Date.now() + options.sampleMs - const samples = [] - let previousSnapshot = null - while (Date.now() <= deadline || samples.length === 0) { - const sampledAt = Date.now() - const processRows = descendantsOf(readProcessRows(), rootPid) - const rawProcesses = processRows.map((row) => ({ ...row, kind: classify(row, rootPid) })) - if (previousSnapshot) { - const elapsedSeconds = Math.max(0.001, (sampledAt - previousSnapshot.at) / 1000) - const previousByPid = new Map(previousSnapshot.processes.map((proc) => [proc.pid, proc])) - const processes = rawProcesses.map((row) => { - const previous = previousByPid.get(row.pid) - const canComputeDelta = - typeof row.cpuTimeSeconds === 'number' && typeof previous?.cpuTimeSeconds === 'number' - const cpu = canComputeDelta - ? Math.max(0, ((row.cpuTimeSeconds - previous.cpuTimeSeconds) / elapsedSeconds) * 100) - : row.percentCpu - return { ...row, cpu } - }) - samples.push({ - at: sampledAt, - elapsedMs: sampledAt - previousSnapshot.at, - totalCpuPercent: processes.reduce((sum, proc) => sum + proc.cpu, 0), - totalRssBytes: processes.reduce((sum, proc) => sum + proc.rssBytes, 0), - processes - }) - } - previousSnapshot = { at: sampledAt, processes: rawProcesses } - await sleep(options.intervalMs) - } + const rendererCensusBefore = await collectRendererCensus(page, options.lineageDepth) + const rendererTimingBefore = await snapshotRendererTimingProbe(page) + const publicationPromise = runZustandPublications( + page, + options.zustandPublications, + options.zustandPublicationIntervalMs + ) + const sampled = await sampleProcessTreeUntilWorkloadsComplete({ + rootPid, + requestedDurationMs: options.sampleMs, + intervalMs: options.intervalMs, + workloadPromise: publicationPromise + }) + const samples = sampled.samples + const zustandPublications = sampled.workloadResult + const rendererTimingAfter = await stopRendererTimingProbe(page) + const rendererCensusAfter = await collectRendererCensus(page, options.lineageDepth) const report = { benchmark: 'orca-idle-cpu', createdAt: new Date().toISOString(), options, rootPid, platform: { platform: process.platform, arch: process.arch, cpus: os.cpus().length }, + fixtureState, + scaleFixtureState, rendererIdleState, + rendererCensusBefore, + rendererCensusAfter, + rendererTiming: { before: rendererTimingBefore, after: rendererTimingAfter }, + zustandPublications, + samplingWindow: sampled.samplingWindow, sampleCount: samples.length, summary: summarizeSamples(samples), processInventory: summarizeProcessInventory(samples), @@ -578,7 +462,13 @@ async function main() { { summary: report.summary, processInventory: report.processInventory, - sampleCount: report.sampleCount + sampleCount: report.sampleCount, + scaleFixtureState: report.scaleFixtureState, + rendererCensusBefore: report.rendererCensusBefore, + rendererCensusAfter: report.rendererCensusAfter, + rendererTiming: report.rendererTiming, + zustandPublications: report.zustandPublications, + samplingWindow: report.samplingWindow }, null, 2 diff --git a/config/scripts/run-ssh-docker-maxsessions-identity-e2e.mjs b/config/scripts/run-ssh-docker-maxsessions-identity-e2e.mjs new file mode 100644 index 00000000000..2f232420531 --- /dev/null +++ b/config/scripts/run-ssh-docker-maxsessions-identity-e2e.mjs @@ -0,0 +1,41 @@ +import { spawnSync } from 'node:child_process' + +const rawExtraArgs = process.argv.slice(2) +const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArgs +const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm' +const env = { + ...process.env, + ORCA_E2E_SSH_DOCKER: '1' +} + +// Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows. +const spawnOptions = { + stdio: 'inherit', + env, + shell: process.platform === 'win32' +} + +const runtime = spawnSync(pnpm, ['run', 'ensure:electron-runtime'], spawnOptions) + +if (runtime.status !== 0) { + process.exit(runtime.status ?? 1) +} + +const result = spawnSync( + pnpm, + [ + 'exec', + 'playwright', + 'test', + 'tests/e2e/ssh-maxsessions-remote-pid-binding-identity.spec.ts', + '--config', + 'tests/playwright.config.ts', + '--project', + 'electron-headless', + '--workers=1', + ...extraArgs + ], + spawnOptions +) + +process.exit(result.status ?? 1) diff --git a/config/scripts/run-ssh-docker-reconnect-pane-cardinality-e2e.mjs b/config/scripts/run-ssh-docker-reconnect-pane-cardinality-e2e.mjs new file mode 100644 index 00000000000..cde82379c1f --- /dev/null +++ b/config/scripts/run-ssh-docker-reconnect-pane-cardinality-e2e.mjs @@ -0,0 +1,41 @@ +import { spawnSync } from 'node:child_process' + +const rawExtraArgs = process.argv.slice(2) +const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArgs +const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm' +const env = { + ...process.env, + ORCA_E2E_SSH_DOCKER: '1' +} + +// Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows. +const spawnOptions = { + stdio: 'inherit', + env, + shell: process.platform === 'win32' +} + +const runtime = spawnSync(pnpm, ['run', 'ensure:electron-runtime'], spawnOptions) + +if (runtime.status !== 0) { + process.exit(runtime.status ?? 1) +} + +const result = spawnSync( + pnpm, + [ + 'exec', + 'playwright', + 'test', + 'tests/e2e/ssh-reconnect-pane-cardinality.spec.ts', + '--config', + 'tests/playwright.config.ts', + '--project', + 'electron-headless', + '--workers=1', + ...extraArgs + ], + spawnOptions +) + +process.exit(result.status ?? 1) diff --git a/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs b/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs index 8d4183b4515..b894ac15217 100644 --- a/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs +++ b/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs @@ -5,7 +5,8 @@ const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArg const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm' const env = { ...process.env, - ORCA_E2E_SSH_DOCKER: '1' + ORCA_E2E_SSH_DOCKER: '1', + ORCA_E2E_WEB_CLIENT: '1' } // Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows. @@ -21,9 +22,8 @@ if (runtime.status !== 0) { process.exit(runtime.status ?? 1) } -// Why both specs in one runner: they share the docker SSH rig and the same -// ORCA_E2E_SSH_DOCKER gate — the SSH parking spec proves SSH panes park and -// restore, the retention spec proves the C1 budget bounds what they retain. +// Why one runner: these specs share the Docker SSH rig; startup-exec also joins +// the paired desktop/headless parity proof under the same isolated CI lane. const result = spawnSync( pnpm, [ @@ -32,10 +32,14 @@ const result = spawnSync( 'test', 'tests/e2e/ssh-terminal-parking.spec.ts', 'tests/e2e/terminal-retention-budget.spec.ts', + 'tests/e2e/ssh-startup-exec-readiness.spec.ts', + 'tests/e2e/paired-startup-exec-readiness.spec.ts', '--config', 'tests/playwright.config.ts', '--project', 'electron-headless', + '--project', + 'electron-headful', '--workers=1', ...extraArgs ], diff --git a/config/scripts/run-ssh-docker-two-hosts-isolation-e2e.mjs b/config/scripts/run-ssh-docker-two-hosts-isolation-e2e.mjs new file mode 100644 index 00000000000..45c3911a3b8 --- /dev/null +++ b/config/scripts/run-ssh-docker-two-hosts-isolation-e2e.mjs @@ -0,0 +1,41 @@ +import { spawnSync } from 'node:child_process' + +const rawExtraArgs = process.argv.slice(2) +const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArgs +const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm' +const env = { + ...process.env, + ORCA_E2E_SSH_DOCKER: '1' +} + +// Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows. +const spawnOptions = { + stdio: 'inherit', + env, + shell: process.platform === 'win32' +} + +const runtime = spawnSync(pnpm, ['run', 'ensure:electron-runtime'], spawnOptions) + +if (runtime.status !== 0) { + process.exit(runtime.status ?? 1) +} + +const result = spawnSync( + pnpm, + [ + 'exec', + 'playwright', + 'test', + 'tests/e2e/ssh-two-hosts-isolation.spec.ts', + '--config', + 'tests/playwright.config.ts', + '--project', + 'electron-headless', + '--workers=1', + ...extraArgs + ], + spawnOptions +) + +process.exit(result.status ?? 1) diff --git a/config/scripts/run-ssh-staged-upload-reliability.mjs b/config/scripts/run-ssh-staged-upload-reliability.mjs index 4fadf6f3001..fb3d0040350 100644 --- a/config/scripts/run-ssh-staged-upload-reliability.mjs +++ b/config/scripts/run-ssh-staged-upload-reliability.mjs @@ -17,8 +17,8 @@ const defaultFiles = [ const cliArguments = process.argv.slice(2) const powerShellFlag = cliArguments.indexOf('--powershell') const configuredPowerShell = - powerShellFlag >= 0 ? cliArguments[powerShellFlag + 1] : process.env.ORCA_POWERSHELL_EXECUTABLE -if (powerShellFlag >= 0 && !configuredPowerShell) { + powerShellFlag !== -1 ? cliArguments[powerShellFlag + 1] : process.env.ORCA_POWERSHELL_EXECUTABLE +if (powerShellFlag !== -1 && !configuredPowerShell) { console.error('--powershell requires an executable path') process.exit(2) } diff --git a/config/scripts/terminal-e2e-helpers.mjs b/config/scripts/terminal-e2e-helpers.mjs index 2f89f1a7f90..8b698416326 100644 --- a/config/scripts/terminal-e2e-helpers.mjs +++ b/config/scripts/terminal-e2e-helpers.mjs @@ -222,8 +222,8 @@ if (process.argv[1]?.endsWith('terminal-e2e-helpers.mjs')) { const args = process.argv.slice(2) const portIdx = args.indexOf('--port') const cmdIdx = args.indexOf('--command') - const port = portIdx >= 0 ? Number(args[portIdx + 1]) : 9444 - const command = cmdIdx >= 0 ? args[cmdIdx + 1] : null + const port = portIdx !== -1 ? Number(args[portIdx + 1]) : 9444 + const command = cmdIdx !== -1 ? args[cmdIdx + 1] : null const term = new OrcaTerminal(port) console.log('Connecting to Orca on CDP port', port, '...') diff --git a/config/scripts/verify-agent-hook-stdin-lifecycle.mjs b/config/scripts/verify-agent-hook-stdin-lifecycle.mjs index 079735c41ec..187b5aa3fc2 100644 --- a/config/scripts/verify-agent-hook-stdin-lifecycle.mjs +++ b/config/scripts/verify-agent-hook-stdin-lifecycle.mjs @@ -142,7 +142,7 @@ function readGeneratedScripts(home, minMtime) { const body = readFileSync(path, 'utf8') const captureIndex = body.indexOf('payload=$(cat)') const firstExitIndex = body.indexOf('exit 0') - if (captureIndex < 0 || firstExitIndex <= captureIndex) { + if (captureIndex === -1 || firstExitIndex <= captureIndex) { throw new Error([fileName, ' can exit before capturing stdin'].join('')) } return { body, fileName, path, source } diff --git a/config/scripts/verify-computer-native.mjs b/config/scripts/verify-computer-native.mjs index ba23a49cdd0..56efeb33521 100644 --- a/config/scripts/verify-computer-native.mjs +++ b/config/scripts/verify-computer-native.mjs @@ -489,11 +489,11 @@ function verifyNativeArgumentGuardrails() { function powerShellFunctionBody(source, name) { const start = source.indexOf(`function ${name}`) - if (start < 0) { + if (start === -1) { return null } const bodyStart = source.indexOf('{', start) - if (bodyStart < 0) { + if (bodyStart === -1) { return null } let depth = 0 @@ -513,11 +513,11 @@ function powerShellFunctionBody(source, name) { function swiftFunctionBody(source, name) { const start = source.indexOf(`func ${name}`) - if (start < 0) { + if (start === -1) { return null } const bodyStart = source.indexOf('{', start) - if (bodyStart < 0) { + if (bodyStart === -1) { return null } let depth = 0 diff --git a/config/scripts/wsl-git-shell-benchmark.mjs b/config/scripts/wsl-git-shell-benchmark.mjs index 00ea47ded0a..d29aaea2824 100644 --- a/config/scripts/wsl-git-shell-benchmark.mjs +++ b/config/scripts/wsl-git-shell-benchmark.mjs @@ -175,7 +175,7 @@ async function main() { wslShellArgs(distro, ['/bin/sh', '-lc', escapeWslShCommandForWindows(script)]) ) const markerOffset = result.stdout.indexOf(outputMarker) - if (markerOffset < 0) { + if (markerOffset === -1) { throw new Error('Login shell did not emit the Git output marker') } result.stdout = result.stdout.subarray(markerOffset + Buffer.byteLength(outputMarker)) diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index a3074230367..610bdb8b92e 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 18m + + downloads: 19m @@ -15,7 +15,7 @@ downloads downloads - 18m - 18m + 19m + 19m diff --git a/docs/readme/README.ko.md b/docs/readme/README.ko.md index e247ace7d7c..d02a025cb5f 100644 --- a/docs/readme/README.ko.md +++ b/docs/readme/README.ko.md @@ -36,7 +36,7 @@ 휴대폰에서 에이전트를 모니터링하고 조종하세요 — 에이전트가 완료되면 알림을 받고 어디서든 후속 지시를 보낼 수 있습니다. -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.37/app-release.apk) · [문서 →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [Android APK 0.0.42](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.42/app-release.apk) · [문서 →](https://www.onorca.dev/docs/mobile) @@ -179,12 +179,14 @@ diff의 어느 줄에든 코멘트를 남기고 에이전트에게 바로 보내 Cursor logo Cursor   GitHub Copilot logo GitHub Copilot   OpenCode logo OpenCode   + MiMo Code logo MiMo Code   Amp logo Amp   OpenClaude logo OpenClaude   Antigravity logo Antigravity   Pi logo Pi   oh-my-pi logo oh-my-pi   Hermes Agent logo Hermes Agent   + Devin logo Devin   Goose logo Goose   Auggie logo Auggie   Autohand Code logo Autohand Code   @@ -211,6 +213,7 @@ diff의 어느 줄에든 코멘트를 남기고 에이전트에게 바로 보내 - **[onOrca.dev에서 다운로드](https://onorca.dev/download)** - 또는 빌드를 직접 받기: [macOS Apple Silicon](https://github.com/stablyai/orca/releases/latest/download/orca-macos-arm64.dmg) · [macOS Intel](https://github.com/stablyai/orca/releases/latest/download/orca-macos-x64.dmg) · [Windows (.exe)](https://github.com/stablyai/orca/releases/latest/download/orca-windows-setup.exe) · [Linux AppImage](https://github.com/stablyai/orca/releases/latest/download/orca-linux.AppImage) · [전체 빌드](https://github.com/stablyai/orca/releases/latest) +- headless Linux 서버에서 `orca serve`를 실행하시나요? [Headless Linux 서버 가이드](../reference/headless-linux-server.md)를 확인하세요. _또는 패키지 매니저로 설치:_ @@ -226,8 +229,8 @@ yay -S stably-orca-bin 데스크톱 앱과 페어링해 휴대폰에서 에이전트를 모니터링하고 조종하세요. -- **iOS:** [App Store에서 다운로드](https://apps.apple.com/us/app/orca-ide/id6766130217) -- **Android:** [APK 다운로드](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.37/app-release.apk) +- **iOS:** [App Store에서 다운로드](https://apps.apple.com/us/app/orca-ide/id6766130217) 또는 [TestFlight 참여](https://testflight.apple.com/join/YjeGMQBA) +- **Android:** [APK 0.0.42 다운로드](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.42/app-release.apk) --- @@ -235,6 +238,10 @@ yay -S stably-orca-bin - **Discord:** **[Discord](https://discord.gg/fzjDKHxv8Q)** 커뮤니티에 참여하세요. - **Twitter / X:** 업데이트와 공지는 **[@orca_build](https://x.com/orca_build)** 를 팔로우하세요. +- **WeChat:** QR 코드를 스캔해 Orca 커뮤니티 WeChat 그룹 7에 참여하세요. + + Orca 커뮤니티 WeChat 그룹 7 QR 코드 + - **피드백과 아이디어:** 우리는 빠르게 출시합니다. 필요한 기능이 있나요? [새 기능을 요청](https://github.com/stablyai/orca/issues)하세요. - **개인정보 보호:** Orca가 수집하는 익명 사용 데이터와 수집 거부 방법은 [개인정보 및 텔레메트리 문서](https://www.onorca.dev/docs/telemetry)를 참고하세요. - **응원하기:** 이 리포지토리에 [Star](https://github.com/stablyai/orca)를 눌러 매일 공개되는 릴리스 소식을 확인해 주세요. @@ -249,6 +256,14 @@ yay -S stably-orca-bin Orca 기여자 +

+ stablyai/orca GitHub Star 히스토리 차트 +

+ +## 서명된 빌드 + +Windows 코드 서명은 [SignPath.io](https://signpath.io)가 후원·제공하며, 인증서는 [SignPath Foundation](https://signpath.org)에서 제공합니다. + ## 라이선스 Orca는 [MIT 라이선스](../../LICENSE)에 따라 자유롭게 사용할 수 있는 오픈 소스입니다. diff --git a/docs/reference/renderer-agent-status-performance.md b/docs/reference/renderer-agent-status-performance.md new file mode 100644 index 00000000000..8ed43d868ce --- /dev/null +++ b/docs/reference/renderer-agent-status-performance.md @@ -0,0 +1,328 @@ +# Renderer agent-status performance + +## Status + +This design is adopted for the renderer's high-frequency agent-status path. It +keeps the existing event semantics while bounding the amount of synchronous +store fanout performed for one IPC burst. + +It lands in slices. This document and the `bench:idle-cpu` harness land first so +the store changes can be reviewed against a baseline someone else measured. Until +the store slice lands, the `setAgentStatuses` / `transactAgentStatuses` actions +and the agent-status write workload described below are not yet on `main`; the +harness measures scale, listener census, and raw publication fanout only. + +## Context + +Orca can display a large expanded worktree lineage inside one virtualized list +row. Virtualizing the root row does not virtualize its descendants, so a +100-worktree lineage can mount 100 `WorktreeCard` instances at once. + +Agent-status IPC events are bursty. The renderer already groups live events into +a 33 ms window, but the original flush applied every queued event with a +separate Zustand write. Zustand synchronously visits every listener for every +publication. The resulting work therefore grew with both the number of status +events and the number of mounted subscriptions: + +```text +burst work ~= status events x store listeners x selector work +``` + +A production trace captured the renderer repeatedly entering +`flushLiveAgentStatusBurst -> applyAgentStatus -> setAgentStatus -> setState` +through `Set.forEach`. A deterministic 100-worktree fixture reproduces the +structural multiplier; see "Baseline on `main`" below for the currently measured +listener count and publication cost. + +The production app later recovered substantially when all configured remote +hosts were removed. Host removal can stop relay/reconnect traffic, remove +mounted remote worktrees, or both, depending on host type and removal options. +That observation identifies remote presence as the production trigger but does +not by itself distinguish traffic volume from mounted-listener fanout. + +A read-only reconnect audit ruled out systematic double status emission from a +full PTY replay: replay bytes bypass OSC status parsing. Reconnect still causes +a full terminal-buffer repaint for every attached remote pane, which is a +separate source of renderer work and remains a follow-up investigation. + +## Goals + +- Keep a large expanded lineage responsive during dense agent-status traffic. +- Preserve every ordered status transition, including repeated updates for one + pane inside the same burst. +- Publish agent-status state once for a deferred live burst. +- Preserve selector identity and child render isolation. +- Make the regression reproducible without relying on a user's production data. + +## Non-goals + +- Changing the client/server status payload or remote protocol. +- Deduplicating status events by pane. +- Changing agent freshness, retention, history, title, completion, or provider + session behavior. +- Changing remote reconnect, PTY replay, or terminal repaint behavior. +- Redesigning lineage presentation or collapsing worktrees automatically. + +## Design + +### Bound mounted subscription fanout + +Sidebar components select cohesive state bundles with shallow equality instead +of registering one listener per field. Derived arrays and maps retain their +existing shallow identity behavior so unrelated store writes do not rerender a +card. Full agent-list mode keeps its child-level subscription boundary; compact +mode passes the already selected rows to avoid selecting the same inputs twice. + +The deterministic 100-worktree fixture pins the resulting listener budget: + +| Surface | Listener budget | +| ------------------------------ | --------------: | +| Worktree card state and caches | 2 | +| Agent-row inputs | 1 | +| Worktree activity status | 1 | +| Closed context menu | 1 | + +Unmount tests require the listener count to return to its prior baseline. In the +bundled prototype, the fixture without seeded agents fell from 8,518 listeners +to 1,218; with 100 visible agent rows the candidate mounted 1,618. Compare +against the census in "Baseline on `main`", which the harness reports directly. + +### Share working-spinner phase without per-element animation queries + +Working rows keep the existing compositor-driven CSS animation and shared +visual phase. Each mount derives one negative animation delay from the document +timeline instead of querying `getAnimations()` and mutating the animation start +time. This removes per-row Web Animations setup from dense status transitions +without adding a JavaScript animation clock. + +### Fold a burst in event order + +The store exposes the single-update action and two batch forms: + +- `setAgentStatus(paneKey, payload, ...)` retains the positional single-update + API for the immediate live path. +- `setAgentStatuses(updates)` applies a prebuilt ordered list, while + `transactAgentStatuses(operation)` lets IPC derive each update against the + exact staged state before the single commit. + +Both entry points reuse the same single-update state transition. The batch +reducer passes each resulting state into the next update, so a sequence such as +`working -> waiting -> done` retains the same history and timestamps as three +sequential calls. Updates are never keyed or deduplicated before the fold. + +The live IPC queue is spliced before it is processed. This preserves the +existing reentrancy guarantee: a synchronous subscriber can enqueue another +event without causing the current queue to be drained recursively. The first +event outside an active burst remains immediate; events accumulated within the +33 ms window are applied as one ordered transaction. Startup snapshots and +bounded pending-hydration retries use the same transaction path instead of +publishing once per restored pane. + +Each transaction builds pane-routing ownership once with the same first-match +semantics as the standalone resolver. Split-layout leaf membership is indexed +once per layout root, so a large snapshot performs linear tab and leaf work +instead of rescanning every mounted worktree for every pane. + +### Run effects after the transaction + +Generated-title work that requires committed state is deferred until after the +transaction. Accepted updates also request freshness scheduling; the outer batch +coalesces those requests and schedules the shared freshness timer once after its +single commit. Generated-title requests are folded in event order and published +together, including first-write and forced-replacement semantics. Resolved tab +titles are projected while the transaction folds, then final title changes are +published together. Completion-triggered review refreshes remain deferred +microtasks. + +Bulk title application preserves event order and duplicate-tab behavior while +indexing owners once, cloning each changed owner array once, and replacing each +top-level map once. This keeps the post-commit title phase linear in mounted +tabs plus changed titles. + +This separation is important: invoking store actions from inside a Zustand +updater would re-enter the store, while running an effect before the commit +would let it observe stale state. + +## Semantic invariants + +Sequential and batched application must agree on: + +- live and retained agent maps; +- state history, `updatedAt`, and `stateStartedAt`; +- agent identity, model, prompt, tools, assistant messages, and subagents; +- orchestration and provider-session continuity; +- sleeping-session and launch-config recovery records; +- retired/closed-pane rejection and inherited-status suppression; +- retention cleanup and live-map eviction; +- `agentStatusEpoch` and `sortEpoch`; +- automation completion observation across intermediate transitions; +- generated-title inputs, freshness scheduling, and completion refreshes. + +Equivalence tests use fixed timestamps and include repeated same-pane +transitions. A publication-count test subscribes to the real store and requires +one notification for a non-empty batch and none for an empty batch. + +## Benchmark contract + +The benchmark launches an E2E-mode Electron build with the store exposed only +for instrumentation. It creates 100 worktrees in one expanded lineage, verifies +100 mounted cards, captures the store listener census, and then applies seeded +ordered agent-status traffic through the real store action. + +The benchmark measures the synchronous store action, not the live IPC leading +edge or post-commit notification path. A real-store snapshot test covers the +end-to-end budget for 100 panes with auto-generated titles enabled: one status, +one bulk generated-title, and one bulk resolved-title publication. Disabling +generated titles removes that middle publication, independent of pane count. + +The artifact records only fixed diagnostic fields needed for comparison: + +- requested and completed batches and updates; +- store action calls and observed publications; +- elapsed time, throughput, and scheduling drift; +- final-state verification; +- renderer mean, p95, and maximum CPU; +- renderer timer drift and long tasks; +- mounted-card and listener counts. + +Raw process inventories, temporary paths, pane identifiers, and DOM text are +diagnostic-only and must not be embedded in the shareable report. + +Run baseline and candidate on the same machine and OS with the same Electron +build mode. CPU samples from macOS and Linux are comparable within that +constraint; Windows process CPU collection currently cannot support this +comparison. + +## Harness + +`pnpm run bench:idle-cpu` drives `config/scripts/run-idle-cpu-benchmark.mjs`, +which composes four modules: + +| Module | Responsibility | +| ------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `idle-cpu-renderer-scale-fixture.mjs` | Seeds the lineage, agent rows, and sidebar view state; takes the mounted-card and listener census | +| `idle-cpu-renderer-timing-probe.mjs` | In-page timer drift and long-task probe; runs the no-op publication workload | +| `idle-cpu-process-sampling.mjs` | Classifies the Electron process tree and samples per-role CPU/RSS | +| `idle-cpu-synthetic-spinners.mjs` | Measurement-only visible spinners | + +The sampling window extends past `--sample-ms` until the workload settles, and +fails the run rather than reporting a truncated window if the workload overruns +the guard. That is why a 2,000-publication run reports a measured window longer +than the requested one. + +`--zustand-publications` publishes an empty partial through the real store, so +each publication costs exactly one full subscriber visit and nothing else. It +isolates the `listeners x selector work` half of the burst-cost model from +agent-status payload work, and it is store-API independent — it measures the +same thing before and after the batching slice. + +The agent-status write workload (`--agent-status-batches`, +`--agent-status-write-mode`) is not in this harness yet. It depends on +`setAgentStatuses`, so it lands with the store slice. + +## Baseline on `main` + +Measured on `main` at `077f5a11cd4` (macOS, arm64, 16 CPUs), Electron built with +`electron-vite --mode e2e`, headless, 100 worktrees at lineage depth 99 with 100 +seeded agent rows, 10 s warmup and a 30 s sampling window. + +Fixture scale is confirmed by the census rather than assumed: 100 store +worktrees, 100 mounted cards, 100 mounted agent rows, and **9,279 store +listeners**. That listener count is the multiplier the design targets. + +2,000 no-op store publications at a 1 ms cadence, three repetitions. The +listener census was 9,279 in every run. + +| Measure | Median | Runs | +| ------------------------ | ----------: | ------------------------------ | +| Wall time to complete | 12,325.7 ms | 13,148.6 / 12,325.7 / 11,870.5 | +| p50 scheduling drift | 5,150.3 ms | 5,432.3 / 5,150.3 / 4,945.2 | +| p95 scheduling drift | 9,802.9 ms | 10,570.4 / 9,802.9 / 9,390.0 | +| Renderer mean CPU | 18.25% | 20.25 / 18.25 / 15.88 | +| Renderer p95 CPU | 32.59% | 40.07 / 32.59 / 31.28 | +| Renderer timer drift p95 | 7.0 ms | 7.3 / 5.3 / 7.0 | + +2,000 publications requested over 2 s take about 12 s, so the renderer sustains +roughly 160 publications per second at this scale. Each publication is +individually short - the long-task observer recorded zero entries in all three +runs - so the cost surfaces as scheduling drift and sustained CPU rather than as +discrete long tasks. Compare drift and CPU here, not long-task counts. + +The idle control at the same scale with `--zustand-publications 0` reports 6.63% +renderer mean CPU, 17.11% p95, and 1.6 ms p95 timer drift. Roughly 11.6 points +of mean renderer CPU are therefore attributable to publication fanout rather than +to the mounted fixture itself. 200 spinner animations run in both cases, so the +control also bounds the animation cost out of the comparison. + +Reproduce with: + +```bash +pnpm run bench:idle-cpu -- --worktrees 100 --lineage-depth 99 \ + --agents-per-worktree 1 --warmup-ms 10000 --sample-ms 30000 \ + --zustand-publications 2000 --zustand-publication-interval-ms 1 \ + --output /tmp/idle-cpu-baseline.json +``` + +## Results + +Three repetitions used 100 mounted worktrees, lineage depth 99, 100 seeded +agent rows, and verified final state. Medians from the regenerated evidence set +are: + +| Single 2,000-update burst | Sequential | Batched | +| ------------------------- | ---------: | ---------: | +| Status-state publications | 2,000 | 1 | +| Store action time | 3,692.0 ms | 188.7 ms | +| Update throughput | 541.7/s | 10,598.8/s | +| Renderer mean CPU | 36.2% | 2.9% | +| Renderer p95 CPU | 107.3% | 8.2% | +| p95 long task | 4,653 ms | 216 ms | + +The direct store transaction performs 99.95% fewer status-state publications, +spends 94.9% less time in the store action, and processes updates 19.6 times +faster. Renderer mean CPU falls 92.0%, renderer p95 CPU falls 92.4%, and the p95 +long task falls 95.4%. + +The 60-burst × 32-update case at 33 ms is a sustained saturation stress, not a +real-time production SLO. Publications fall from 1,920 to 60 and median store +action time falls from 2,791.9 ms to 323.3 ms. Median completion time falls from +5,298.2 ms to 2,710.6 ms, p95 scheduling drift falls from 3,073.0 ms to 664.9 +ms, and long-task count falls from 57 to 1. Renderer p95 CPU remains saturated +and noisy in this cadence, so it is not used as the discriminating measure. + +The 20-pane artificial OpenCode regression passes with 12.4 ms median key echo, +25.2 ms worst key echo, 19.4 ms maximum timer drift, and zero dropped renderer +backlogs. + +These figures come from the bundled prototype and are restated here as the +target. They are re-measured with the harness when the store slice lands. + +## Acceptance criteria + +- The 100-worktree fixture stays at or below the pinned listener budgets. +- A deferred transaction performs one status-state publication while preserving + ordered final state, including live-map eviction at the 500-row cap. +- A 100-pane startup snapshot performs one status and one bulk resolved-title + publication with generated titles disabled; enabling generated titles adds at + most one ordered bulk publication while preserving final statuses and titles. +- Sequential-versus-batch equivalence tests pass across same-pane transitions + and side-effect-bearing updates. +- Renderer CPU tails and scheduling drift improve in repeated candidate runs. +- The 20-pane artificial terminal test reports no dropped output backlog and no + material typing-latency regression. +- Web typecheck, focused unit tests, lint, max-lines ratchet, and E2E build pass. + +## Compatibility + +This is renderer-local. It adds no RPC field, stream opcode, persisted data, Git +command, or provider-specific contract. Native, WSL, SSH, relay, folder +workspace, and git-worktree status events enter the same renderer action. Mixed +client/server versions therefore need no capability negotiation. + +## Failure containment + +The first live event remains immediate. Startup replay and bounded pending +retries fold synchronously without waiting for the 33 ms live-burst window, but +publish their accepted updates together. Empty batches are no-ops. If an update +is stale or targets retired authority, the reducer skips only that update and +continues folding later events in order. diff --git a/docs/reference/terminal-session-behavior-contract.md b/docs/reference/terminal-session-behavior-contract.md new file mode 100644 index 00000000000..e345f36c8c2 --- /dev/null +++ b/docs/reference/terminal-session-behavior-contract.md @@ -0,0 +1,146 @@ +# Terminal session behavior contract + +Properties every terminal-session change must preserve. They describe +observable behavior, not mechanism, so a test written against them stays valid +under any implementation. + +Oracles for the STA-3077 properties live in +`src/main/ssh-reattach-pane-cardinality.test.ts`. + +## Why this exists + +Reconnecting an SSH-backed workspace used to add panes the user never opened, +and the remote host accumulated shells nobody was using — one report went from +2 to 19 to 20 relay PTYs across three reconnects. The failures in this class +share one shape: **something absent was treated as something dead**, or a +reattach was allowed to create what it should only have bound. + +## A. Unknown is not dead + +A disconnect, timeout, absent inventory entry, or failed inspection means +_unresolved_. None of them may terminate a PTY, release a binding, or authorize +cleanup. + +**A5** — a timer may never be the _sole cause_ of a destructive action. A timer +that bounds a wait or triggers re-verification is fine; a timer that kills is +not. Retry count never decides identity or liveness. + +This is deliberately weaker than "no timers". Recovery budgets and scratch-file +age-gates are correct code and must stay. + +Two patterns make a retention bound safe, and both beat shortening it: + +- measure **process time**, not wall clock, so a suspended laptop does not + burn the budget; +- gate aggressive reclamation on an **independent observation** — a second + consecutive scan, or another client completing a handshake — so the clock + bounds a wait while evidence authorizes the act. + +**B** — respawn requires proof. A failure that does not prove the session is +gone is unresolved: leave the shell running and keep the binding. An +unrecognized failure must never become a respawn, because a duplicated shell +is worse than a stalled one. + +## B. Attach binds; it never creates + +An ambiguous, unavailable, or rejected attach does not spawn a shell and does +not grow topology — no minted tab, no minted leaf, no split root, no minted +layout. Only an explicit create for a fresh pane may spawn. + +Corollary: after a recovery, keystrokes cannot land on a different shell than +the one that was visible before it. + +## C. Exact-binding fencing + +Mutating operations name the binding captured before the first await and are +rejected when any component no longer matches. A stale operation cannot reach a +later pane generation, a later PTY incarnation reusing the same id, or a +restarted owner. Output and exit arriving under a stale binding are dropped. + +The store already enforces this via `persistPtyBinding`'s `expectedBinding` +compare-and-swap and the per-repo topology revision fence. + +## D. Cardinality + +One pane owns at most one live PTY binding, and one PTY incarnation belongs to +at most one pane. Lease identity must therefore include the pane, not just the +transport id — keying on `(targetId, ptyId)` alone is what let predecessors +accumulate. + +Superseding a lease marks it expired; it does not kill the remote process, +because losing a lease is not proof the shell died. + +## E. Ordering and loss + +Output is delivered in PTY order. A gap is resolved by resnapshot, never by +silently continuing. A correctness-bearing effect (exit, command completion, +review link, bell) is neither lost while the renderer is unmounted nor applied +twice after a replay. + +Bounded replay plus idempotent application by event key satisfies this. A +durable per-consumer delivery cursor is not required, and is not currently +used. + +**Lifecycle is state, not an event.** An exit that happens while nothing is +attached is not recovered from a delivery channel — it is read during the +attach handshake. The attach reply should carry whether the session is alive +or exited, its exit code, and the resume offset. That is what removes the need +to guarantee delivery of an exit _event_, and it is why no journal is required +here. + +Where a resume offset cannot be served, advance the offset explicitly by the +size of the gap and persist the running total, so "output was lost here" stays +a queryable fact rather than a silent discontinuity. + +## F. Isolation + +A failure on one host cannot affect another host; a failure in one workspace +cannot affect another on the same connection. There is no process-wide failure +fence. + +## G. Liveness + +Every fail-closed path needs a bounded, user-reachable recovery. A workspace +must never reach a state that permanently refuses terminal operations with no +operator escape — in particular, backpressure from a consumer that is gone +forever must be releasable without that consumer's cooperation. + +Unavailable transports retry with bounded backoff and bounded memory. + +## H. Compatibility + +Clients and hosts update independently. A capability is negotiated or the newer +side degrades; a required operation is never silently dropped. New stream +opcodes must be capability-negotiated, because decoders drop unknown opcodes +silently. Nothing is gated on an app build id. + +See [`remote-wire-compatibility.md`](./remote-wire-compatibility.md). + +## I. Cost + +No new work on the input hot path and none per output frame. Pane create and +close latency must not regress, including over a high-latency SSH link. No +startup-blocking probe of a host nothing has asked for. + +--- + +## Test the call site, not the capability + +A guard that exists and is never passed is indistinguishable from no guard. +`mayCreate` was added to `persistPtyBinding`, was correct, and had no +production caller for several commits — every store-level test passed the whole +time, because they called the store directly. + +So for anything that refuses a destructive action, pin the **caller**: assert +that the reattach path passes the refusal, not merely that the store honours it +when asked. The same applies to a classifier — assert the branch that consumes +its verdict is reachable, since a guard behind an unreachable `catch` is dead. + +## Deliberately not required + +A durable event journal, per-consumer cumulative delivery cursors, and +cryptographic device principals are **not** required by any property above. +Each would need to earn its place by being the only way to satisfy one of them. + +Principals, in particular, exist only to key cursors: without cursors there is +nothing for them to key. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/PR-13326-REPLACEMENT-DESIGN-2026-08-13.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/PR-13326-REPLACEMENT-DESIGN-2026-08-13.md new file mode 100644 index 00000000000..0e5eae53bc4 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/PR-13326-REPLACEMENT-DESIGN-2026-08-13.md @@ -0,0 +1,192 @@ +# Design: make "Start a new terminal" a replacement, not a spawn + +Supersedes the mechanism in `PR-13326-SESSION-HANDOFF-2026-08-12.md` §"Approved bounded redesign". +Keeps its **properties**; replaces several of its **mechanisms** with smaller ones, and adds the +thing it was missing — a way to actually run the decisive test. + +## 1. The defect, stated once + +"Start a new terminal" is routed through a path whose job is *"resolve this pane's owner and attach +it; spawn only if there is none."* Creation is that path's fallback, not its purpose. The pane's +durable binding still names the old shell at click time, so the path resolves it and adopts it. + +I confirmed this first-hand earlier in the branch: commit `ab6ce176f3f` detects adoption after the +fact (`freshPtyId === sessionId`) and stops the callback from unbinding the live shell. Its own +message records that suppressing the adoption itself was left undone. So the adoption is real, and +the current code only contains its worst consequence. + +## 2. Why every previous fix leaked + +Each attempt expressed "do not adopt" as **another condition inside the adopting path**. Conditions +are forgettable and order-dependent, and this branch has three shipped proofs of that failure mode: + +- a guard centralised into a publisher that returned `void`, so four callers paired a conditional + publish with an unconditional `return`; +- the same rule applied to the tombstone branch and missed on the liveness branch beside it; +- the incarnation fence sent on the pane-driven route and not on the reconnect route. + +Every one was "the rule exists, but this path does not ask it." A fourth condition in the same path +is the same bet again. + +## 3. The design, and why it removes the defect + +### P1 — Replacement is a separate operation that cannot adopt + +Add a main-owned entry that performs replacement only. It contains **no owner-resolution call**: it +does not read a stable-pane owner, does not accept `sessionId`/`attachOnly`, and constructs provider +options from a narrow main-owned allowlist (dimensions + validated pane/workspace identity). + +*Why this fixes it:* adoption stops being a branch that must be avoided and becomes code that is not +present. A function with no owner-resolution cannot adopt for the same reason a function with no +socket cannot make a network call. This converts "remember to skip adoption" (liveness) into "there +is nothing here to adopt with" (structure). + +*Falsifiable by:* route the action back through generic spawn — the oracle in P0 must redden. + +### P2 — Ownership moves in one durable commit, keyed on exact incarnation + +One Store method mutates and flushes once: exact-CAS the old binding and the old active lease, +install the new binding + incarnation + attached lease, expire the exact old lease **without +touching its process**, bump the topology/lease versions, flush. + +*Why:* ownership lives in the durable binding and the lease. Moved separately, there is a window +where a racing reconnect sees a half-moved pane and restores the predecessor. One commit means the +window does not exist rather than being narrow. + +*Why exact incarnation:* the relay reissues `pty-N` from 1 after a reset, so any CAS keyed on ptyId +alone can match a different process. This branch already proved that and already carries the +primitive: host-attested `SshRemotePtyLease.incarnationId`, the relay-side `expectedIncarnationId` +fence, and `isRelayAttestedPtyIncarnationId` filtering synthesised values. + +*Falsifiable by:* split the commit in two flushes and drive a reconnect between them. + +### P3 — Ambiguity leaks, never kills + +Provider/relay shutdown identifies a PTY by id only. After a dispatched spawn whose outcome is +ambiguous, we cannot prove which incarnation a shutdown would reach. So: clean up a failed new shell +only when its exact incarnation is provable; otherwise leave it running and unbound for the existing +cleanup surface to reap. + +*Why:* the costs are asymmetric. Leaking costs an orphan shell that a user can already list and +terminate. Killing the wrong incarnation destroys a live agent session — the exact harm this whole +program exists to prevent. + +*Falsifiable by:* make the ambiguous path call shutdown; the oracle asserting zero kill RPCs on an +unprovable outcome must redden. + +### P4 — The successor is invisible until it is the owner + +Spawn the replacement hidden and install its output handlers only after P2 commits. + +*Why:* a new shell reusing the old raw id could otherwise deliver bytes into the predecessor's +model. Ordering removes the window without a new quarantine subsystem. + +### P5 — Stale renderer work does nothing + +Guard every completion on: not disposed, current transport identity, current action generation. A +stale callback must not clear a binding, republish the card, or kill a result. Main owns the durable +transition, so the renderer never clears the old binding on success. + +## 4. What I am deliberately NOT building, and the risk of each + +The handoff prescribes more machinery. I judge these unnecessary for this defect; each is a +reversible decision if an oracle shows otherwise. + +| Prescribed | Decision | Reasoning | Risk if I am wrong | +|---|---|---|---| +| Opaque ticket bound to ~11 fields (sender, both generations, worktree, tab, leaf, pane key, both ids, both incarnations, expiry, 5-state machine) | **Replace** with an operation id + expected-owner `{ptyId, incarnationId}` CAS | The renderer is not a trust boundary — it can already open terminals. The ticket's real jobs are staleness and idempotency, which the CAS and op id give directly. Eleven bindings add eleven invalidation paths, and invalidation bugs are the same class we are trying to leave | A forged/stale request creates one blank shell for a pane the user owns — recoverable, and the CAS still refuses to move ownership off an unexpected incumbent | +| A new shared owner mutex | **Reuse** `paneSpawnReservationsByOwnerKey` (already per-pane) and the runtime pane-create claim | Serialisation already exists at exactly this granularity; a second lock invites lock-order bugs | Two operations interleave on one pane; the P2 CAS still refuses the loser | +| A quarantine subsystem for provider output | **Reuse** hidden spawn + install-after-commit ordering | Achieves the same property with existing options | Bytes reach the wrong model; caught by the P4 oracle | + +## 5. The part the previous session was missing: the decisive test can now run + +`tests/e2e/ssh-disconnected-pane-affordance.spec.ts` holds the decisive case at `test.fixme` because +**the state was not inducible**: it needs the SSH target CONNECTED while exactly one pane's +`pty.attach` fails with an error that does not prove the shell gone. Host faults tried (SIGSTOP the +relay) take the whole connection down and produce the connection overlay instead. + +That state is now inducible, by a mechanism this branch added for another reason. The relay refuses +an attach whose `expectedIncarnationId` names a different shell, with +`PTY "" identity mismatch` — per-pty, connection healthy, and explicitly not proof of death +(`SSH_PTY_IDENTITY_MISMATCH` never grounds a respawn). + +So the test can seed the pane's lease with an incarnation that is not the host's, reconnect, and get +exactly the state the banner needs — deterministically, with no timing fault. + +**This is the highest-value item in the plan and it comes first.** The previous session looped +because every claim was adjudicated by reading code; with the oracle running, the design is +*demonstrated* instead of argued, and a regression reddens instead of being found in review. + +## 6. Goalposts + +Each is a behaviour with a stated mutation that must redden it. G1 is a prerequisite for believing +any of the others. + +| # | Goalpost | Mutation that must redden it | +|---|---|---| +| **G1** | The decisive E2E runs unskipped: with the target connected, one pane unreachable, clicking "Start a new terminal" yields exactly one new remote shell, the pane count is unchanged, and the host transcript shows no second agent launch | Remove the induction; the test can no longer reach the banner | +| **G2** | The action never adopts: the pane's shell id/incarnation after the click differs from before, and the new shell has no command, resume metadata, launch token, agent, or startup delivery | Route the action back through generic `pty:spawn` | +| **G3** | Ownership moves atomically: a reconnect racing the replacement cannot restore the predecessor; binding and lease agree at every observable point | Split the durable commit into two flushes | +| **G4** | Ambiguity never kills: on an unprovable spawn outcome, zero shutdown RPCs are issued and neither process dies | Call ID-only shutdown on the ambiguous path | +| **G5** | The successor is silent until it owns the pane: no provider bytes reach the predecessor's model, including when the raw id is reused | Install output handlers before the commit | +| **G6** | Stale renderer work is inert: a disposed or superseded callback clears no binding, republishes no card, kills no result | Drop the generation guard on the completion path | + +## 7. Sequence + +0. Remove the rejected six-file WIP (targeted edits, not a broad restore — the worktree is dirty). +1. **G1** — induction + un-`fixme`. Nothing else is believable until this runs. +2. **G2** — the separate replacement operation. +3. **G3** — the single durable commit. +4. **G4/G5/G6** — ambiguity, ordering, staleness. +5. Adversarial review on both models, then push. + +## 8. Stop conditions + +- If G1 cannot be made to run, stop and report. Building 2–6 without it repeats the previous loop. +- If exact cleanup cannot be achieved within existing local/provider contracts, take the leak (P3). + Do **not** add `expectedIncarnationId` to remote shutdown — that is a separate, capability- + negotiated wire change with its own review. + +--- + +## 9. Findings from running the gate (2026-08-13) + +The oracle in §5 works: the state is inducible and the card appears reliably. Running it found +three things that reading had not. + +**Fixed — the card's buttons were unclickable.** `TerminalErrorToast` renders at `z-50` in the same +bottom strip and was suppressed only for the connection overlay, not for the pane's own card. In +the one state this affordance exists for, both actions were covered. `TerminalPane.tsx` now also +suppresses it while the active pane shows the card. + +**Fixed — a session id is the instruction to attach.** "Start a new terminal" was still sending the +pane's recorded `sessionId`, which routes straight to reattach before any pane-owner logic runs, so +the action attached the very shell it could not reach and created nothing. Skipping owner +resolution in main was NOT enough on its own; the id had to be dropped at the last gate before the +IPC (`admittedSessionId` in `pty-transport.ts`). + +**OPEN — the action produces no spawn at all.** With both fixes in, the measured result after +clicking is still `visible=true launches=1 shells=1`: the card clears briefly, no shell is created, +and the card returns. The main log over the same window shows only the pane's own restore retries +(three `spawn() called with sessionId=…` → `identity mismatch`), never a fresh spawn. + +The evidence points at the action closure rather than the spawn path: the pane retries its restore +while the card is up, each retry republishes the card, and the button the test clicks appears to +belong to a superseded connection whose `startFreshSpawn` no longer does anything. That is the +"stale renderer work" hazard from the original handoff, showing up as a dead button rather than as +a wrong write. + +**RESOLVED.** Instrumenting handler, transport and main in one correlated run disproved the +closure hypothesis: the handler ran, the connection was live, and the renderer half was already +correct — it sent no session id and asked for adoption to be refused. Main re-derived the id anyway. + +The rule had been applied at the two places an owner is PRODUCED and missed at the one place it is +CONSUMED: `spawnForStablePane` turns an owner into `sessionId` for the provider, which is what makes +an attach an attach. Gating there — `if (args.owner && !args.refuseAdoption)` — closes it for every +producer at once, present and future. + +The gate now passes, and reverting that single condition reddens it. + +Lesson worth keeping: this rule leaked at three sites in a row (early owner resolution, the +transport's session id, the owner consumption). Each fix was necessary and none was sufficient. The +one that finally held was the one placed where the value is USED rather than where it is derived. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/PR-13326-SESSION-HANDOFF-2026-08-12.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/PR-13326-SESSION-HANDOFF-2026-08-12.md new file mode 100644 index 00000000000..bd4900ddf52 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/PR-13326-SESSION-HANDOFF-2026-08-12.md @@ -0,0 +1,823 @@ +# STA-3077 / PR #13326 session handoff + +> **Status:** paused at an approved bounded redesign; not release-ready. +> +> **Review/fix round:** 6. +> +> **Do not continue the current six-file implementation.** It is a rejected, +> uncommitted grant-map approach. Remove it with `apply_patch`, then implement +> the dedicated main-owned replacement transaction described below. + +This is the continuation entrypoint for the current PR. It records the whole +session at the point the user asked to pause, including what shipped to the PR +branch, what failed review, the agreed design boundary, and the next safe work. + +## Executive summary + +The session started with STA-3077's SSH reconnect failure class: reconnects +could graft panes the user never created, accumulate remote shells, fabricate +process death from an attach failure, or let stale identities affect a +successor. The branch now contains extensive fixes, tests, design records, and +two user-visible recovery actions for an unreachable pane. + +The pushed candidate is still incorrect in one important action. “Start a new +terminal” invokes generic `pty:spawn` while the old durable pane binding remains. +Main can adopt that old owner, so the action can reopen the old shell instead of +creating the one blank shell the user requested. + +An attempted six-file fix added `freshSpawnForUnreachablePtyId` to generic spawn +and a process-global grant map. Three independent read-only audits rejected it. +The common verdict was that replacement must be a dedicated local transaction +owned by Electron main, with exact incarnation identity, one durable Store +commit, runtime ownership transfer, output quarantine, reconnect fencing, and +renderer generation guards. + +The user approved this bounded redesign. It applies only to the broken +unreachable-pane replacement operation. It is not authority to restart the +earlier whole-system architecture effort. + +## Repository checkpoint + +Verified before this handoff was written: + +| Item | Value | +| ----------------------------------- | ---------------------------------------------------- | +| Worktree | `/Users/nwparker/orca/workspaces/orca/eye-React-185` | +| Local branch | `nwparker/sta-3077-reattach-pane-cardinality` | +| HEAD | `df6edfcebd2ea401a6feda1fccf31189e57eceda` | +| HEAD subject | `fix(ui): center narrow terminal recovery actions` | +| Actual PR | `stablyai/orca#13326` | +| Actual PR ref | `origin/nwparker/sta-3077-d-affordance-and-review` | +| Actual PR ref SHA | exactly `df6edfcebd2ea401a6feda1fccf31189e57eceda` | +| Configured upstream | `origin/nwparker/sta-3077-reattach-pane-cardinality` | +| Configured upstream SHA | `518dac34415e0f67883461c3f58e5586209c7f24` | +| Local `origin/main` | `889dd4c7d2fe255aac552e4dcc91204279dc022c` | +| Merge base with local `origin/main` | `58a926170cd99baf8920a83a86799bfbd307d735` | +| Local `origin/main...HEAD` | 10 commits on main / 109 commits on HEAD | + +The configured upstream is stale. Its `[ahead 387]` status is not the PR's +push state. The PR ref is exactly at HEAD. When the work is genuinely ready, +push explicitly: + +```bash +git push origin HEAD:nwparker/sta-3077-d-affordance-and-review +``` + +Before this document, the worktree had six modified tracked files, no untracked +files, and a `+163/-11` uncommitted diff. `git diff --check` was clean. No +product test, typecheck, lint, build, Electron, or E2E command was run against +that dirty state. + +## The intended outcome + +For a pane whose old SSH terminal cannot currently be reached, the UI offers: + +- **Try again:** attempt to reattach the exact existing shell without claiming + it exited or spawning a replacement. +- **Start a new terminal:** keep the same pane and leaf, create exactly one + genuinely blank shell, move durable and runtime pane ownership to it, and + leave the unproven old process alive but unbound. + +The second action must never: + +- silently adopt or resume the old shell; +- resume an agent, command, launch token, startup sequence, or saved telemetry; +- create another pane or tab; +- kill a process whose exact incarnation is not proven; +- let a reconnect restore the predecessor after replacement wins; +- let stale renderer work clear, kill, or republish the successor; +- expose provider output before the replacement commits; or +- add replacement intent to SSH, relay, provider, paired-runtime, or stream + wire contracts. + +## What was done during the session + +The branch has 109 first-parent commits over its current merge base, including +two large updates from `origin/main`. The useful progression is below; use the +git history for the complete commit-by-commit record. + +### 1. Reconnect and persistence containment + +The early work stopped SSH reconnect from treating persisted rows as permission +to create UI, made pane binding authoritative during duplicate arbitration, +and added rollback around durable lease retirement. + +Representative commits: + +- `5d8bb18fd3f` — stop reconnect from grafting panes and stacking leases. +- `ae134995c13` — heal duplicate pane leases from older state. +- `ccb082740fc` — let the durable pane binding outrank recency. +- `8d9aeb55e03` — roll back lease retirement when durable writing fails. +- `03d794a0f90` — pass `mayCreate: false` from the production reattach writer. +- `a7558a837ca`, `13ca7630116`, and `8ec025e4e46` — add and strengthen pane, + process, binding, and lease census oracles. + +### 2. Unknown is not death + +The session removed several paths that inferred a dead process from missing, +unavailable, timed-out, or disconnected state. + +Representative commits: + +- `eec807d7594` — stop respawning a shell that may still be running. +- `356d6b52b24` — apply positive-proof requirements to both reattach paths. +- `b9d58423121` and `7589df8b348` — let PTY liveness remain unknown. +- `7cd7fef927f` — a reattach not-found is not itself proof of shell death. +- `e39514e9ab2` and `41613b5c84c` — distinguish bare not-found from a relay- + proven exit and retire a lease only in the latter case. + +This work also stopped one exhausted delivery recovery from tearing down every +session on an SSH host (`07e382ec196`) and made parked delivery recoveries +expire/re-enter correctly (`124e00e8a83`, `601604d17b1`). + +### 3. Exact operation and incarnation fencing + +The branch added or strengthened stale-operation refusal, host-attested shell +identity, remembered-exit identity, and reconnect fences. + +Representative commits: + +- `0de5994be91` and `980e5d846b5` — fence stale writes, resize, and signals. +- `235e45ad0f2` — record host-attested shell identity on a lease. +- `30441f1ebbb` — fence recycled relay PTY IDs by shell identity. +- `8f0c8e3ed35`, `42cbe34523f`, `c14ba64d9dc`, and `0cb187f6035` — require an + exit proof to name the shell for which it grants replacement authority. +- `5793f186e96`, `be02c4e7f5c`, and `901dd06b8d1` — apply incarnation and pane + fences on reconnect, including clients unable to name a shell. +- `c8d08e1b215` — strengthen the incarnation write-fence regression oracle. + +These improvements are valuable, but the round-6 review found that raw PTY ID +is still used as identity in important lease/runtime/cleanup paths. The new +replacement transaction must finish that exact-incarnation work for its own +surface rather than assuming the existing fencing is complete. + +### 4. Pane arbitration and rollback hardening + +Lease arbitration moved from tab-level assumptions toward the actual pane leaf, +and rollback was hardened so an already-expired duplicate cannot be revived. + +Representative commits: + +- `b92498468a5` — arbitrate on the pane, not the tab. +- `1697b3be163` — supersede on the leaf. +- `7724a950ecd` — mutate only the plane that supplied the supersession proof. +- `21ad47c0bc5` — fence duplicate-lease rollback and add a regression oracle. + +The existing `upsertSshRemotePtyLease` key remains `(targetId, ptyId)`. That is +insufficient when an old and a new process reuse the same raw ID but have +different incarnations. Replacement requires exact lease identity. + +### 5. Unreachable-pane product behavior + +The renderer now presents a provider-neutral disconnected card with two +explicit actions and copy that does not claim an unobserved exit. + +Representative commits: + +- `5e1b57bb2f9` — add the two-action disconnected pane affordance. +- `d27927b84b5` — remove a remote-host-only assumption from its copy. +- `037ee535b8a` — centralize unreachable-pane guards. +- `f7eb6f26656` — suppress the entire saved startup set for a fresh shell. +- `b46a1f8773e` — avoid stranding a local pane after restore failure. +- `ab6ce176f3f` — do not unbind a live shell that generic spawn adopted. +- `df6edfcebd2` — center the recovery actions in narrow panes. + +The last item in that list makes the pushed behavior internally safer but also +exposes the unresolved product bug: generic spawn can adopt the incumbent, so +“Start a new terminal” is not guaranteed to start anything new. + +### 6. Tests, design records, and platform evidence + +The session added substantial focused and E2E coverage for local restart, +daemon/WSL survival, SSH pane cardinality, two-host isolation, `MaxSessions=1`, +mixed-version decoding, lease termination, relay exit proof, and renderer +recovery behavior. The main records are: + +- `docs/reference/terminal-session-behavior-contract.md` +- this folder's `goalposts.md`, `design-final-detail.md`, and `resume-plan.md` +- `src/main/ipc/pty.test.ts` +- `src/main/ipc/pty-superseded-operation-fence.test.ts` +- `src/main/persistence.test.ts` +- `src/main/persistence-ssh-lease-termination.test.ts` +- `src/main/runtime/orca-runtime.test.ts` +- `src/main/ssh-reattach-pane-cardinality.test.ts` +- `src/main/ssh/ssh-relay-reattach-exit-proof.test.ts` +- `src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts` +- `src/renderer/src/components/terminal-pane/pty-connection.test.ts` +- `src/renderer/src/components/terminal-pane/pty-transport.test.ts` +- `src/renderer/src/components/terminal-pane/TerminalPaneDisconnectedBanner.test.tsx` +- `tests/e2e/ssh-disconnected-pane-affordance.spec.ts` + +Historical receipts in `goalposts.md` include discriminating native macOS, +Linux, Windows, physical WSL, daemon, and Docker work at earlier candidate +SHAs. They are historical evidence, not a current-HEAD validation receipt. + +Important proof corrections were also recorded during the session: + +- a guard tested only through a direct Store call can still have no production + caller; +- a green E2E that also passes without the fix is a forward guard, not proof; +- the disconnected-pane state is not currently inducible with the existing + Docker host faults; and +- the first recovery grant and a later pane-binding fold were deleted after + review showed their premises were false or their path was unreachable. + +## The proven current bug + +At pushed HEAD, the renderer's disconnected action calls `startFreshSpawn`, +which calls the normal transport `connect`, which invokes generic `pty:spawn`. +The old durable binding is still present. Generic spawn resolves stable pane +ownership and may attach/adopt that incumbent rather than create a blank shell. + +Consequences: + +- “Start a new terminal” can reopen the old terminal. +- A same-ID/new-incarnation result is not representable in the current renderer + result contract. +- The action's success path may compare or clear ownership by raw PTY ID. +- The full product oracle is not running. + +The decisive E2E is +`tests/e2e/ssh-disconnected-pane-affordance.spec.ts`, test “starting a new +terminal adds exactly one shell and leaves the panes alone,” beginning near line 314. It is still unconditionally held by +`test.fixme(true, UNREACHABLE_PANE_INDUCTION_UNAVAILABLE)` near line 318. + +## Dirty WIP that must be removed + +The six uncommitted files implement the rejected +`freshSpawnForUnreachablePtyId`/grant-map design: + +| File | Uncommitted behavior | +| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `src/main/ipc/pty.ts` | Adds a max-256 process-global grant map, records a raw `StablePaneOwner` after attach failure, accepts replacement intent on generic spawn, skips adoption, and performs best-effort raw-ID cleanup. | +| `src/preload/api-types.ts` | Adds `freshSpawnForUnreachablePtyId` to generic spawn. | +| `src/preload/index.ts` | Forwards that generic spawn option. | +| `src/renderer/src/components/terminal-pane/pty-connection.ts` | Passes the old `sessionId` as replacement authority. | +| `src/renderer/src/components/terminal-pane/pty-transport-types.ts` | Adds the option to the generic transport contract. | +| `src/renderer/src/components/terminal-pane/pty-transport.ts` | Forwards it to generic spawn and suppresses telemetry with saved startup. | + +Why it was rejected: + +1. Raw PTY ID is not process identity; same-ID/different-incarnation leases and + runtime owners collapse. +2. Renderer input becomes replacement authority on a broad generic IPC. +3. Grants have no TTL, sender binding, one-shot operation state, reload + invalidation, or post-spawn revalidation. +4. Concurrent pane reservations can return another operation's result rather + than re-resolving the caller's intent. +5. Binding and lease changes flush separately, so no atomic replacement exists. +6. Provider output can reach the old model before persistence/runtime commit. +7. Generic spawn still accepts renderer-derived environment and other startup + data, so it is not a guaranteed blank shell. +8. Runtime pane ownership is registered, not exactly transferred; lookup can + continue returning the old record. +9. Renderer callbacks remain authoritative after dispose or a newer attempt. +10. Failure cleanup calls ID-only shutdown and can kill the wrong incarnation. +11. The grant is minted on only one attach-failure path, while the UI action can + be published from other paths, leaving a visible dead action. +12. Replacement intent leaks into `PtySpawnOptions`-adjacent contracts, making + remote-wire and mixed-version reasoning unnecessarily dangerous. + +No uncommitted tests cover this WIP, and no test was run against it. + +Remove only these WIP edits with `apply_patch`. Do not use `git reset`, +`git checkout --`, or another broad restoration command in this dirty worktree. + +## Round-6 independent review result + +Three read-only reviews converged: + +- **Relay/wire review:** request changes. It identified raw-ID identity, + ambiguous cleanup, missing atomic Store commit, precommit output publication, + broad IPC authority, incomplete blank-shell enforcement, and wire- + compatibility blockers. +- **Targeted transaction review:** recommended a dedicated IPC, owner-keyed + mutex, token-keyed idempotency, combined Store transaction, reconnect CAS, + post-image inspection on flush error, and deterministic race tests. +- **Final readiness audit:** request changes. It independently found the same + persistence/runtime/grant/incarnation/renderer/cleanup defects and one hard + feasibility boundary: existing SSH shutdown is raw-ID-only. + +All three reviews were read-only. They ran no tests or builds and changed no +files. + +## Approved bounded redesign + +### 1. Main-issued replacement ticket + +When main classifies an attach as unreachable but not proven dead, return a +typed local result containing an opaque ticket. The ticket is authority, not a +renderer-supplied PTY ID. + +Bind it to: + +- the issuing `webContents`/sender; +- connection and provider generation; +- worktree or folder-workspace identity; +- tab, leaf, and pane key; +- exact old application PTY ID and provider-native ID; +- persisted and runtime incarnation IDs; +- exact active lease identity; +- issuance generation and short expiry; +- a random operation ID; and +- state `issued | running | committed | rejected | unresolved` plus the + idempotent result where applicable. + +Invalidate tickets on renderer reload/destruction, provider replacement, +connection re-registration, expiry, or exact-owner change. A consumed or +rejected ticket must not become valid again after any request was dispatched. + +### 2. Dedicated local IPC + +Add a local-only API such as: + +```ts +pty.replaceUnreachablePane({ ticketId, cols, rows }) +``` + +It should return a structured result such as: + +```ts +{ + ;(ptyId, incarnationId, operationId) +} +``` + +It must not route through generic `pty:spawn` or `PtyTransport.connect`, and it +must not add fields to provider, SSH, relay, paired-runtime, or stream payloads. +Authenticate the sender as the main renderer window before ticket lookup. + +### 3. Shared owner lock and idempotency + +Use one host/worktree/pane owner mutex for: + +- ordinary pane spawn/adoption; +- unreachable-pane replacement; and +- relay reconnect's final owner activation. + +Each waiter must re-resolve its own intent after acquiring the lock. It may not +return another operation's result merely because it waited on the same lock. + +Use the ticket's operation ID for idempotency. A double-click, lost response, +or retry while running awaits the same operation and returns the same result. +It must create at most one shell. + +### 4. Main-constructed blank spawn + +Under the owner lock, re-read the workspace and re-derive CWD. Repeat folder- +workspace path validation at that moment; do not trust the path captured when +the ticket was issued. + +Construct provider spawn options from a narrow main-owned allowlist. Exclude: + +- command and command delivery; +- `sessionId`, `attachOnly`, or resume metadata; +- launch config, token, agent, or telemetry; +- arbitrary renderer environment or environment deletion; +- shell override; +- startup command delivery; and +- sequenced-startup environment. + +Only the validated pane/workspace identity, dimensions, and provider-required +blank-shell metadata may cross the provider boundary. + +### 5. Exact incarnation lease identity + +Lease identity for this transaction must include incarnation, not only +`(targetId, ptyId)`. Old `pty-1/inc-A` and new `pty-1/inc-B` must coexist as: + +- old exact lease: expired/unbound; and +- new exact lease: attached/bound. + +Every mark, remove, attach, rollback, and reconnect CAS touched by replacement +must name the exact lease incarnation. Preserve compatibility with persisted +legacy rows that lack optional incarnation data; unknown identity may not +authorize destructive cleanup. + +### 6. One Store transaction + +Add one Store method, for example `replaceUnreachableSshPaneOwner`, that under +one mutation and one flush: + +1. exact-CASes the old durable pane binding; +2. exact-CASes the old active lease; +3. installs the new binding and incarnation; +4. installs the new exact attached lease; +5. expires the exact old lease without shutting down its process; +6. advances topology and lease mutation versions, including affected already- + expired siblings; and +7. flushes once. + +Snapshot every mutated in-memory field before starting. + +Because durable-file replacement renames the new image before directory fsync, +a thrown flush is not proof that disk stayed old. Inspect the persisted post- +image before deciding what happened: + +- **Old image:** restore memory and clean only a provably exact new process. +- **New image:** treat the transaction as committed. +- **Mixed or unreadable:** kill neither process; mark the operation unresolved, + quarantine publication, and reconcile from disk/provider evidence. + +### 7. Runtime ownership replacement + +Add a non-exit runtime primitive along these lines: + +```ts +runtime.replaceTerminalPaneOwner({ + paneKey, + worktreeId, + expected: { ptyId, incarnationId }, + replacement: { ptyId, incarnationId } +}) +``` + +It must: + +- exact-CAS the current owner; +- clear the old record's pane ownership without `onPtyExit`; +- leave the old process live and unbound; +- move the pane/leaf/handle lookup to the replacement; +- invalidate old handles so they cannot silently target the successor; and +- correctly reset ID-keyed state when raw PTY ID is reused with a new + incarnation. + +Prepare and validate runtime replacement before the Store commit. Make the +final in-memory step synchronous and designed not to fail. If an unexpected +post-durable failure still occurs, never roll durable ownership back to the old +process and never kill either shell; quarantine and retry publication/ +reconciliation idempotently. + +### 8. Quarantine provider output + +Capture the provider object and generation before spawn and recheck them after +every await. Quarantine output for the exact +`{ provider generation, ptyId, incarnationId }` until durable and runtime +replacement commit. + +Only then activate source delivery and publish the new runtime owner. A new +shell reusing the old raw ID must never send bytes into the predecessor model. + +### 9. Fence relay reconnect + +Relay reconnect must acquire the same owner lock after network attach and, +before changing ownership or delivery, exact-CAS: + +- the current pane binding; +- the lease incarnation; and +- the provider/connection generation. + +Only a winning reconnect may set ownership, restore incarnation, activate +source delivery, or register runtime state. A reconnect for the predecessor +must be unable to publish it after replacement commits. + +### 10. Renderer adoption rules + +The renderer calls only the dedicated API. Guard every completion/failure by: + +- connection object not disposed; +- current transport identity; +- current action generation; and +- matching ticket/operation generation. + +Accept same-raw-ID/new-incarnation as a real successor. Adopt only the exact +structured committed result. A stale or disposed callback does nothing: it does +not clear a binding, republish the card, or kill a result. Main owns the durable +transition, so the renderer must never clear the old durable binding after +success. + +## Hard cleanup boundary and selected policy + +Current provider and SSH relay shutdown APIs identify only a PTY ID. If spawn +returns `pty-1/inc-B`, then reconnect races and `pty-1` may refer to a different +incarnation by the time rollback runs. Calling `shutdown('pty-1')` is not exact +cleanup. + +The safe policy for this PR is: + +- do not add replacement intent to the remote wire; +- use existing capability-gated create-operation replay and host-attested + incarnation when they provide conclusive identity; +- clean a failed new shell only when its exact incarnation is provable through + a provider-owned rollback handle or equivalent existing evidence; +- otherwise park/quarantine the ambiguous shell for reconciliation; +- never blind-retry an ambiguous legacy spawn; and +- never risk killing the incumbent merely to avoid a leak. + +Legacy relays without create-operation replay or host-attested incarnation must +fail closed or leave the outcome unresolved. If implementation cannot satisfy +this with current local/provider contracts, stop at the design gate. Do not +silently add `expectedIncarnationId` to remote shutdown; that is a separate, +capability-negotiated wire design and review. + +## Transaction outcome table + +| Outcome | Durable owner | Process action | Publication | +| -------------------------------------------- | ----------------- | ------------------------------------------------- | ------------------------------------- | +| Ticket/pre-spawn validation or fence failure | Old | None | Reject | +| Spawn failure before dispatch | Old | None | Reject; ticket may be safely terminal | +| Spawn response ambiguous after dispatch | Old or unresolved | No blind retry or ID-only shutdown | Park/reconcile | +| Known new shell, post-spawn CAS loss | Winner or old | Stop only the exact new incarnation when provable | Publish nothing | +| Store commit succeeds | New | Leave old process alive; expire exact old lease | Publish new | +| Flush throws; disk has old image | Old | Clean exact new only when provable | Reject | +| Flush throws; disk has new image | New | Leave both processes | Publish new | +| Flush throws; disk mixed/unreadable | Unresolved | Kill neither | Quarantine/reconcile | +| Post-commit runtime/publication failure | New | Never roll back or kill | Retry publication idempotently | + +## Required deterministic oracles + +These are completion requirements, not optional follow-ups. + +### Main transaction + +- Seed an exact failed owner, ticket, binding, and lease. +- One explicit replacement call makes exactly one provider fresh spawn. +- Provider options contain no session, attach, command, startup, resume, + renderer env, launch metadata, or telemetry. +- The same pane remains; the old shell receives no shutdown or synthetic exit. +- Exactly one combined Store handoff occurs and runtime lookup resolves the new + owner. + +### Authorization and lifecycle + +- Missing, expired, replayed, wrong-sender, wrong-host, wrong-worktree, + wrong-pane, and renderer-reload tickets reject before provider spawn. +- Changed/missing binding, persisted/runtime incarnation, lease, provider, or + generation rejects before mutation. +- Folder-workspace path changes after ticket issuance are revalidated under the + lock. + +### Identity and races + +- Old and new may both be raw `pty-1` with distinct incarnations. +- Double-click and lost-response retry create one operation and one shell. +- Ordinary spawn racing replacement does not inherit the replacement result. +- Reconnect before spawn yields no spawn. +- Reconnect after spawn cannot republish the predecessor. +- Provider replacement during every await prevents an unsafe commit. +- A delayed old-incarnation exit cannot affect the new incarnation. + +### Persistence and durability + +- Success survives save/reload with exactly one flush. +- Old exact lease is expired, new exact lease attached, and new binding exact. +- Pre-rename failure restores old memory/disk state. +- Post-rename failure recognizes the new image as committed. +- Mixed/unreadable post-image kills neither process. +- Duplicate-retirement rollback cannot revive an already-expired sibling. +- Same raw PTY ID with different incarnations remains representable. + +### Runtime and renderer + +- Exact non-exit runtime rebind moves pane/leaf/handle lookup to the successor. +- The old owner remains live but unbound and receives no exit. +- Disposed, stale-generation, late-success, and late-failure callbacks cannot + spawn, clear, kill, or republish over newer state. +- Same-ID/new-incarnation structured results are adopted. +- A disposed transport never kills a main-committed replacement. + +### Compatibility and E2E + +- No replacement field appears in provider, SSH, relay, runtime RPC, paired + RPC, or stream payloads. +- Legacy relay degradation is fail-closed/unresolved, never destructive. +- Current-to-release and release-to-current terminal compatibility suites stay + green. +- Unfix the decisive Docker test and add a deterministic production seam that + leaves the target connected while one pane attach is unreachable. +- The E2E must prove old PID plus start ticks stay alive, exactly one blank + shell is added, pane/leaf count is unchanged, new durable `(id, +incarnation)` is bound, new lease is attached, old exact lease is expired, + and no agent/resume/startup transcript is duplicated. + +## Remaining work, in dependency order + +### Phase 0 — resume safely and freeze the invariants + +1. Read this document and the repository `AGENTS.md` instructions. +2. Run the checkpoint commands below. +3. Confirm the PR ref remains at the recorded SHA and inspect any newly arrived + changes before editing. +4. Treat ambiguous cleanup as unresolved rather than adding a remote wire field. +5. If that constraint becomes infeasible, stop and return to the user instead + of widening scope. + +### Phase 1 — remove the rejected WIP + +Use `apply_patch` to remove only the current six-file +`freshSpawnForUnreachablePtyId` and grant-map edits. Preserve every committed +change and any unrelated user work. Run `git diff --check` and verify the only +remaining change is this handoff document before beginning the replacement. + +### Phase 2 — build the identity and persistence foundation + +1. Add incarnation-aware exact lease identity with legacy-row compatibility. +2. Add exact lease lookup/mark/remove APIs required by replacement and + reconnect. +3. Add the single Store replacement transaction and one-flush rollback state. +4. Add post-image inspection for pre-rename, post-rename, and mixed/unreadable + outcomes. +5. Write persistence tests first and demonstrate the intended failure on the + current implementation. + +### Phase 3 — build runtime and coordination primitives + +1. Add the exact non-exit runtime pane-owner replacement primitive. +2. Add the host/worktree/pane owner mutex shared by normal spawn, + replacement, and reconnect final activation. +3. Add operation-token idempotency independent from that lock. +4. Update reconnect to revalidate exact binding, lease incarnation, and + provider generation after it acquires the lock. +5. Add same-ID/new-incarnation and delayed-old-exit tests. + +### Phase 4 — implement the main replacement transaction + +1. Issue typed, sender-bound, expiring, one-shot tickets from every renderer + path that can publish the unreachable action. +2. Add the dedicated preload/main IPC and main-window sender check. +3. Re-derive CWD and validate folder workspaces under the lock. +4. Construct the blank provider spawn from the main allowlist. +5. Capture provider generation and quarantine exact new output. +6. Revalidate after every await; prepare runtime; execute the Store commit; + finish runtime activation; publish output/result. +7. Implement all transition-table outcomes without ID-only cleanup. + +### Phase 5 — adopt through the renderer + +1. Remove replacement from generic transport/spawn types. +2. Thread the typed ticket and structured committed result through the + disconnected action only. +3. Add disposed/current-transport/action-generation guards. +4. Remove renderer-side binding clearing or committed-result killing. +5. Verify UI layout, copy, and behavior through Electron Playwright CDP as + required by repository instructions. + +### Phase 6 — validate and review once + +1. Run the focused deterministic suite. +2. Make the Docker E2E inducible, remove its unconditional `fixme`, and prove + it fails for the intended reason on the unfixed candidate before claiming + it as evidence. +3. Run typecheck, lint, full unit tests, build, reliability gates, and relevant + SSH/daemon/cross-version regressions. +4. Run independent repository and release-readiness reviews, including + security, performance, mobile/backcompat, Windows, Linux/glibc, SSH, folder + workspace, and provider-neutrality coverage. +5. Resolve every P0/P1 and relevant P2. If another architectural invariant + fails, pause instead of entering an unbounded seventh patch loop. + +### Phase 7 — deliver + +Only after the implementation and reviews are clean: + +1. Commit the replacement work. +2. Push explicitly to + `origin/nwparker/sta-3077-d-affordance-and-review`. +3. Update PR #13326's body with the transaction, compatibility behavior, and + exact validation receipts. +4. Resolve the seven saved review threads only when their findings are actually + addressed. +5. Request `@coderabbitai review` and monitor CI to completion. +6. Use the `orca-linear` workflow to post one concise STA-3077 completion + update and attach the PR if needed. + +## First safe resume commands + +Run from the primary worktree before editing: + +```bash +git status --short --branch --untracked-files=all +git rev-parse HEAD +git rev-parse origin/nwparker/sta-3077-d-affordance-and-review +git rev-parse origin/main +git rev-list --left-right --count origin/main...HEAD +git diff --stat +git diff --check +``` + +Expected before any external state changes: + +- HEAD and the PR ref are both `df6edfcebd2ea401a6feda1fccf31189e57eceda`; +- the six rejected production-file edits are present; +- this handoff file is the only additional local artifact; and +- `git diff --check` exits 0. + +Do not use the configured upstream to infer PR state. + +## Suggested validation commands after implementation + +Adjust the focused file list only when the final implementation clearly moves +the covered behavior. Record exact commands and outcomes in the PR. + +```bash +pnpm exec vitest run --config config/vitest.config.ts \ + src/main/ipc/pty.test.ts \ + src/main/persistence.test.ts \ + src/main/persistence-ssh-lease-termination.test.ts \ + src/main/runtime/orca-runtime.test.ts \ + src/main/ssh-reattach-pane-cardinality.test.ts \ + src/main/ssh/ssh-relay-session.test.ts \ + src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts \ + src/main/ssh/ssh-relay-session-reattach-pane-fence.test.ts \ + src/renderer/src/components/terminal-pane/pty-connection.test.ts \ + src/renderer/src/components/terminal-pane/pty-transport.test.ts \ + src/renderer/src/components/terminal-pane/TerminalPaneDisconnectedBanner.test.tsx \ + --reporter=dot + +pnpm typecheck +pnpm lint +pnpm test +pnpm build +``` + +For the Docker product oracle, use the repo's Electron Playwright configuration +with `ORCA_E2E_SSH_DOCKER=1` after adding the deterministic induction seam and +removing the test's unconditional `fixme`. Keep the run POSIX-only as the +existing Docker fault harness requires. + +Run the current↔release cross-version terminal suite and the relevant Docker +SSH cardinality, `MaxSessions=1`, and two-host scripts as part of broad +regression coverage. + +## Validation record at pause + +### Current redesign/WIP + +No product validation was run after the rejected six-file WIP was introduced. +No product validation was run during the three final read-only audits or while +writing this handoff. Therefore this document claims no current test, typecheck, +lint, build, Electron, Docker, cross-version, or packaging pass. + +### Read-only checkpoint commands run for this handoff + +The following repository inspections completed successfully: + +```bash +git status --short --branch +git status --short --branch --untracked-files=all +git rev-parse HEAD +git branch --show-current +git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' +git rev-parse origin/nwparker/sta-3077-d-affordance-and-review +git rev-parse origin/nwparker/sta-3077-reattach-pane-cardinality +git rev-parse origin/main +git rev-list --left-right --count origin/main...HEAD +git merge-base origin/main HEAD +git log --oneline --decorate -12 +git reflog --date=iso +git diff --stat +git diff --name-status +git diff --check +``` + +Observed results are recorded in the repository checkpoint above. In +particular, `git diff --check` exited 0. + +Historical validation details are preserved in `goalposts.md` and +`resume-plan.md`. Those receipts belong to their recorded SHAs and must not be +reported as validation of the final replacement candidate without rerunning +them. + +## Security, compatibility, migration, and release risks + +- **IPC authority:** a renderer-supplied PTY ID is forgeable/piggybackable; + tickets must be opaque, sender-bound, short-lived, one-shot, and revalidated. +- **Same-ID reuse:** raw PTY ID cannot distinguish an incumbent from a + successor. Every destructive or ownership operation needs exact incarnation. +- **Durability:** a thrown fsync after rename can leave the new image on disk. + Blind in-memory rollback can diverge from restart state. +- **Remote ambiguity:** ID-only shutdown cannot safely clean same-ID reuse. + Prefer a visible/reconcilable leak to killing an unproven process. +- **Output isolation:** precommit bytes from a successor can corrupt the old + pane model unless quarantined by provider generation plus incarnation. +- **Mixed versions:** clients and hosts update independently. Keep replacement + local; any future exact-shutdown wire field needs capability negotiation and + both-direction live skew tests. +- **Legacy persisted rows:** missing incarnation is unknown, not permission to + mutate or delete. Migration must be additive and old-reader-safe. +- **Folder and SSH workspaces:** re-resolve current paths and host generation + under the lock; neither git worktree presence nor local filesystem access may + be assumed. +- **Cross-platform:** preserve macOS, Linux/glibc floor, Windows, WSL, path, and + shortcut rules even though the Docker fault harness is POSIX-only. +- **Performance:** avoid global scans, unbounded ticket/operation maps, + repeated fsyncs, or hot-path lock contention. Bound retention and measure + affected reconnect/spawn paths. +- **Release evidence:** the key E2E remains held. The change is not release- + ready until that product path is deterministic and discriminating. + +## Stop conditions + +Pause and return to the user if any of these occurs: + +- exact cleanup appears to require an unreviewed remote-wire change; +- the Store/runtime transaction cannot distinguish old, new, and mixed durable + post-images; +- replacement requires treating unknown identity as proof; +- the deterministic E2E still cannot enter the actual production state; +- the shared lock introduces a new global serialization or deadlock risk; or +- the next independent review finds another architectural invariant failure. + +The point of this handoff is to prevent another opaque loop: one bounded +redesign, deterministic evidence, one adversarial review, then either delivery +or a principled stop. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/README.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/README.md new file mode 100644 index 00000000000..2dab127658c --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/README.md @@ -0,0 +1,265 @@ +# Terminal session correctness and authority handoff + +> **Status: preserved and paused, not complete, not release-ready.** +> +> The comprehensive program is at **0/8 proven goalposts** and +> **2/13 proven journeys**. No agent may narrow, replace, or mark a goalpost +> complete without the user's explicit approval and the proof named in this +> folder. + +This folder is the sole continuation entrypoint for the work previously called +“React 185” or “terminal session authority.” That shorthand is too narrow: the +program covers terminal identity, ownership, exact operations, reconnect, +delivery, migration, daemon and SSH lifecycle, paired and remote runtimes, +cross-platform compatibility, performance, and removal of superseded code. + +## Read in this order + +1. Read all three preserved source documents with the exact `git show` commands + under [Repository checkpoint](#repository-checkpoint). The normative design, + delivery ledger, and original pause handoff are mandatory, not optional + implementation detail. +2. [`goalposts.md`](./goalposts.md) — the current completion contract, amendable + only by an explicit user decision. +3. [`related-open-work.md`](./related-open-work.md) — live PR/issue overlap and + conflicts. +4. [`resume-plan.md`](./resume-plan.md) — safe continuation order and required + validation receipts. + +The older `terminal-session-authority-handoff-2.md` is useful as an adversarial +report, but it is not authoritative. In particular, its “descoped,” “shipped,” +identity-equivalence, timer, and LOC claims must not be copied as settled facts. + +## Non-negotiable user objective + +Deliver one coherent long-term terminal-session correctness model that: + +- removes the root causes instead of leaving quarantine, retry-window, + sliding-window, optional-metadata repair, or other reconciliation as the + final correctness mechanism; +- never treats missing, unavailable, timed-out, disconnected, or unknown state + as proof that a process is dead or that replacement/destruction is safe; +- works for local terminals, daemon, WSL, direct and nested SSH, paired runtime, + remote server, folder workspaces, floating workspaces, and git worktrees; +- remains correct when clients and hosts update independently; +- works on macOS, Linux at the supported glibc floor, Windows, WSL, and Docker + OpenSSH; +- has no correctness, security, latency, throughput, memory, restore, startup, + backpressure, or large-pane regression; +- finishes with **strictly less aggregate production code than the frozen + pre-program baseline** after all superseded implementations are deleted; and +- is proven through real production paths and discriminating end-to-end + journeys, not inferred from test counts or green CI. + +Correctness and performance cannot be weakened to reach the code-size target. +The code-size target also cannot be waived because a replacement architecture +was added beside the old one. + +## Authority and scope rules + +- Direct user instructions govern scope. +- The original normative design remains the contract except where a later, + explicit user decision changes a named requirement. +- This handoff tightens G6 to **strictly net-negative production LOC** because + the user explicitly asked to end with less production code than the original + baseline. +- The default frozen accounting baseline is + `5ed45739e94bdf6460364e033bfcec9b32c0b42a`, the base recorded by GitHub for + PR #12600. This program subsumes that containment PR. Every later + program-attributable merged prerequisite and every stack layer must be counted + in aggregate; rebasing may not roll the accounting baseline forward and hide + earlier additions. Changing this baseline requires an explicit user decision. +- Focused tests, green CI, a review comment, a behavior-contract document, an + open PR, or a construction milestone cannot amend the design or promote a + release goalpost. +- A replacement design is allowed, but it must map every original invariant, + risk, and journey to an equal or stronger mechanism, close the known liveness + gap, and receive explicit user approval before the ledger changes. +- Only `not started`, `partial`, and `proven` are valid gate statuses. + “Descoped,” “superseded,” and “met for what shipped” are not valid statuses + for G0–G7 under the current objective. +- A narrow incident PR may be independently useful or mergeable. It does not + reduce the comprehensive denominator of eight goalposts and thirteen + journeys. + +## Settled status + +| Scope | Status | Meaning | +| -------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Construction preservation | **Complete locally; not remotely durable** | The 814-path construction tree and the original three authority documents are preserved at local branch `nwparker/react185-authority-snapshot` / `fddb19f6977`. | +| Comprehensive goalposts | **0/8 proven** | G0–G4 and G6 are partial. G5 and G7 are not started. | +| Required journeys | **2/13 proven** | Journeys 1 and 2 have clause-selective discriminating oracles run on every environment they name. The other eleven remain unproven. | +| Current branch / PR #13111 | **Implemented, open, unapproved, incomplete** | Useful narrow SSH containment; not a long-term completion and not merged. | +| PR #13110 | **Open, independent, unapproved** | Useful preload artifact guard; not shipped and has an unresolved major review thread. | +| Less-code gate | **Failed on current candidate** | PR #13111 is net positive; the preserved construction snapshot is net `+60,903` production LOC. | + +The numeric release checkpoint is therefore: + +- **G0:** partial +- **G1:** partial +- **G2:** partial +- **G3:** partial +- **G4:** partial +- **G5:** not started +- **G6:** partial and currently failing its final LOC condition +- **G7:** not started +- **Total:** **0/8 proven, 6/8 partial, 2/8 not started** +- **Journeys:** **2/13 proven** (Journey 1 natively on macOS/Linux/Windows; Journey 2 on macOS/Linux/physical WSL) + +This is the **program artifact ledger**. Its partial G0, G1, G3, and G4 evidence +exists only in the preserved construction snapshot and historical receipts. It +does not mean those implementations exist on the current #13111 branch. The +current candidate contributes credible partial G2 evidence and limited +compatibility/review evidence, but it proves **zero** complete release gates. + +## Repository checkpoint + +Verified before creating this documentation folder: + +- Worktree: + `/Users/nwparker/orca/workspaces/orca/eye-React-185` +- Current branch: `nwparker/sta-3077-reattach-pane-cardinality` +- Current HEAD: `5369479be2953f45cea9ab5cfcde756dd9660548` +- HEAD subject: `fix(pty): let liveness say unknown instead of forcing it to say dead` +- Local `origin/main`: `0d29497f8279e2d4c2d26ffc8f3fb68cee2756a7` +- Merge base: `e6e197feeddd1adda066c5cd22f7ee056a12c8c1` +- Distance from local `origin/main`: 15 commits ahead, 19 behind +- The worktree was clean before this handoff. The expected handoff-only changes + are this folder and its `.gitignore` allow-list entry. +- Preserved construction branch: + `nwparker/react185-authority-snapshot` +- Preserved construction commit: + `fddb19f6977ae4ba4764c32afc9fe104c1ed2549` +- Preservation location: local ref only; the branch has no upstream, tag, or + remote branch containing this commit +- Snapshot status: **unshippable salvage/reference only** + +The exact commit ID is the preservation anchor. Do not checkout, switch, reset, +rebase, commit, or push from the snapshot branch in the primary worktree. Read +its authority documents without switching branches: + +```bash +git show fddb19f6977:docs/reference/terminal-session-authority.md +git show fddb19f6977:docs/reference/terminal-session-authority-delivery.md +git show fddb19f6977:docs/reference/terminal-session-authority-handoff.md +``` + +Mine tests, design arguments, or narrow implementations only through `git show` +or a disposable isolated worktree, and only after verifying that they address a +reachable production path on the current base. A local tag protects against +branch movement and ordinary GC only; it does not survive loss of this machine. +Cross-machine/crash preservation requires a copy-verified off-machine bundle or +an explicitly authorized remote ref. Do not infer permission to push it. + +## Current narrow candidate: what is real + +At current HEAD / PR +[#13111](https://github.com/stablyai/orca/pull/13111): + +- SSH relay reattach passes `mayCreate: false` to stop that call site from + creating durable pane/layout state. +- Duplicate complete pane leases are superseded and excluded from reattach. +- Existing duplicate complete leases are reconciled during reconnect. +- Reattach failure paths require positive evidence before cold respawn. +- PTY inventory can report `unknown` rather than collapsing an unavailable + provider into `false`/dead. +- Focused tests and GitHub checks are green at HEAD. + +These are credible partial G2 improvements. They do **not** establish the +comprehensive design or release gates. + +## Current narrow candidate: what remains unproved or wrong + +- Lease row identity is still `(targetId, ptyId)`. Pane fields remain optional. + Active-pane cardinality is enforced by sibling expiration and a healing scan, + so the end state remains reconciliation-based rather than structurally + pane-keyed. +- Incomplete legacy leases bypass pane arbitration. +- Superseded remote shells are deliberately left running and unreachable. The + PR body acknowledges that the “accumulates unused shells” half of the incident + remains unresolved. +- The repeated-reconnect Docker test still passes with and without the fix: it + is a forward guard, not causal proof. Its sibling in the same spec — 'leaves a + lease whose durable pane is gone unbound…' — was reported as discriminating, + but that DID NOT REPRODUCE on a second machine: with `mayCreate: false` + removed from the reattach call site and the app rebuilt, both tests still + passed. Its induction races `pty:kill` against a severed transport, so when + the kill lands the lease is cleaned up and there is nothing to graft. Treat + both tests as forward guards. No journey is proven. +- The final Docker settle assertion has an unresolved major review thread: a + late pane or shell can appear after the polling assertion has already passed. +- The production-call-site wiring oracle reads source text. It does not execute + the full production reattach path. +- `mayCreate: false` is wired at one production binding call site, not proven + across every recovery/reattach runtime. `removeSshRemotePtyLease` still has one + production caller, the spawn-persistence rollback. +- `WEDGED_DAEMON_GRACE_RETRIES = 11` remains reachable and still permits retry + count to drive daemon replacement after unknown inventory. +- `terminal-input-quarantine.ts` remains reachable. +- No current-tree proof covers physical Windows, WSL, the Linux glibc floor, + paired runtime, remote server, two independent SSH hosts, live mixed-version + peers, or production-scale performance. +- There is no candidate-versus-baseline performance result for the new + per-upsert sibling scan or reconnect healing pass. +- PR #13111 is open, has no approval decision, and is not shipped. + +Current HEAD census against its merge base, before this documentation change: + +| Category | Additions | Deletions | Net | +| --------------------------------------------------- | --------: | --------: | -------: | +| Production source, including a fixture under `src/` | 374 | 65 | **+309** | +| Tests and end-to-end tests | 944 | 30 | +914 | +| Documentation | 146 | 0 | +146 | +| CI/configuration | 43 | 0 | +43 | +| Total GitHub diff | 1,507 | 95 | +1,412 | + +The production source plus Docker runner is net `+350`. Whichever taxonomy is +used, the categories must remain separate and G6 is not proven. + +## Corrections to the previous handoff + +- PRs #13110 and #13111 are **open and green**, not shipped. +- #13110 is implementation-independent from #13111, but emitted-preload safety + remains inside G0/G5/G7 and any retained #13110 production/build logic counts + in the aggregate G6 census. +- The snapshot genuinely failed to wire `mayCreate`, pane-cardinality + arbitration, or a complete shell-lifecycle fix into the affected legacy SSH + path. +- Pane key, PTY ID, incarnation ID, a narrow CAS, and a three-valued daemon + resolver pre-existed and should be reused where their semantics match. +- Existing `connectionId` and `worktreeId` do **not** establish equivalence to a + final-host-minted authority identity and canonical host-local namespace. +- The normative design never banned all timers. It permits bounded waits and + backoff; it forbids elapsed time or retry count **alone** from deciding + identity, liveness, takeover, replacement, or destruction. +- The design does have a liveness gap: a permanently lost retained consumer can + hold compaction at capacity without a sufficiently explicit bounded operator + recovery path. G0 and G3 cannot become proven until that is resolved. +- The claimed approximately 6,500-line comparison implementation has no + reproducible census and cannot justify deleting requirements. + +## Definition of done + +The comprehensive work is done only when all of the following are true on one +rebased, converged candidate SHA: + +- every G0–G7 section in [`goalposts.md`](./goalposts.md) has its named + production implementation and current proof; +- all thirteen required journeys pass with their full oracles; +- each new causal oracle is red on the unfixed baseline and green on the final + candidate; formal verification may supplement but never replace a required + live journey; +- every open incident bound to the mandatory issue-to-journey matrix in + [`related-open-work.md`](./related-open-work.md) passes its discriminating + oracle or is ruled unrelated with explicit evidence and user acceptance; +- correctness, security, wire, migration, platform, packaging, performance, + restore, and scale reviews have no unresolved P0–P2 findings; +- the aggregate production source census is strictly net-negative against the + frozen pre-program baseline, including all program-attributable prerequisite + PRs and stack layers; +- no superseded reconciliation, quarantine, duplicate state machine, legacy + writer, or test fixture remains reachable in production; and +- the user explicitly accepts any deliberate change to the normative design. + +Anything less must be reported as partial, regardless of test count or PR +state. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/RESUME-PROMPT.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/RESUME-PROMPT.md new file mode 100644 index 00000000000..88cff53f68b --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/RESUME-PROMPT.md @@ -0,0 +1,111 @@ +# Resume prompt — terminal session ownership + +Paste the block below into a fresh session. Everything it needs is in the repo. + +--- + +You are taking over an in-flight implementation in this repo. Read these, in +order, before doing anything: + +1. `docs/reference/terminal-session-correctness-handoff-2026-08-07/new-design-goalposts.md` + — the tracked goalposts. This is the contract. Report progress against it. +2. `docs/reference/terminal-session-correctness-handoff-2026-08-07/design-explained.html` + — the design in plain English (open it; it has diagrams). +3. `docs/reference/terminal-session-correctness-handoff-2026-08-07/design-final-detail.md` + — the full detail: record shape, death rule, reattach algorithm, migration + order, and the oracle list. +4. `docs/reference/terminal-session-correctness-handoff-2026-08-07/counsel-design.html` + — how the design was reviewed, and the defects the review found in earlier + shipped work. Read at least the "What I got wrong" section. + +## The problem being fixed + +Reconnecting to an SSH host multiplied a user's terminals (2 → 19 → 20), and a +coding agent could be resumed twice into one transcript. Root cause is not one +bug: it is that ownership bookkeeping is filed under the wrong key and written to +two places, and that the client infers "the program died" from things that do not +prove it. + +The design in one line: **keep our own notes about which terminal is whose, and +never guess whether a program died.** + +## State + +Branch `nwparker/sta-3077-reattach-pane-cardinality`. Landed and committed: + +- `e2524b0472f` — an identity mismatch is no longer read as death (goalpost S1) +- `c51be8072ba` — pane identity is no longer sent on reattach (S2) +- Goalposts, design docs (S6 verdict recorded) + +**3 of 7 step goalposts proven. Net production lines: −24.** + +Two older PRs (#13110, #13111) are **held, unmerged, deliberately**. The owner +decided: no stopgap, get the design right. Do not merge them without being asked. + +## What to do next + +Three goalposts have **failing oracles already written**, each with the exact +production change identified. This is implementation against a fixed target. + +**S3 — a failed reattach must never fabricate an exit.** +Oracle: `src/main/ssh/ssh-relay-reattach-exit-proof.test.ts` (6 red, 2 green). +In `handlePtyReattachFailure` (`src/main/ssh/ssh-relay-session.ts`), the +not-found case currently sends the pane a synthetic `pty:exit { code: -1 }`, +clears provider state, deletes ownership and expires the lease — all claims about +a process we know nothing about. Collapse it into the non-destructive branch that +already exists a few lines above (`restoreRequired = 'reattachAttemptsExhausted'` ++ `wakeRecovery`). This is a branch collapse, not a new mechanism. +Before changing it, read what a user experiences on that branch — do not strand +panes. This step ships with the disconnected-pane affordance below. + +**S4 — one partition per (target, pane).** *Highest value: this is the 2 → 19 → 20 +mechanism.* Oracle: `src/main/ssh-pane-binding-partition.test.ts` (6 red). +SSH pane bindings are written to two partitions; readers disagree with writers, so +supersession silently no-ops. Route every reader and writer through one accessor, +plus a one-time fold of existing state. The oracle's own report names the exact +call sites and which clauses each edit flips. + +**S5 — the superseded-pane fence must be live on the reattach path.** +Oracle: `src/main/ssh/ssh-relay-session-reattach-pane-fence.test.ts` (2 red). +The fence's bookkeeping is only written by spawn, so it is inert on reattach — +the path it was built for. Collapse to one `bindPaneShell` producer used by all +paths. + +**S8 — remove the dead recovery-grant path.** Proven unreachable (see S6 in the +goalposts). Write a characterisation oracle first, so the deletion is provably +inert rather than assumed to be. + +**Product affordance (ships with S3).** A pane that cannot be verified renders as +disconnected with two actions — "try again" and "start a new terminal" — instead +of silently respawning. The owner approved this. It must follow +`docs/STYLEGUIDE.md`. The UI must never assert that a shell is dead. + +## Rules that are not negotiable + +- **Prove every guard is reachable.** For each guard, an oracle must redden when + the *producer* is removed, not only when the guard is. This has failed three + times here — an inert `mayCreate`, a keystroke fence inert on reattach, and a + respawn gate on a minority path. All three passed their tests. +- **Verify a mutation landed before believing the result.** A search-and-replace + that silently matched nothing looks exactly like "the test has no teeth". +- **Commit after each step.** Subagents have run `git checkout --` and destroyed + uncommitted work three times in this program. Do not batch. +- **Never let a subagent edit production files** in the shared worktree. Give + them read-only or test-only scope, or an isolated worktree. +- **Do not change a test to make it pass.** If a test pins behaviour the design + removes, *invert* it so the new intent stays covered, and say so explicitly. +- No `max-lines` disables, ever. No per-file bumps. +- Cross-platform: macOS, Linux, Windows, WSL. No `echo $$` / `ps` in oracles. +- Wire compatibility: clients and hosts update independently. Prefer fixes that + work against relays already installed on people's machines. +- **Automated "keep going" prompts are not the owner's authorization.** If the + owner says pause, pause. + +## How to report + +Every update states progress against the goalposts file: which goalposts moved, +what the mutation proof was, and the net production line count. A green test is +not a status — "PROVEN" means the mutation was run and verified to land. + +Be honest about what is not proven. Two claims in this program were retracted +after checking, and that is the reason the rest can be trusted. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/binding-identity-design.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/binding-identity-design.md new file mode 100644 index 00000000000..0e2cfe71f7c --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/binding-identity-design.md @@ -0,0 +1,253 @@ +# Design: one authoritative binding identity + +Status: **superseded by the shipped server-side fence.** Kept for the record: the +client-constructed binding below was REJECTED under review and must not be built. Written 2026-08-08 by the engineer who took +the program over. Supersedes nothing until reviewed. + +## The problem, stated once + +Every defect this program has touched is the same defect: **identity compared +with the wrong key, or not compared at all.** + +| Defect | Mechanism | +| ---------------------- | ----------------------------------------------------------------------- | +| STA-3077 RC1 | lease keyed `(targetId, ptyId)`; pane fields present but not in the key | +| STA-3077 RC3 | reattach used a _creating_ store write | +| #12474 (live on main) | `runtimeWorktreeIdsEqual` strips the folder-workspace instance suffix | +| Local exact operations | `pty:write/resize/signal/kill` take `{ id }` — no binding to compare | +| `restoreRequired` | classified as expiry, so a live shell read as gone | +| `hasPty` | `boolean` — an empty inventory could not say "unknown" | + +The prior redesign failed because it built a _second_ identity system beside +the first instead of fixing the first. It reached +60,903 production LOC and +fixed none of RC1–RC3. + +## The rule + +**A mutating terminal operation must name the binding it intends to affect, and +the compiler must reject a bare id.** + +Not a new subsystem. A type, one comparison, and a signature change. + +## 1. `PtyBinding` — one branded type + +```ts +declare const bindingBrand: unique symbol + +export type PtyBinding = Readonly<{ + hostId: ExecutionHostId // exists — LOCAL_EXECUTION_HOST_ID | ssh: + worktreeId: WorktreeId // exists — `${repoId}::${path}[::workspace:]` + paneKey: PaneKey // exists — `${tabId}:${leafId}`, already branded + ptyId: string // exists + incarnationId: PtyIncarnationId // exists — already branded +}> & { readonly [bindingBrand]: true } +``` + +Every field already exists and is already persisted. Nothing is invented. + +Construction is the whole point: `PtyBinding` is producible **only** by +`bindingFromAuthority()` — reading the durable store, a spawn result, or an +attach reply. There is no public constructor from loose strings, so a caller +cannot fabricate one, and `as PtyBinding` is banned by lint. + +## 2. Mutating IPC carries the binding + +Today, on the local path: + +```ts +pty: write({ id, data }) +pty: resize({ id, cols, rows }) +pty: signal({ id, signal }) +pty: kill({ id }) +``` + +There is no fence to test because there is nothing to compare. That is a +production gap, not a test gap. + +After: + +```ts +pty: write({ binding, data }) +pty: resize({ binding, cols, rows }) +pty: signal({ binding, signal }) +pty: kill({ binding }) +``` + +The handler resolves the binding against the authoritative record and rejects a +mismatch — the same compare-and-swap `persistPtyBinding` already performs for +`expectedBinding`. A stale renderer cannot reach a successor pane or a reused +PTY id, which is invariants 1–4 of the original design, enforced rather than +asserted. + +**Compatibility:** the ID-only channels stay for one release behind the existing +capability negotiation, since clients and hosts update independently. They are +marked deprecated, are not reachable from authoritative paths, and are deleted +in the release after — that deletion is where the LOC comes back. + +## 3. One comparison, not twenty-six + +```ts +export function bindingsEqual(a: PtyBinding, b: PtyBinding): boolean +export function sameNamespace(a: PtyBinding, b: PtyBinding): boolean +``` + +Delete the hand-rolled comparisons. `runtimeWorktreeIdsEqual` — the #12474 bug — +is one of them; ~26 repeat a host-id/namespace-id comparison inline. Each +hand-rolled copy is a future drift, and #12474 proves drift already happened. + +## 4. Three-valued liveness + +Landed (`5369479be29`). `hasPty: boolean | null`, `null` never authorizes +destruction. + +## What this deletes + +| Target | Est. LOC | +| ----------------------------------------------------------------- | -------: | +| ID-only IPC channels + handlers (release after next) | ~250 | +| Hand-rolled identity comparisons (~26 sites) | ~180 | +| `pty-source-replay-index.ts` (done) | 201 | +| Inference sites that exist only because a binding was unavailable | ~200 | + +Net direction is negative once the deprecated channels go. It is net-positive in +the release that adds the type, and the recorded G6 decision permits that when +justified. + +## What this deliberately does not build + +No durable journal, no per-consumer cumulative cursors, no cryptographic device +principals, no parallel authority service. Verified against mature prior art: +bounded replay plus lifecycle-in-the-attach-reply is what shipping systems use, +and their entire persistent-terminal subsystem is ~6,500 LOC. + +If a reviewer can name a concrete event sequence where bounded replay loses or +double-applies an outcome, that conclusion changes. Nobody has yet. + +## How each claim gets falsified + +| Claim | Oracle | +| ---------------------------------------- | ---------------------------------------------------------------------- | +| A stale op cannot reach a successor pane | Send a captured binding after the pane is recreated; must be refused | +| A stale op cannot reach a reused pty id | Same, after incarnation change | +| Same-path workspaces do not collide | The 5 skipped tests in `workspace-namespace-terminal-identity.test.ts` | +| Reattach never creates | Proven, discriminating (`ed10a467883`) | +| Unknown never destroys | Revert three-valued `hasPty`; daemon spec reddens | + +Every row must fail with its guard removed, verified under an isolated +`TMPDIR` — the e2e harness keys its seeded-repo pointer on a machine-global +tmpdir path, so a shared machine can both fabricate and mask a red. + +--- + +# Post-review record (2026-08-08) + +## The proposal above was rejected, correctly + +Verified against the code, three load-bearing claims in it were false: there is +no `WorktreeId` type; `PtyIncarnationId` is a bare `string` alias, not branded; +and `incarnationId` is optional in the store and never reaches the renderer, so +the side asked to construct the binding cannot. It was also a _second_ identity +comparison beside `resolveStablePaneOwner` (`src/main/ipc/pty.ts:647`), which +already resolves pane ownership against runtime and store and already throws +`terminal_pane_owner_conflict` — with 9 call sites, all on spawn/adopt, none on +a mutating handler. The fence existed; it was not being called. + +## What shipped instead + +`isSupersededPtyId` in `src/main/ipc/pty.ts`, consulted by `pty:write`, +`pty:writeAccepted`, `pty:resize` and `pty:signal`. Main keeps `ptyPaneKey` and +`paneKeyPtyId` in lock-step, so their disagreement is proof the caller's id was +superseded. No wire change, no renderer change, nothing added to the input +payload. `pty:kill` is deliberately exempt: a superseded PTY is orphaned and +reclaiming it is the point. + +## Peer review of that shape + +Four comparable agent IDEs were studied. The verdict was to keep this shape. +None sends a composite identity per keystroke; the one that fences keystrokes +sends a single opaque server-minted scalar. The best peer formulation is _keep +the id as the sole lookup key and make the second field a rejection predicate, +never a key component_ — which is what this does, with the owner read from +authority rather than accepted from the caller. + +## Known gap, stated precisely + +**The fence compares a binding, not an incarnation.** If a pane respawns under +the _same_ ptyId, `paneKeyPtyId.get(paneKey) === ptyId` still holds and a write +composed for the dead shell passes. + +The obvious remedy — mint a fresh ptyId on every spawn — is wrong here. +`ptySessionIdForAgentCreateOperation` (`src/main/daemon/pty-session-id.ts:26`) +is deterministic _by design_ so a replayed agent-create is idempotent rather +than spawning a second shell. Randomising it would trade this narrow gap for a +duplicate-spawn bug, which is worse. + +So the residual exposure is one path: an agent-create PTY dies, the same +operation is replayed, the id is reproduced, and a caller holding a pre-death +reference writes into the successor. Closing it needs the caller to carry the +incarnation — the rejected proposal — or a per-attachment token, which is a wire +change. Neither is justified by evidence today. Recorded rather than hidden. + +## Adopted from the peer review + +- The "no binding recorded" branch is an explicit, commented decision (permit), + not an accident — an omitted guard on an optional field is exactly how one + peer reintroduced this defect class. +- A classifier's default must be non-destructive: unknown resolves to reattach, + and only a positive "session not found" authorises a respawn. + +## Not yet adopted, ranked + +1. Typed end-reason recorded at end time (`detached` vs `terminal-exited`), so a + user quit is not a resume candidate. Aimed squarely at duplicate resume. +2. Compare-and-swap before any _delayed_ destructive write. Three-valued probes + stop us acting on unknown; CAS stops us acting on stale-known. +3. Derive the pane inventory from the authority snapshot rather than merging into + a local store. A projection cannot grow; an accumulator can — which is what + 2 -> 19 -> 20 was. +4. Durable intent-to-kill, since kill is the reclamation path for orphaned leases + and a one-shot renderer broadcast should not be its only chance. + +--- + +# Duplicate agent resume: why I did not add the fix I recommended + +Adoption item 1 was a typed end-reason recorded at end time — `detached` (the +user quit; not a resume candidate) versus `terminal-exited` (it died under the +agent; resumable) — on the grounds that a boolean `ended` cannot express the +difference, which is why systems keep resuming things they should not. + +I went to implement it and stopped, because the codebase already contains that +idea three times over. + +`SleepingAgentSessionRecord` (`src/shared/agent-session-resume.ts`) carries: + +- `origin?: 'worktree-sleep' | 'quit' | 'live'` — added so worktree activation + would not launch a tab that a warm reattach had already restored (#5232); +- `restoreOnTabOpenOnly?: boolean` — added so a mobile wake would not background + mount every slept tab and respawn the workspace the user just slept (#11598); +- `automaticResumeBlockedBy?: 'legacy-orchestration-worker'` — added so a + relaunch could not race a durable orchestration assignment. + +Three fields, three incidents, one defect: something resumed that should not +have. They are consulted at 22 non-test sites. A fourth flag — however well +typed — is the fifth containment cycle, which is the failure pattern this +program exists to break. + +The peer designs that do not have this bug do not have a better flag. They have +a different shape: + +1. **Nothing resumes automatically.** Resume is a button. On click it resumes + into a _brand-new terminal id_, re-points the pane, then kills the old + terminal — so two live agents for one pane never exist even transiently. +2. **Two-agents-in-one-terminal is unrepresentable.** The terminal id is the + agent binding's primary key with a cascade to the session row, and live reads + inner-join on the session being active — so a dead terminal's agent cannot + appear in a read no matter how the terminal died. + +Neither is a 30-line change here, and (1) is a product decision about whether +automatic resume stays a feature. That belongs to the user, not to me. + +What is safe to say: the next duplicate-resume incident should not be answered +with a fourth predicate on this record. The record already proves that approach +does not converge. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/counsel-design.html b/docs/reference/terminal-session-correctness-handoff-2026-08-07/counsel-design.html new file mode 100644 index 00000000000..34c224c6352 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/counsel-design.html @@ -0,0 +1,278 @@ + + + + + + Design Counsel — Terminal Session Ownership + + + +
+
+

Design Counsel — Terminal Session Ownership

+

Three review rounds across two models, an adversarial fact-check, and a close-out · the design that emerged is not the one I proposed

+
+ +
+
1
Live bug found
+
2 → 1
Durable records
+
3
Review rounds
+
78 / 12
Facts right / wrong
+
4
Unresolved conflicts
+
~900–1250
Lines deleted
+
+ +
+

The headline

+

The counsel found a live duplicate-agent bug reachable from a shipped gesture, and then something worse: respawn is reachable down at least five paths, and the proof gate I shipped sits on only one of them — not the primary one. Detaching a pane into a new tab makes a healthy remote shell report as dead, and the client starts a second one with agent resume while the original keeps running.

+
+ +

1 · How the counsel ran

+
+
Process and convergence⤢ zoom
+

Round 1

Grok · 10 findings

Opus · 8 findings

GPT seat · empty

shared brief
verified facts vs unverified leads

synthesis
both models independently say:
one record, not two

Round 2 · Grok 6 · Opus 7
→ key by leafId, not paneKey

Round 3 · Grok 5 · Opus 5
→ delete attach identity entirely

clean-check + fact-check

close-out
C1–C5

Round 1

Grok · 10 findings

Opus · 8 findings

GPT seat · empty

shared brief
verified facts vs unverified leads

synthesis
both models independently say:
one record, not two

Round 2 · Grok 6 · Opus 7
→ key by leafId, not paneKey

Round 3 · Grok 5 · Opus 5
→ delete attach identity entirely

clean-check + fact-check

close-out
C1–C5

+
+

The GPT seat returned nothing in all three rounds and was dropped. Grok ran through its CLI; the wrapper was instructed to report a failure rather than author findings, so its participation is real rather than assumed. Findings fell 10 → 6 → 5 and 8 → 7 → 5 across rounds — converging, not exhausted.

+ +

2 · The live bug

+

Four independently reasonable decisions compose into a shell-killer.

+
+
Detach a pane → duplicate agent⤢ zoom
+

user detaches a pane
into a new tab
shipped gesture

tabId changes;
relay still holds the old one
frozen at spawn

reattach → relay compares
and throws
PTY "x" not found (identity mismatch)

isSshPtyNotFoundError
regex /PTY ".+" not found/
matches

re-emitted as
SSH_SESSION_EXPIRED

isProvenSshSessionGoneError
returns true

clear binding →
startFreshColdRestoreAgentResume

second shell + SECOND AGENT RESUME
original shell still running

user detaches a pane
into a new tab
shipped gesture

tabId changes;
relay still holds the old one
frozen at spawn

reattach → relay compares
and throws
PTY "x" not found (identity mismatch)

isSshPtyNotFoundError
regex /PTY ".+" not found/
matches

re-emitted as
SSH_SESSION_EXPIRED

isProvenSshSessionGoneError
returns true

clear binding →
startFreshColdRestoreAgentResume

second shell + SECOND AGENT RESUME
original shell still running

+
+

The error string says the PTY was not found. It was found — that is how its identity got compared. The word “not found” is doing double duty for “absent” and “present but mismatched”, and a regex cannot tell them apart.

+
// my classifier — the last link
+export function isProvenSshSessionGoneError(error: unknown): boolean {
+  if (message.includes(SSH_SOURCE_RESTORE_REQUIRED_ERROR)) return false
+  return message.includes(SSH_SESSION_EXPIRED_ERROR) || /PTY ".+" not found/i.test(message)
+}
+// two functions away, unused by me:
+export function isSshPtyIdentityMismatchError(error: unknown): boolean
+
+

Why I missed it

+

I wrote this file to enforce “unknown is not dead,” and its doc-comment says “True only when the failure proves the session no longer exists.” I treated a message shape as proof. The discriminator I needed already existed in the same file. A test asserting “not-found ⇒ gone” passes happily, because the wrongness is in what the string means, not in what the code does with it.

+
+ +

The gate is on the wrong path

+

I shipped “respawn requires positive proof” and pinned it with a test. Grok traced every respawn path and found the proof check is bypassed on the main one, because the error never reaches a classifier — it is converted into a boolean first:

+
// pty-transport.ts — catches the error and RESOLVES
+return { id: options.sessionId, sessionExpired: true }
+
+// pty-connection.ts — respawns on the flag alone, no proof check
+if (connectResult?.sessionExpired) { /* clear binding */
+  startFreshColdRestoreAgentResume(...) }
+
+
Respawn paths vs the proof gate⤢ zoom
+

resolved as a flag

bare token

empty result

main process

thrown

reattach fails

how does the
failure travel?

sessionExpired: true
→ respawn
no proof check

isSshSessionExpiredError
→ respawn

no ptyId returned
→ respawn

lease marked expired
→ recoverTerminalPane

isProvenSshSessionGoneError
the gate I shipped

resolved as a flag

bare token

empty result

main process

thrown

reattach fails

how does the
failure travel?

sessionExpired: true
→ respawn
no proof check

isSshSessionExpiredError
→ respawn

no ptyId returned
→ respawn

lease marked expired
→ recoverTerminalPane

isProvenSshSessionGoneError
the gate I shipped

+
+
+

What this means for the shipped work

+

Two of my six changes are now known to be narrower than claimed. The keystroke fence is inert on the reattach path, and the respawn gate guards a minority of respawn routes. Both passed their tests because each test asserted the guard behaves correctly when reached — neither could observe that the guarded route is not the route production takes.

+
+ +

3 · What the counsel changed about my design

+ + + + + + + + +
My proposalCounsel’s designWhy theirs is better
Two records: ownership + orphan inventoryOne record. Orphans become a connect-time projection with no durable rowsA durable orphan row goes stale across exactly the disconnect during which the truth changed — and an orphan is only actionable while connected. Also deletes the two-record transaction my split needed.
Key by paneKey = tabId:leafIdKey by leafId; tab derived from the live layout, never storedA stored tabId is either frozen (names a tab the leaf left) or updated (desyncs from the relay’s copy). Both are live failures. Keying by the leaf deletes the transfer problem instead of managing it.
Keep attach-time pane identityDelete it — compare returned incarnation insteadThe apparatus is over-strict and under-strict at once: it rejects a live renamed pane, and accepts a different shell after a relay restart recycles the id. It fails at its own stated job.
“Unknown is not dead” as a principleSame rule, made structural: fate must be reported by the host, never inferred from timing, absence, or error-string shapeEvery defect found across three rounds is one violation of that clause. Mine was a slogan; theirs is a rule with an enforcement point.
+

Both models proposed the single-record collapse independently, which is the strongest signal available in a counsel and why it outweighed my version.

+ +

4 · The rule everything follows from

+
+
Ownership vs fate⤢ zoom
+

FATE — is the shell alive

non-durable

host-local

must be REPORTED by the host
never INFERRED by the client

OWNERSHIP — which pane owns which shell

durable

client-local

read synchronously
from disk while offline

not from timing
not from an absent entry
not from an error string

FATE — is the shell alive

non-durable

host-local

must be REPORTED by the host
never INFERRED by the client

OWNERSHIP — which pane owns which shell

durable

client-local

read synchronously
from disk while offline

not from timing
not from an absent entry
not from an error string

+
+

This is what makes the offline case work without an authority layer. Ownership is answerable with the network down, because it never depended on the network. Fate is never answered by the client at all.

+ +

5 · The record

+
/** Main-owned. TOP-LEVEL in PersistedState — never inside WorkspaceSessionState. */
+type PaneShellOwnership = {
+  leafId: string          // PRIMARY KEY — layout leaf UUID
+  hostId: ExecutionHostId // FIELD: 'local' | 'ssh:<target>' | 'runtime:<id>'
+  worktreeId: string
+  ptyId: string           // relay-native form for SSH — one namespace, always
+  incarnationId: string   // REQUIRED
+  relayInstanceId?: string
+  state: 'attached' | 'detached' | 'terminated'
+  createdAt / updatedAt / lastAttachedAt? / lastDetachedAt?
+}
+// Absent on purpose: no tabId, no paneKey, no hostEpoch, no second record.
+

Uniqueness is enforced on (hostId, ptyId, incarnationId), not ptyId alone — because relay ids are minted pty-1, pty-2… per relay process, so pty-1 recurs on every host after every relay restart. Round 1 had rejected a collision here as impossible; round 3 showed it is guaranteed, and the rejection was withdrawn.

+ +

6 · Orphans are a projection, not an authority

+
+
Why no durable orphan rows⤢ zoom
+

rejected

on connect

ask the host what it has

subtract what our records claim
incarnation-scoped

remainder = orphans
computed, never stored

feeds the existing cleanup affordance
never auto-killed

a durable orphan row would
go stale across the very disconnect
during which the truth changed

rejected

on connect

ask the host what it has

subtract what our records claim
incarnation-scoped

remainder = orphans
computed, never stored

feeds the existing cleanup affordance
never auto-killed

a durable orphan row would
go stale across the very disconnect
during which the truth changed

+
+ +

7 · What gets deleted

+ + + + + + + + + +
DeletedWhere
Attach-identity apparatusrelay comparison + throw, the error constants, the expected-identity derivation on both reattach paths, the renderer branch that treats a mismatch as proof
Lease↔binding reconciliationsupersession, ranking, deferral, rollback, dual matchers — the ~209 lines I added, plus the ~374 that preceded them
The restorable forkthe two contradictory predicates where absence of a lease meant opposite things depending on a sibling leaf
The 30-second grant arithmeticreplaced by an explicit record state
Never built at allhostEpoch and its clock arithmetic; a five-row evidence matrix; a resumed flag — all proposed in earlier rounds and killed before implementation
+
+

Net lines, honestly

+

Removed ≈900–1,250. Added ≈450–700. Net ≈ −300 to −700 — but only after a one-release legacy projection is dropped; during that release it is ≈ −100 to −450. Tests go up ≈900–1,500 for 25 oracles, several needing SSH + detach + relay-restart harnesses that do not exist. The synthesizer stated plainly it could not narrow the range further without doing the call-site rewiring.

+
+ +

8 · Verification

+

Models assert plausible file contents confidently, so every claim about existing code was checked.

+
+
78
Confirmed
+
12
Wrong
+
1
Unverifiable
+
+

Eleven of the twelve errors were citation-level and changed no conclusion. One was a real premise defect: the claim that abandoning a wrongly-attached shell is free. It is not — attach commits activation, clears pending output and may replay before it returns the incarnation the client would use to detect the mistake, and there is no detach RPC to undo it. That correction is folded in as C4.

+

I independently verified the duplicate-agent chain end to end, since it implicates my own code.

+ +

9 · Where the models disagreed

+ + + + + + + + +
ConflictStatus
Do shells survive a hard relay death on Windows/WSL?Open — adjudicated toward “dead” on POSIX evidence; the Windows case is not established
Does the 30-second recovery grant execute in production at all?Open — two reviewers read its comparison as unreachable for a real SSH pane; the covering test seeds a shape production cannot produce
Should relayInstanceId exist?Open — one would delete it and let incarnation carry the rule; the other keeps it because a re-minted id proves only that the relay restarted
Fix or delete the attach identity?Resolved — deletion, and the synthesizer went further than either reviewer
+ +

10 · Readiness

+

A final pass re-checked whether the close-out actually closed its own blockers. Verdict: STILL NOT READY.

+ + + + + + +
BlockerClose-out
The spawn reattach path still wraps any not-found as expired, so client-side auto-respawn survivesNOT CLOSED — C1 hardens the classifier, but the primary path never reaches a classifier. Every auto-respawn consumer must require proof, not just the one that catches a throw.
Migrated records have no incarnation, but the design requires one and throws on mismatchCLOSED, conditionally — C2/C3 work only if an absent recorded incarnation means learn and stamp, never mismatch. That rule must be written into both the algorithm and the type.
+ +

11 · Decisions for you

+ + + + + + + + +
#Decision
1The live bug. It is independent of the redesign and fixable in isolation. Fix it now as its own change, or fold it into the track?
2Visible detached panes. The design replaces an invisible 30-second auto-recovery with an explicit state and two actions (reattach / start a new shell). That is a deliberate product change — a user-initiated relay reset would now show detached panes rather than silently recreating shells.
3Release policy. A leaf removed while its shell lives releases the claim — the shell becomes orphan-eligible and adoptable, and is never auto-killed. Confirm you want liveness preserved over tidiness.
4Sequencing. Two preconditions block everything: one partition per (target, pane), and one bind producer. The second is also what would make the shipped fence non-inert.
+ +
+ Companion to report.html (evidence for the shipped work) and finalized-design.html (the two-plane decision this supersedes at the control plane). + Click any diagram to zoom · scroll to scale · drag to pan. +
+
+ +
×
scroll to zoom · drag to pan · Esc to close
+ + + + diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-brief-for-review.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-brief-for-review.md new file mode 100644 index 00000000000..30d99ae116e --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-brief-for-review.md @@ -0,0 +1,186 @@ +# Design brief — terminal session ownership & transport + +Review artifact. Repo: Orca (Electron + renderer + relay). Everything below marked +**[V]** was verified by reading the code at the cited location. Everything marked +**[R]** is agent-reported and only spot-checked. Treat **[R]** as a lead, not a fact. + +--- + +## 1. The product problem + +Orca runs terminals on four "routes": + +| Route | Provider | Survives app restart | +| --------------------- | ----------------------------------------------- | -------------------------- | +| local in-process | `LocalPtyProvider` | no | +| local daemon | `DaemonPtyAdapter` (swapped into the same slot) | yes | +| direct SSH | `SshPtyProvider` → remote relay | yes, within a grace window | +| paired remote runtime | not an `IPtyProvider`; runtime RPC | yes | + +Reported failures: + +1. **Pane cardinality growth (STA-3077).** SSH reconnect: 2 terminals → 19 → 20. + Most are panes the user never opened. Remote host fills with unused shells. +2. **Duplicate agent resume.** A coding agent gets resumed twice, two processes + writing one conversation file. One report reached five. +3. **Blast radius.** One PTY failing to re-prove its output stream could drop the + whole host connection, killing every pane, file transfer and git command on it. + +## 2. Verified facts (the evidence base) + +**[V] Dispatch is a substitution for daemon, a parallel registry for SSH.** +`src/main/ipc/pty.ts:932-941`: + +```ts +function getProvider(connectionId) { + if (!connectionId) return localProvider // local AND daemon — one slot + const provider = sshProviders.get(connectionId) // SSH — separate map +} +``` + +The daemon is installed by `setLocalPtyProvider(routedAdapter)` +(`src/main/daemon/daemon-init.ts:1031`) and adds **zero** branches to the shared +spine. The paired runtime is encapsulated behind a `PtyTransport`. SSH is neither — +it rides the local path carrying a `connectionId` tag. + +**[R] That tag leaks:** ~199 remoteness branches in main (52 in `pty.ts`, 143 in +`orca-runtime.ts`), ~191 in the renderer, plus 25 `instanceof` provider checks. +The `remote:` predicate is re-declared 5 times in the renderer. + +**[V] The transport dropped the half that makes it persistent.** +`src/main/ssh/relay-protocol.ts:34`: + +```ts +export const MessageType = { Regular: 1, KeepAlive: 9 } as const +``` + +The 13-byte frame header was copied from a well-known persistent protocol, but +only 2 of its 9 message types were kept. Dropped: `Control`, `Ack`, `Disconnect`, +`ReplayRequest`, `Pause`, `Resume`, `None`. The surviving ACK field feeds only +`unackedTimestamps` (`ssh-channel-multiplexer.ts:107,448,596`), a seq→timestamp map +read solely by the death timer. **Nothing is retained at the transport layer; +nothing is replayed.** Consequence: three layers above it each rebuilt +retain-and-replay independently (SSH credit ledger, runtime-RPC source-range +ledger, daemon batcher — the last deliberately lossy). + +**[V] Method layer is transport-agnostic.** `runtime/rpc/methods/terminal.ts` and +`git.ts` have 0 SSH references; `files.ts` has 27. + +**[V] Three durable records exist, plus a fourth copy on the host.** + +| | key | pane identity is | +| ------------------------------------- | ------------------------- | ----------------------------- | +| PTY binding (`WorkspaceSessionState`) | `(hostId, tabId, leafId)` | **the key** | +| `SshRemotePtyLease` | `(targetId, relayPtyId)` | **optional payload** | +| `SshPtyConsumerRecovery` | `targetId` | n/a (per-target resume token) | +| relay `attachIdentity` | per PTY, in-memory | compare-only | + +**[R] ~374 lines of pure lease↔binding reconciliation in `persistence.ts`**, and 9 +enumerated states where the records can disagree. Example of an independent latent +bug: absence of a lease means "restorable" in `isRestorablePtyBinding` but "not +restorable" in `hasRestorableSshRemotePtyLease` — so whether a binding survives +depends on whether a _sibling leaf_ had a binding. + +**[V] The relay holds nothing durably.** Its PTY table is +`private ptys = new Map()` (`src/relay/pty-handler.ts:356`). +No relay-side persistence of PTY state exists. `pty.serialize`/`revive` hand state +to the _client_ and take it back; `revive` requires the original PIDs to still be +alive. On PTY exit the entry is deleted with no tombstone. + +**[V] Pane identity is write-only over the wire.** `listProcesses` and `attach` +never return `paneKey`/`tabId`/`leafId`; `attach` only compares and throws +`identity mismatch`. The one RPC that returns identity (`pty.serialize`) has +**zero production callers** — test files only. + +**[V] The client's lease is consulted from a synchronous, offline, disk-only path.** +`hasRestorableSshRemotePtyLease` is called inside `setLocalWorkspaceSession` +(`src/main/persistence.ts:6465`), a synchronous `void` method invoked on every +renderer session publish including during quit (`:6287`, `:6351`). + +## 3. Alternatives already refuted + +**A. Merge the lease into the pane binding.** Blocked by two load-bearing +properties: a lease must be able to name a live shell **no pane owns** (the actual +STA-3077 field state; reattach enumerates these), and a lease **outlives** the +binding — expiry deletes the binding and then authorizes recreating a shell for 30s +(`SSH_PANE_RECOVERY_GRACE_MS`, `orca-runtime.ts:1771`). + +**B. Delete the lease; make the remote host authoritative.** Refuted. The host has +no durable state, cannot be queried for pane identity, has no notion of "recently +died, replacement authorized", and is by construction unreachable exactly when the +record is needed. Decisive: you cannot replace a synchronous local disk read during +quit with an RPC to a host that is down. + +**C. A second "authority architecture" beside the existing one** (+60,903 lines, +394 new files). Rejected earlier: it fixed none of the three root causes. + +## 4. The design under review + +### Plane 1 — data plane (adopted from a separate proposal) + +Restore a delivery guarantee at the transport, then collapse what was rebuilt above +it. Roughly: capability handshake; one delivery-identity type; one credit-ledger +implementation parameterised by unit and limit; one chunk-and-ack primitive; one +lane vocabulary; binary PTY payloads reusing the binary terminal frame Orca already +ships to mobile; prebuilt native binaries so first connect stops needing a compiler; +then teach the relay to listen on a loopback WebSocket, forward that port, and let +the _same_ client serve the SSH route — after which SSH is "launch + access" only. + +### Plane 2 — control plane (proposed here; the reviewed contribution) + +The lease answers two different questions with one record keyed for neither: + +- "which shell does this pane own?" → wants a **pane** key +- "which shells exist that nobody owns?" → wants a **pty** key + +Proposal: split by question. + +- **Ownership record**, keyed `(host, pane)` — the _same_ key local already uses. + Transport-specific payload (lease state + timestamps for SSH; nothing extra for + local). Makes "one pane, one live shell" structural rather than enforced. +- **Orphan inventory**, keyed `(host, ptyId)` — live shells with no owner. Feeds the + reattach work list and the disconnected-cleanup UI. +- The 30s recovery grant becomes a terminal state on the pane-keyed record. +- Offline consumers keep reading local disk synchronously, unchanged. + +Claimed payoff: the ~209 lines of supersession/ranking/rollback/dual-matchers exist +_only_ to bolt a pane-keyed constraint onto a pty-keyed record, and become +unnecessary. + +## 5. Historical defect, now resolved + +This defect was resolved by the shared `bindPaneShell` producer used by relay reattach and both +spawn handlers. Its mutation proof is recorded in +[S5](./new-design-goalposts.md#s5--the-superseded-pane-fence-is-live-on-the-reattach-path--proven). + +## 6. Hard constraints + +- **Cross-platform**: macOS, Linux, Windows (+ WSL). No `echo $$`/`ps` assumptions. +- **Folder workspaces**, not only git worktrees. +- **Remote wire compatibility**: clients and remote hosts update independently; + mixed versions are normal. New optional field = safe; new stream opcode must be + capability-negotiated (decoders drop unknown opcodes silently); changing what a + host publishes reaches old clients with no wire change. +- **Git 2.25 baseline** for git-touching work. +- Durable on-disk state is also read by pinned older builds in cross-version tests. +- "Unknown is not dead": disconnect, timeout, absent inventory, and retry + exhaustion must never authorize destroying a process. +- No `max-lines` lint disables. + +## 7. What the review must answer + +1. **Correctness holes.** Which cases does the Plane 2 design get wrong or fail to + cover? Specifically: multi-window / multi-device on one host; app restart while + disconnected; relay restart; host reboot; PTY exit during disconnect; two panes + racing for one shell; migration from existing on-disk state; a pane deleted while + its shell lives; the same worktree open in two windows. +2. **Simplicity.** Is there a _simpler_ design with the same correctness? Simpler + means fewer code paths and fewer concepts, not merely fewer lines. Is the + two-record split actually necessary, or is there a single-record formulation that + survives the section-3 refutations? +3. **Migration.** Re-keying a durable record needs a story for existing state, + partial writes, and rollback. +4. **Testability.** What oracle would fail if each guarantee were removed? A design + whose guarantees cannot be falsified by mutation is not finished. +5. **Is Plane 2 even the right cut?** Attack the premise that data plane and control + plane are separable here. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-explained.html b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-explained.html new file mode 100644 index 00000000000..8718846bd98 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-explained.html @@ -0,0 +1,235 @@ + + + + + + Terminals that don't duplicate — the plain-English design + + + +
+
+

Why terminals duplicate,
and how we stop it

+

Plain English, no code. Two bugs, two fixes, then one decision for you.

+
+ +
+ The whole design in one line:
+ Keep our own notes about which terminal is whose — and never guess whether a program died. +
+ +
Setup
+

What's behind one terminal

+

When you open a terminal on a remote machine, there are three things, not one.

+
+
The three pieces⤢ zoom
+

THE PANE
the box on your screen

THE NOTE
this pane goes
with that program

THE PROGRAM
really running on
the other machine

THE PANE
the box on your screen

THE NOTE
this pane goes
with that program

THE PROGRAM
really running on
the other machine

+
+

Your network blips. The pane stays on screen. The program keeps running over there. Only the connection between them breaks.

+

So reconnecting is one job: match the notes back up to the programs. Both bugs below are that matching going wrong.

+ +
Bug one
+

The notes piled up

+

A real user report: 2 terminals became 19, then 20. Most were panes they never opened.

+
+
Why they multiplied⤢ zoom
+

you have 2 terminals

blip → reconnect

Orca writes a new note
and keeps the old one

another blip

another note.
old ones still kept.

reconnect restores EVERY note.
one pane per note.
19 panes

you have 2 terminals

blip → reconnect

Orca writes a new note
and keeps the old one

another blip

another note.
old ones still kept.

reconnect restores EVERY note.
one pane per note.
19 panes

+
+

The cause is boring and completely fixable: the notes were filed under the program's name, not the pane's. One pane could collect unlimited notes, and nothing threw the old ones away.

+ +

The fix: one slot per pane

+
+
Filed by pane instead⤢ zoom
+

after · filed by pane

pane A

its one note

before · filed by program

pane A

note 1

note 2

note 3

after · filed by pane

pane A

its one note

before · filed by program

pane A

note 1

note 2

note 3

+
+

Piling up is no longer something we prevent — there is one slot, so it cannot happen. That's the difference between a rule you enforce and a shape where the bug has nowhere to live.

+ +
+ One detail that matters +

The note is filed under a permanent serial number stamped on the pane when it's created — not under "which tab it's in". Tabs change: you can drag a pane into another tab any time. A serial number never does. File things under what doesn't move.

+
+ +
Bug two
+

"I can't find it" was read as "it died"

+

This is the worse one, because it's how you end up with two AI agents writing into the same conversation.

+
+
Drag a pane to a new tab, then reconnect⤢ zoom
+

you drag a pane
into a new tab

the other machine still has
the OLD tab written down

on reconnect it compares, sees
a difference, and replies:
no such terminal

Orca reads that as
the program died

starts a replacement,
and resumes your agent again

TWO agents writing to one
conversation. the first one
never stopped.

you drag a pane
into a new tab

the other machine still has
the OLD tab written down

on reconnect it compares, sees
a difference, and replies:
no such terminal

Orca reads that as
the program died

starts a replacement,
and resumes your agent again

TWO agents writing to one
conversation. the first one
never stopped.

+
+ +
+ The trick in it +

The other machine did find your program. Comparing is how it noticed the tab was different. But it answered "not found" — so a message meaning "it's alive and I'm being fussy" looked exactly like "it's gone."

+
+ +

Fix, part one: stop comparing tabs

+

Moving a pane between tabs is a normal thing you're allowed to do, so it must never make a terminal unreachable. That comparison is removed.

+

It was also failing at its real job anyway. It existed to catch a different problem — the remote machine reusing an old ID for a brand-new program, like an apartment number being handed to a new tenant. It never caught that. So we check the tenant instead of the apartment number: catches the real case, stops rejecting panes that merely moved.

+ +

Fix, part two: never guess about death

+

A replacement terminal starts only on actual proof the old program is gone.

+
+
What counts as proof⤢ zoom
+

did the program die?

we watched it exit

the same helper that started it
says it's gone

can't reach the machine

it timed out

missing from a list

confusing error message

PROOF
start a replacement

NOT PROOF
leave it running.
ask the user.

did the program die?

we watched it exit

the same helper that started it
says it's gone

can't reach the machine

it timed out

missing from a list

confusing error message

PROOF
start a replacement

NOT PROOF
leave it running.
ask the user.

+
+

The second proof is the clever one. The helper on the remote machine keeps its list of running programs only in memory. So if that same helper — same process, not a restarted one — says a program isn't in its list, it must have exited. There is nowhere else it could be.

+

And if the helper restarted, it remembers nothing, so we say we don't know. We never treat a fresh helper's empty list as news that your programs died.

+ +
Result
+

What you'd actually notice

+ + + + + + + + +
SituationTodayAfter
Network drops and comes backTerminals multiply; the remote machine fills with junkYour terminals come back. Nothing invented.
You drag a pane to a new tabA second agent resumes onto the same conversationJust works.
Orca genuinely can't tell if a program survivedSilently starts a new onePane says "disconnected", with two buttons
Leftover programs on a remote machineInvisible, pile up foreverListed with folder and name — you choose what to close
+ +
+
The one visible change⤢ zoom
+

Orca isn't sure whether
your program survived

TODAY
quietly starts a new one.
you may not notice until
there are two agents.

AFTER
pane shows 'disconnected'
[ try again ] [ new terminal ]

Orca isn't sure whether
your program survived

TODAY
quietly starts a new one.
you may not notice until
there are two agents.

AFTER
pane shows 'disconnected'
[ try again ] [ new terminal ]

+
+ +
+ This is the decision I need from you +

Today, uncertainty gets resolved silently and wrongly. After this, uncertainty becomes visible — a disconnected pane with two buttons.

+

Slightly more friction in a rare case, in exchange for never resuming your agent twice. I think it's clearly right, but it changes what people see, so it's your call.

+
+ +
Plan
+

The order we'd build it

+

Six steps. Each ships on its own and can be undone on its own.

+ + + + + + + + + + +
StepWhat it does
1Stop the tab comparison killing live terminalsFixes the double-agent bug. Small, self-contained, helps immediately.
2Stop faking "the program exited"Today a failed reconnect tells the pane the program exited — a claim we can't back up. Ships with the two-button UI.
3Write the notes in one placeThey go to two different places today, which makes the cleanup silently do nothing. This is the actual cause of 2 → 19.
4One piece of code writes the notesTwo paths write them and a third forgets to — which is why an existing safety check never runs during reconnect.
5Check whether an old recovery path ever runsTwo reviewers believe it's unreachable. Measure before building on it.
6The proof ruleOnly if step 5 shows it's needed.
+ +
+

The five words I couldn't avoid

+ + + + + + + + +
PaneOne terminal box on your screen.
ProgramThe shell or agent actually running — often on another machine.
NoteOrca's record that a pane goes with a program. Saved to disk, so it survives a restart.
HelperThe small program Orca installs on a remote machine to run terminals there.
OrphanA program still running that no pane claims. We list them; we never close them for you.
+
+ +
+ Why this is smaller, not bigger +

It removes roughly 900–1,250 lines and adds roughly 450–700. Most of what goes away exists only to patch up disagreements between notes filed different ways. Once there's one note per pane, that code has nothing left to do.

+
+ +
+ The detailed versions: counsel-design.html — how this was reviewed and what it cost. + report.html — evidence for the work already written. + Click any diagram to zoom · scroll to scale · drag to pan. +
+
+ +
×
scroll to zoom · drag to pan · Esc to close
+ + + + diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-final-detail.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-final-detail.md new file mode 100644 index 00000000000..d6b474c93a8 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-final-detail.md @@ -0,0 +1,256 @@ +FINAL DESIGN — one leaf-keyed ownership record; pane identity deleted from the attach path; death proved only by the relay process that spawned the shell + +===================================================================== +D0. SCOPE AND THE ONE RULE EVERYTHING FOLLOWS FROM +===================================================================== +Problem (from the brief): SSH reconnect grows pane cardinality (2 -> 19 -> 20, STA-3077); a coding agent gets resumed twice into one transcript (RC2); one PTY's failure can drop a whole host connection (RC3, out of scope — Plane 1). + +One rule, applied without exception: + +Ownership ("which shell does this pane own?") is DURABLE, CLIENT-LOCAL, and read +synchronously from disk while offline. Evidence about a shell's FATE is +NON-DURABLE, HOST-LOCAL, and must be REPORTED by the host, never INFERRED by the +client from timing, from the absence of an entry, or from the shape of an error +string. + +Every defect found across three review rounds is one violation of the second clause. The design's job is to remove all of them, not to add an authority layer. + +SCOPE DECLARATION (grok, low): the record is host-agnostic (`hostId` is a field). The _death rule_'s row 2 is relay-specific. Local and daemon panes reach `terminated` only through row 1 (an exit observed in-process, which is how they already work) and never through row 2. That is stated rather than left implicit. + +===================================================================== +D1. THE DURABLE RECORD +===================================================================== + +```ts +/** Main-owned. TOP-LEVEL in PersistedState — never inside WorkspaceSessionState. */ +type PaneShellOwnership = { + leafId: string // PRIMARY KEY. Terminal-layout leaf UUID. + hostId: ExecutionHostId // FIELD: 'local' | 'ssh:' | 'runtime:' + worktreeId: string // FIELD. Opaque FULL string incl. any `::workspace:` suffix. + ptyId: string // RELAY-NATIVE form for SSH (toRelaySshPtyId). One namespace, always. + incarnationId: string // REQUIRED. Relay mints one per pty (relay/pty-handler.ts:1525). + relayInstanceId?: string // The relay PROCESS that owned it, as reported at bind time. + state: 'attached' | 'detached' | 'terminated' + createdAt: number + updatedAt: number + lastAttachedAt?: number + lastDetachedAt?: number +} +// Storage: PersistedState.paneShellOwnershipByLeafId: Record +``` + +Note what is NOT here: no `tabId`, no `paneKey`, no `hostEpoch`, no `resumed`, no second (pty-keyed) record. + +WHY `leafId` AND NOT `paneKey`. `makePaneKey(tabId, leafId)` returns `${tabId}:${leafId}` and the repo states at src/shared/stable-pane-id.ts:47-49 that "only the leaf UUID is remint-stable pane identity (the tab half changes on pane break-out)" — which is why `isEquivalentPaneKey` exists at :50-57. The mutation is a shipping gesture: `detachTerminalPaneToTab` (src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts:245-310) moves a LIVE pane and its ptyId into a new tab via `createTab(..., initialPtyId)` while explicitly not killing the PTY (:275-276). `leafId` is a UUID and is never remapped once it is one (src/main/persistence.ts:1858-1872 skips ids already passing `isTerminalLeafId`). Keying by the leaf deletes the transfer problem instead of managing it. + +WHY NO `tabId` AT ALL (this is the round-3 change). A stored tabId is either frozen (and then it names a tab the leaf no longer lives in) or updated (and then it desynchronizes from the relay's frozen copy). Both are live production failures — see D2. The tab is LOCATION, derived from the live layout at the moment it is needed; it is never stored and never trusted. + +WHY TOP-LEVEL. `session:set` / `session:set-sync` (src/main/ipc/session.ts:13, :31) accept a whole `WorkspaceSessionState` from a renderer with no revision or fencing token; the clobber guards at src/main/persistence.ts:6379, :6384-6476 exist only because of that. `sshRemotePtyLeases` is already top-level. The KEY is shared with the layout; the STORAGE LOCATION is not. + +UNIQUENESS. At most one non-terminal record may name a given `(hostId, ptyId, incarnationId)`, enforced on write through a reverse index. Not ptyId alone: leases store the relay-native id (`getRelayPtyIdForSshLeaseStorage` -> `toRelaySshPtyId` strips the connection scope, src/main/persistence.ts:6641-6643, src/shared/ssh-pty-id.ts:58-67) and relay ids are `pty-${this.nextId++}` with `nextId = 1` per relay PROCESS (src/relay/pty-handler.ts:356-357, :1440-1443), so `pty-1` recurs on every host after every relay restart. Round 1's rejection ("a cross-target collision on ptyId is impossible") is withdrawn; it is guaranteed, not impossible. + +===================================================================== +D2. DELETE PANE IDENTITY FROM THE ATTACH PATH (the largest round-3 change) +===================================================================== +Both reviewers independently attacked the attach-time identity comparison. Verified, and it is worse than either stated: the apparatus is simultaneously over-strict and under-strict, and it is a live duplicate-agent bug today. + +VERIFIED FACTS + +- The relay compares frozen strings: `attachIdentityMismatches` (src/relay/pty-handler.ts:334-339) does full-string `expected.paneKey !== managed.paneKey || expected.tabId !== managed.tabId`; `attachIdentity` is captured once at spawn from `ORCA_PANE_KEY`/`ORCA_TAB_ID` (:1512-1517, :1446). On mismatch it throws `PTY "" not found (identity mismatch)` (:1616-1626). +- `isSshPtyNotFoundError` is a message regex `/PTY ".+" not found/i` (src/main/providers/ssh-pty-errors.ts:12-15), so it is TRUE for the mismatch string. `reattachSshPtySession` re-emits it as `SSH_SESSION_EXPIRED: SSH_PTY_IDENTITY_MISMATCH` (src/main/providers/ssh-pty-session-reattach.ts:218-226). +- The renderer's `isProvenSshSessionGoneError` returns TRUE for anything containing `SSH_SESSION_EXPIRED` and for the raw not-found regex, and IGNORES the mismatch marker (src/renderer/src/components/terminal-pane/reattach-failure-classification.ts:24-30). Its two call sites then clear the binding and call `startFreshColdRestoreAgentResume` (pty-connection.ts:8839-8847, :9086-9097) — a second shell and a SECOND AGENT RESUME while the original shell keeps running. That is RC2, on a live process, reachable from a shipped gesture. +- The spawn-path reattach builds the expected identity from the CURRENT options (`args.options.paneKey ?? env.ORCA_PANE_KEY`, ssh-pty-session-reattach.ts:66-68), i.e. the current tab — so after a detach it mismatches. The connect-path reattach builds it from the lease's stored tabId (`expectedIdentityForLease`, src/main/ssh/ssh-relay-session.ts:190-210, consumed at :2201-2210), which is never re-keyed on detach — so it matches, attach succeeds, and then `persistPtyBinding(tabId = old tab, mayCreate:false)` refuses because the leaf is no longer in that tab's layout (src/main/persistence.ts:6821-6877 sets `terminalMembershipChanged` and returns false), leaving the shell running unbound (ssh-relay-session.ts:2513-2521). Grok's "scissors" is confirmed on both blades. +- The apparatus does not even do its own stated job ("generation resets can reuse PTY IDs; reject conflicting identities", pty-handler.ts:1615): after a relay restart that recycles `pty-3` for the SAME pane, paneKey and tabId both match and a different shell is accepted. + +RESOLUTION — delete the comparison; do not replace it with another comparison. + +1. Relay: delete `attachIdentity`, `attachIdentityMismatches`, the `params.expectedPaneKey`/`expectedTabId` handling and the `(identity mismatch)` throw. `ManagedPty.paneKey`/`tabId` STAY — they are documented as separate from attach identity (pty-handler.ts:139-143) and are used by the exit listener (:765) and, newly, by listProcesses reporting (D4). paneKey stops being an authorization INPUT and becomes a reported HINT. +2. Main: delete `ExpectedPtyIdentity`, `expectedIdentityForLease`, `expectedIdentityByPtyId`, the `expectedIdentity` parameter threaded through `attachPtyWithRetry`, `isSshPtyIdentityMismatchError`, `SSH_PTY_IDENTITY_MISMATCH_ERROR`, the marker append, and the mismatch branch at ssh-relay-session.ts:2628-2634. +3. Renderer: `isProvenSshSessionGoneError` keeps only proofs. (After step 1/2 the mismatch string ceases to exist; the renderer fix ships FIRST and independently, because it must protect users running against relays that have not been redeployed.) +4. Recycled-id rejection moves to two places that already hold exact data: + (a) PROCESS GATE, once per connection: if the owner grant reports a `relayInstanceId` different from the one recorded on a record, that record's ptyId is not attachable at all. One comparison covers every pty on the host. Within a single relay process ids never recycle (`nextId` is monotonic), so this is complete against new relays. + (b) PER-ATTACH GUARD, zero wire change: EVERY `pty.attach` success path already returns `incarnationId` (src/relay/pty-handler.ts:1646, :1653, :1668, :1676), and the client already parses and remembers it (`requestSshPtyAttach` -> `rememberPtyIncarnation`, ssh-pty-session-reattach.ts:74-100). Compare it to `record.incarnationId`; on mismatch, throw — the existing `activationLease.rollback()` already runs on a thrown error — and classify `detached`, never death. `RecentPtyOutputBuffer.read()` is explicitly non-mutating (src/main/runtime/recent-pty-output-buffer.ts:75-85), so abandoning a wrongly-attached shell does not consume its replay. + This is strictly stronger than the frozen-string check (a per-pty UUID vs a pane label), needs NO new request field, and works against OLD relays — which a new `expectedIncarnationId` request parameter would not. +5. The reattach BIND resolves the tab from the live layout: find the tabId whose `terminalLayoutsByTabId[*].root` contains this `leafId`. If no layout contains it, refuse exactly as today (leave the shell running unbound, "no durable pane owns this"). `mayCreate:false`'s guarantee is preserved; its dependence on a stored tabId is deleted. + +ONE IDENTITY RULE, EVERYWHERE: the leaf is identity; the tab is derived location; the incarnation is shell identity; the relay instance is process identity. There is no fourth. + +===================================================================== +D3. THE DEATH RULE — two rows, one new field +===================================================================== +`resumed` and `hostEpoch` are deleted and must not be built. + +- `resumed: replaces !== null` (src/shared/pty-consumer-session.ts:275); `expireOwner()` nulls the incumbent after `PTY_CONSUMER_OWNER_GRACE_MS = 30_000` (:281-287, contract :2), after which admission takes `if (!current) return this.newOwner(...)` (:215-216) and `resumed` is false regardless of proof. Unreachable for quit, sleep, overnight, reboot — the normal case. Its own contract comment says it means "the client's checkpoints for the previous claim no longer apply" (pty-consumer-session-contract.ts:49-52): a delivery-checkpoint flag, not liveness. +- `hostEpoch = Date.now() - os.uptime()*1000` under exact equality is a reconstructed estimate; second-granularity uptime, NTP steps and suspend/resume make it differ on an unrebooted host, and "differs" was the grant-YES row — it fails OPEN toward respawn. Repo precedent settles it: `readCurrentDaemonReadyIdentity` reads `/proc/sys/kernel/random/boot_id` on Linux only and returns bare `{ startedAtMs }` elsewhere (src/main/daemon/daemon-ready-identity.ts:11-13). + +THE ONE NEW GRANT FIELD: `relayInstanceId?: string` on `PtyConsumerSessionGrant` (src/shared/pty-consumer-session-contract.ts:43-59) — a `randomUUID()` minted once at relay process start (`randomUUID` is already imported at relay/pty-handler.ts:6). It is genuinely new information: the grant's existing `serverBuildId` is `launchVersion` (src/relay/relay.ts:694-696), a build string that is identical across restarts of the same build. + +| Condition | Transition | Respawn grant | +| ---------------------------------------------------------------------------------- | ------------ | -------------------- | +| PTY exit observed on a live attached stream | `terminated` | yes | +| attach returns not-found AND the grant's `relayInstanceId` EQUALS the recorded one | `terminated` | yes (subject to E-1) | +| attach returns an incarnation different from the recorded one | `detached` | no | +| `relayInstanceId` absent on either side, or differing | `detached` | no | +| any other error (today's `restoreRequired` path, ssh-relay-session.ts:2612-2620) | `detached` | no | + +Row 2 is sound and UNBOUNDED IN TIME: `this.ptys` is the relay process's only store (pty-handler.ts:356) and entries are deleted on exit, so "the same process that minted this pty no longer has it" means it exited. It is sound on Windows too, because the relay OBSERVED the exit — unlike any rule that reasons from a relay restart. A restarted relay reports a different id and we correctly claim no knowledge. + +SHIP GATE (grok H4): row 2 grants a respawn on a not-found detected by a message regex. One shared normalization helper (`toRelaySshPtyId`) must be applied on every attach / mark / record / comparison path, and the record stores exactly one namespace (D1), so a namespace mismatch cannot manufacture a false not-found. Row-2 grant-yes does not ship until E-1 is green. + +STOP FABRICATING THE EXIT. `handlePtyReattachFailure` currently sends `pty:exit { code: -1 }` (ssh-relay-session.ts:2643-2647) plus `clearProviderPtyState` + `deletePtyOwnership` + `markSshRemotePtyLease('expired')` on a plain not-found. On every `detached` row this is a lie about a process the client knows nothing about. Remove the whole block and route the unknown case into the branch that ALREADY EXISTS three lines above it: `pending.restoreRequired = 'reattachAttemptsExhausted'` + `wakeRecovery` (:2612-2620), which is non-destructive by construction. This is a branch COLLAPSE, not a new signal — which is also the answer to the objection that removing only the send turns a wrong signal into no signal. + +===================================================================== +D4. ORPHANS — a connect-time projection, never an authority +===================================================================== + +``` +orphans(host) = successful listProcesses(host) + MINUS { (ptyId, incarnationId) named by a non-terminal record on this host } +``` + +Computed at connect/reattach, held in memory for the connection's life, discarded on disconnect. No durability, no migration, no rollback. + +WHAT `listProcesses` IS: it iterates only `this.ptys` (pty-handler.ts:1894-1911) — the current relay process's Map. No durability, no OS scan. It is therefore (i) the cleanup-UI source and (ii) a SUPPLEMENT to the reattach work list, never the sole discovery authority. The work list stays `getPtyIdsForConnection(target) UNION` the non-terminal records (today's `leasedPtyIds` shape, ssh-relay-session.ts:2211-2219). + +ABSENCE IS NEVER AUTHORITATIVE. The repo already adjudicated this with an issue number: `pty:listSessions` documents "Absence is authoritative only from a provider that serializes claims — otherwise it is 'unknown', never 'absent' (#8459)" (src/main/ipc/pty.ts:7343-7347), and `SshPtyProvider.hasPty` returns `null` before a completed listing "a miss there is ignorance about the host, not a dead PTY" (src/main/providers/ssh-pty-provider.ts:308-312). The only aggregating caller launders every remote failure with `provider.listProcesses().catch(() => [])` (ipc/pty.ts:7333), and `PtyProcessListAdmission.admit` throws on capacity and on `agent_session_ownership_unknown` (src/main/providers/pty-process-list-admission.ts:60-99). So: a rejected or truncated listing yields orphans = UNKNOWN (empty UI, no claims, no retirement), never orphans = everything. + +THE ONE NEW RESPONSE FIELD: `PtyProcessSummary` gains optional `paneKey`. The relay already holds it (`ManagedPty.paneKey`, pty-handler.ts:1446, :139-140) and omits it from the summary (:1899-1908). Additive optional response field — safe under docs/reference/remote-wire-compatibility.md, no opcode, no negotiation. It does NOT reach the client for free: `PtyProcessInfo` has no `paneKey` (src/main/providers/pty-process-info.ts:4-16) and `admit` REBUILDS an allowlist (pty-process-list-admission.ts:106-115). Three edits — relay summary, `PtyProcessInfo`, allowlist — and the oracle asserts survival THROUGH `admit`. `incarnationId` and `worktreeId` already traverse that whole chain, which is what makes the incarnation-scoped subtraction free. + +ADOPTION matches `parsePaneKey(reported.paneKey)?.leafId` — never the full string, because the relay's copy is frozen at spawn and names a tab the leaf may have left. Because the record is leaf-keyed this is a direct lookup, not fuzzy equivalence; `isEquivalentPaneKey` is not imported here. Adopt is a CAS: write `leafId -> (ptyId, incarnationId)` only if no non-terminal record exists for that leaf AND none on this host names that `(ptyId, incarnationId)`. Exactly one of two concurrent adopts wins; the loser gets a typed refusal. + +KILL POLICY (replaces the "owned elsewhere" classification, which is DELETED). Both reviewers attacked `worktreeId`-based classification from opposite directions and both are right, because `worktreeId = ::` and `repoId` is a client-local `randomUUID()` minted at repo add (src/shared/worktree-id.ts:15-28; src/main/runtime/orca-runtime.ts:18729). So "unknown worktreeId" means "not in this install's current state file": it wrongly EXEMPTS the user's own shells after a repo re-add, profile transfer or state reset, and it wrongly INCLUDES another device's shells whenever the two installs share state. One rule replaces it: the orphan list never auto-kills, never bulk-kills, and never kills as a side effect of any reattach or cleanup pass. Kill is an explicit per-shell user action, with cwd, title, worktreeId and reported paneKey shown. No classifier, no new field, and it is safe in both directions. + +OLD-RELAY DEGRADATION: a relay that omits `paneKey` yields unclassified orphans that are listed and never killed — exactly today's behavior. + +===================================================================== +D5. RECORD LIFETIME — three exits, none of them "absent from a list" +===================================================================== + +1. RETIRE (delete). The record reached `terminated` (row 1 or row 2 of D3, or explicit user close via `retireExitedPty`, ssh-relay-session.ts:2153-2172). Terminal records are garbage-collected after a bounded retention (long enough to serve any surviving grant window) so they cannot mask a recycled `pty-1`. There is NO retire-on-absence clause: the case it was written for (shell exited during a disconnect, relay still up) is already covered by row 2 — the attach itself proves the exit — so deleting the clause costs nothing and removes a direct contradiction with #8459. +2. RELEASE (keep the shell, drop the claim). Fired ONLY from the explicit pane-close and tab-delete code paths — never from "this publish did not contain the leaf". Detach is not atomic across layouts: `createTab` installs an empty layout, then `setTabLayout(sourceTabId, ...)` removes the leaf, then `setTabLayout(tab.id, ...)` adds it (terminal-pane-tab-detach.ts:298-300), so between the last two no layout contains the leafId, and any `session:set` flush in that window would look like a durable removal. Released records are cleared to a non-claiming state: the shell becomes orphan-eligible (visible, adoptable) and is deliberately NOT `terminated`, so it can never authorize a respawn. +3. EXPLICIT USER CLOSE -> `terminated`, and the record dies with the shell. + +RESIDUAL, STATED HONESTLY: a shell that died while the relay ALSO restarted leaves a `detached` record with no proof available. It stays restorable until the user acts. That is the conservative direction and it is bounded by the affordance below, not by a timer. + +PRODUCT AFFORDANCE, REQUIRED IN THE SAME PR. A `detached` pane renders as disconnected with two explicit actions — "reattach (retry)" and "start a new shell" (the latter retires the record). Nothing infers death, nothing auto-spawns. Per AGENTS.md this must follow docs/STYLEGUIDE.md. COPY CONSTRAINT: the UI must never assert that a shell is dead. The claim "after a relay crash the shells are almost certainly dead" is REMOVED from this design: it rests on POSIX master-fd close SIGHUPing the foreground group, and on Windows the relay is deliberately launched through WMI because "Windows sshd kills the exec channel's process tree on close" (src/main/ssh/ssh-relay-deploy.ts:1805), with ConPTY and no SIGHUP. No rule in this design concludes anything from a relay restart, so the design is correct either way; only the copy had to change. + +===================================================================== +D6. HISTORICAL — one partition per (target, pane). SUPERSEDED. +===================================================================== +This migration proposal was rejected. The shipped containment keeps the existing persistence +planes and gives the pane binding one local home; see [S4](./new-design-goalposts.md#s4--one-partition-per-target-pane--proven). + +SSH pane bindings live in two partitions today. Readers and writers that consult ONLY `ssh:`: `resolvePersistedStablePaneOwner` (src/main/ipc/pty.ts:676-677), `retirePersistedStablePaneOwner` (:760-761, :783), the CAS write `persistPtyBinding(..., expectedBinding)` (:833), and the two spawn upserts (:5108, :6493). Against that, the relay reattach write has no hostId (ssh-relay-session.ts:2500-2511 -> `resolveHostId(undefined)` -> `LOCAL_EXECUTION_HOST_ID`, persistence.ts:6243-6246) and the renderer keeps SSH worktrees in `local` deliberately (workspace-session-host-persistence.ts:167-173). `durablyBoundPtyIdForPane` hedges ssh-first-then-local (persistence.ts:7269-7277), so `supersedeSiblingLeasesForPane` early-returns when the bound pty differs (:7229-7232) — supersession silently no-ops and both leases stay live. That is the STA-3077 mechanism itself. + +FIX: one accessor `sessionForSshPaneBindings(connectionId): WorkspaceSessionState` returning the `local` partition, routed through by EVERY reader and EVERY writer above, flipped in a single atomic PR — not five write-site edits. `local` wins because the only publisher of pane membership writes there and `mayCreate:false` is evaluated there. A one-time fold moves `ssh:.terminalLayoutsByTabId[*].ptyIdsByLeafId` and `tabsByWorktree[*].ptyId` into `local`, preferring `local` on conflict; the loser is NOT demoted to orphan-candidate by ptyId alone (recycled ids collide) — it carries `incarnationId` or is dropped. + +===================================================================== +D7. HISTORICAL — one bind producer. RESOLVED. +===================================================================== +The shared `bindPaneShell` producer now serves relay reattach and both spawn handlers; see +[S5](./new-design-goalposts.md#s5--the-superseded-pane-fence-is-live-on-the-reattach-path--proven). + +`rememberPaneKeyForPty` (ipc/pty.ts:517-525) has two callers, both spawn (:5222, :6668). `restoreReattachedPtyRuntime` calls `runtime.registerPty` instead (ssh-relay-session.ts:2523), and `isSupersededPtyId` returns `false` for an unrecorded id by design (:284-296) — so the shipped superseded-PTY fence is INERT on the path it was built for. Collapse to one `bindPaneShell({ hostId, worktreeId, leafId, ptyId, incarnationId, relayInstanceId })` that, in one call, (a) resolves the current tab containing the leaf (refusing if none), (b) writes the durable record, (c) writes the in-memory `ptyPaneKey`/`paneKeyPtyId` fence maps using the paneKey composed from the CURRENT tab, (d) calls `registerPty`. All three paths call it and nothing else. + +===================================================================== +D8. COLLAPSE THE RESTORABLE FORK — and the offline/synchronous path +===================================================================== +`setLocalWorkspaceSession` forks on whether the INCOMING layout map is empty (persistence.ts:6450-6473): empty -> `isRestorablePtyBinding` (absence of a lease implies restorable, :6620-6631); partial -> `hasRestorableSshRemotePtyLease` (requires a live lease, :6670-6685). They disagree on the absent-record case, so whether a binding survives depends on whether a SIBLING LEAF had one. + +One predicate replaces both: RESTORABLE IFF `paneShellOwnershipByLeafId[leafId]` exists with state `attached` or `detached`. + +OFFLINE / SYNCHRONOUS ACCESS PATH (refutation B, honored exactly). `setLocalWorkspaceSession` is a synchronous `void` method invoked on every renderer publish including during quit (persistence.ts:6465, :6287, :6351). The loop at :6448-6462 already iterates `priorLayout.ptyIdsByLeafId` and therefore already holds a `leafId`, so the new predicate is a DIRECT map lookup on a top-level, main-owned, in-memory-mirrored disk record: no key composition, no lease-array scan, no `incomingHasAnyBinding` branch, no mux, no RPC, no host. It works with the host down and during quit — which is precisely what refutation B says cannot be replaced by asking the host. + +===================================================================== +D9. THE REATTACH ALGORITHM (SSH, on connect) +===================================================================== + +1. Obtain the consumer owner grant. Read `grant.relayInstanceId` (may be absent — old relay). +2. Work list = `getPtyIdsForConnection(target)` UNION `{ r.ptyId | r.hostId === 'ssh:'+target and r.state !== 'terminated' }`, every id normalized through `toRelaySshPtyId`. +3. PROCESS GATE. For each record: if both `grant.relayInstanceId` and `r.relayInstanceId` are present and differ, do not attach by that id. Set `detached`. Its shell, if any, is rediscoverable only through step 5. +4. For each remaining id, call `pty.attach { id, cols, rows }` — with NO expectedPaneKey and NO expectedTabId. + 4a. SUCCESS -> if a record exists and `response.incarnationId !== r.incarnationId`, throw (activation lease rolls back), set `detached`, no grant, no exit. Otherwise call `bindPaneShell(...)`: resolve the current tab containing `leafId`; if none, log and leave the shell running unbound (today's refusal, preserved); else write record (`attached`, `relayInstanceId = grant.relayInstanceId`), fence maps, `registerPty`. + 4b. NOT-FOUND -> if `grant.relayInstanceId` is present and equals `r.relayInstanceId`: `terminated`, retire, grant authorized (gated on E-1). Otherwise: `detached`, no grant, and route into the existing `restoreRequired = 'reattachAttemptsExhausted'` branch. No `pty:exit -1`, no `clearProviderPtyState`, no `deletePtyOwnership`. + 4c. ANY OTHER ERROR -> `detached` via the same existing branch. +5. Call `listProcesses` best-effort. If it REJECTS or admission truncates it: orphans = unknown; do nothing. If it RESOLVES: orphans = returned MINUS `(ptyId, incarnationId)` named by non-terminal records on this host. For each orphan with a reported `paneKey`, look up `parsePaneKey(paneKey)?.leafId`; if that leaf exists in the live layout and has no non-terminal record, CAS-adopt it via `bindPaneShell`. The rest are listed in the cleanup UI, never auto-killed. + +===================================================================== +D10. MIGRATION, SEQUENCING, ROLLBACK +===================================================================== +ORDER — each its own PR, each independently revertible: + +| | Step | Contents | +| --- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A | Identity-mismatch is not death | Renderer: `isProvenSshSessionGoneError` stops treating the mismatch marker as proof. Relay+main: delete the whole attach-identity apparatus (D2). Pure bug fix, no design dependency, ships FIRST; the renderer half must ship even before relays are redeployed. | +| E-0 | Stop lying about exits | Collapse the plain-not-found branch of `handlePtyReattachFailure` into the existing non-destructive `restoreRequired` branch (D3). Ships with, or immediately followed by, the D5 disconnected-pane affordance. | +| P | Single partition | D6: one accessor for every reader and writer, plus the fold migration, atomically. | +| F | Single bind producer | D7: `bindPaneShell`; makes the shipped fence live on the reattach path; introduces tab-from-layout resolution. | +| E-1 | Prove the grant executes | Production-id-shape oracle for `recoverTerminalPane`; record the actual behavior. | +| E-2 | Death rule | `relayInstanceId` on the grant + the D3 table. Conditional on E-1. | +| W | Projection | `paneKey` through relay -> `PtyProcessInfo` -> admission allowlist; incarnation-scoped subtraction; explicit-only kill (D4). | +| K | Re-key | The leaf-keyed record + D8 + D5 lifetime + `reassignSshTargetId` field rewrite + porting all lease readers. | + +E-1 CONTEXT (why E-2 is conditional). The chain `not-found -> expired -> 30s grant -> createTerminal` has one spawn-authorizing caller, `recoverTerminalPane` (src/main/runtime/orca-runtime.ts:16449-16490), gated on `getRecentExpiredSshLease(...)`, whose comparison is raw `lease.ptyId === ptyId` with no normalization (:6310). `lease.ptyId` is relay-native (persistence.ts:7184) while the graph's `pty.ptyId` is app-form `ssh:@@pty-N` (ssh-relay-session.ts:2523), so for a real SSH pane they can never be equal, and the branch also cannot be reached by a local pane (it requires an SSH lease). The covering test seeds both sides as `'pty-expired'` and registers with a NULL connectionId (orca-runtime.test.ts:1350-1370, :2932-2940) — a shape production cannot produce. Do not build grant-arbitration machinery before E-1 shows the branch executing. + +FORWARD MIGRATION AT K, per `SshRemotePtyLease`: + +- has `leafId` -> one record. `state`, `createdAt`, `updatedAt` copied VERBATIM (any surviving grace window reads `updatedAt`). `worktreeId` copied as an OPAQUE FULL STRING — the `::workspace:` folder-workspace suffix must survive, since matching is full-string equality (persistence.ts:7239, orca-runtime.ts:6308) and issue #12474 was a comparator that stripped exactly that. `ptyId` stays relay-native. `tabId` is DROPPED (D1). `relayInstanceId` absent -> the record falls to `detached` on first reconnect with no ambiguity to resolve. `incarnationId` absent on a legacy row -> treat as adoption-eligible rather than as a subtracting claim, so it cannot mask a recycled id. +- no `leafId` -> no record; recovered at first reconnect by the leaf-half `paneKey` match, or listed as an orphan. +- ALSO synthesize a record from any live layout binding (`ptyIdsByLeafId`) whose ptyId has no lease, so a bound-but-unleased pane is not silently demoted. +- Sequence AFTER the legacy numeric-leaf remap (persistence.ts:1858-1872) so every record keys on a UUID. + +PORT EVERY LEASE READER — the "write-only legacy projection" claim was FALSE and is corrected. Verified production readers of `sshRemotePtyLeases` outside persistence.ts: + +- `getRecentExpiredSshLease` (orca-runtime.ts:6295-6316) with `ptyId` UNDEFINED, feeding `hasRecentExpiredSshLeasePane` (:6318-6323) -> the headless-mobile terminal-tab filter (:5290-5299 region, the `onlyRuntimeOwnedTerminals` filter) and `hasLiveOrPersistedServeOrSshOwnedPtyBinding` (:6355-6360). These are a live VISIBILITY signal for paired mobile/HUB clients and are NOT killed by the namespace bug, because they pass `ptyId` undefined. Port: "a non-terminal record names this leaf" replaces "an `expired` lease within 30s". Visibility becomes bounded by the D5 lifetime rule instead of a timer; that behavior change is deliberate and must be covered by an oracle. +- `ssh:terminateSessions` (src/main/ipc/ssh.ts:1282-1300) enumerates leases and distinguishes owned from expired (#2626). This is the EXISTING kill affordance; the D4 orphan UI FEEDS it rather than duplicating it. It is re-expressed over records: non-terminal records plus projection entries, with kill always explicit (D4). +- `ssh:resetRelay` (ipc/ssh.ts:1370-1385) marks every live lease `expired` after force-killing the relay. Ported to: mark records `detached` (never `terminated` — the client killed the relay, which proves nothing about the shells). BEHAVIOR CHANGE, flagged for the owner: a user-initiated relay reset stops silently re-showing panes for 30s and instead shows the disconnected affordance. +- `ssh-relay-session.ts:1914, :2197` internal lease reads -> record reads. + +CROSS-VERSION READS. Pinned older builds read `sshRemotePtyLeases`. For ONE release the new writer emits a derived legacy projection of the array. It must emit RELAY-NATIVE ptyIds via `toRelaySshPtyId` — leaking app-form ids gives pinned builds leases matching nothing, a silent no-op that looks like a passing test. Because the record already stores the relay-native form, this is a copy, not a conversion. It carries no `tabId`-dependent semantics, so old builds that call `expectedIdentityForLease` simply get `null` and attach without an identity — which, after step A, is the correct behavior anyway. + +PARTIAL WRITE / ROLLBACK. Reuse the existing discipline (persistence.ts:7346-7360): snapshot, mutate in memory, `flushOrThrow`, undo on failure. One record, so this is a single-record transaction. Rollback of K: the legacy projection lets an older build boot on new state; the one-way loss is leafId-less rows, which the old build also could not act on. + +`reassignSshTargetId` (persistence.ts:7055-7086) today re-keys partitions, rewrites lease `targetId`s and drops recoveries. Because `hostId` is a FIELD and not part of the key, it only rewrites a field in place plus the reverse index; no re-keying. + +===================================================================== +D11. ORACLES — each must redden under a stated mutation +===================================================================== + +1. DETACH-TO-TAB OVER SSH, THROUGH THE REAL RELAY COMPARISON. Bind an SSH pane in tab A leaf L, run `detachTerminalPaneToTab` to tab B, disconnect, reconnect. Assert: exactly one shell on the host, no second agent resume, the pane reattaches and the ptyId lands in tab B's layout. THIS MUST BE RED BEFORE STEP A. If it is green today, the harness stubbed the relay comparison or omitted `ORCA_PANE_KEY`/`ORCA_TAB_ID` from the spawn env, and the whole detach oracle family is measuring nothing. Gate the program on it going red first. +2. Identity mismatch is not proof of death. Assert `isProvenSshSessionGoneError` is false for the mismatch string, no record reaches `terminated`, no grant. Mutation: restore `.includes(SSH_SESSION_EXPIRED)` as the sole predicate (reattach-failure-classification.ts:29). +3. Wrong-incarnation attach is abandoned, not adopted and not fatal. Relay returns a different `incarnationId` than recorded: assert no bind, no stream, `detached`, no grant, activation lease rolled back. Mutation: skip the response check. +4. Same-instance not-found is proof; different or absent is not. Two runs, recorded `relayInstanceId` equal -> `terminated` + grant; differing/absent -> `detached` + no grant. Mutation: flip the comparison. +5. Failed listing is not an empty listing. Make `listProcesses` reject, and separately make `admit` throw `agent_session_ownership_unknown`: assert zero records retired and zero orphans reported. Mutation: replace the failure with a resolved `[]` — must redden, proving the implementation does not reuse the `.catch(() => [])` shape at ipc/pty.ts:7333. +6. No fabricated exit on unknown. Drive `handlePtyReattachFailure` with a not-found and a differing `relayInstanceId`: assert `detached`, no grant, no `pty:exit -1`, and that provider state and ownership are NOT cleared. Mutation: restore the block at ssh-relay-session.ts:2641-2647. +7. Detach mid-publish does not release. Force a `session:set` flush between `setTabLayout(source)` and `setTabLayout(target)`: assert ownership is NOT released. Mutation: release on any publish missing the leaf. +8. Pane/tab delete releases. Delete a tab while its shell is live: assert the record is released, the shell IS an orphan, and no respawn is authorized. Mutation: remove the release rule — the shell must become invisible to both adopt and the cleanup UI. +9. Production id shapes in the recovery grant (E-1). Seed relay-native `pty-7`; register the runtime pty as `ssh:@@pty-7` with a NON-NULL connectionId; call `recoverTerminalPane`; assert the actual behavior. Mutation: swap either namespace. +10. E-2 false not-found. Same `relayInstanceId`, not-found caused by the wrong id form while the shell is in the Map under the correct id: assert NO `terminated` and NO grant. Mutation: skip `toRelaySshPtyId` on the attach path. +11. Projection is incarnation-scoped. Record `pty-1@incX`; restart the relay; it mints `pty-1@incY` for a different pane: assert the fresh shell IS an orphan and the stale record does NOT mask it. Mutation: subtract on ptyId alone. +12. `paneKey` survives `admit`. Mutation: remove it from the allowlist rebuild (pty-process-list-admission.ts:106-115). +13. Detached shell is still re-adopted. Seed a leafId-less lease whose relay-reported `paneKey` names a DIFFERENT tab than the live pane: assert the shell is attached exactly once and no second shell spawns. Mutation: match on full-string paneKey. This is the migration gate — green before K, re-run after. +14. Paired-client visibility survives the state rename. Record in `detached`, ptyId absent from every layout: assert `buildHeadlessMobileSessionTerminalTabs` still yields the tab. Mutation: drop the `expired`-equivalent — orca-runtime.ts:5964/:6290/:6322/:6359 must all be covered, not just the dead :16478 caller. +15. Cleanup UI reaches the user's own abandoned shells. Delete the repo row (new `repoId` on re-add) while shells run: assert they are offered for cleanup. Mutation: reinstate worktreeId-based "owned elsewhere" — must redden. +16. Nothing is killed implicitly. Any reattach/cleanup pass over foreign or unrecognized shells: assert zero kill RPCs. Mutation: auto-kill unclassified orphans. +17. One pane, one live shell across partitions. Two live shells for one `(worktree, tab, leaf)` with the binding only in `local`: assert exactly one is bound. Mutation: restore the ssh-first preference in `durablyBoundPtyIdForPane` (persistence.ts:7271). +18. P covers readers. Seed a binding only in `local`, call stable-pane resolve/retire with `connectionId` set: must find it. Mutation: revert either reader. +19. Adopt is exclusive. Two concurrent adopts of one orphan: one succeeds, the other gets a typed refusal. +20. Renderer cannot clobber ownership. Publish a stale full `WorkspaceSessionState` via `session:set`: assert the ownership map is byte-identical. +21. Offline quit path. Restorable predicate with store only and a null mux: must not throw, must not require an RPC (persistence.ts:6465). +22. Folder-workspace suffix. Two `::workspace:` instances on one path: a record for A must not reattach into B. +23. Target reassign carries ownership. `reassignSshTargetId(old, new)`: every record's `hostId` field and the reverse index follow, with no re-keying. +24. Windows/WSL relay kill. Assert the rules produce `detached`, never `terminated`, and that no UI copy asserts death. Mutation: assert-death — must redden on a Windows fixture even though it would pass on POSIX. +25. Old-relay degradation. `listProcesses` without `paneKey`, grant without `relayInstanceId`: projection non-empty, nothing killed, reattach falls back to the `getPtyIdsForConnection UNION records` work list, and the per-attach incarnation guard still rejects a recycled id. + +===================================================================== +D12. RE-TEST AGAINST THE SECTION-3 REFUTATIONS +===================================================================== +REFUTATION A LEG 1 — "a lease must name a live shell no pane owns." SURVIVES. Discovery never was the lease's job: reattach builds its list from `getPtyIdsForConnection(target) UNION` the durable rows (ssh-relay-session.ts:2211-2219), and the connect-time projection adds host-reported shells on top. Leaf-keying does not weaken this. D5's RELEASE-vs-RETIRE distinction is REQUIRED BY this leg: a record whose leaf is gone must be released (shell stays discoverable and adoptable) rather than deleted (knowledge lost) or terminated (respawn wrongly authorized). + +REFUTATION A LEG 2 — "a lease outlives the binding; expiry authorizes a 30s recreate." First clause survives exactly: `detached`/`terminated` are states on a main-owned, top-level record that persists after the layout binding is wiped. The recreate clause is PRESERVED AS A CONDITIONAL, not deleted: E-2 keeps a grant, gated on `relayInstanceId` equality, and only after E-1 shows the branch executes at production id shapes. Deleting the grant outright — proposed twice — is still refused as a simplification, because it dies to A leg 2 as written and rests on a read-not-run conclusion; it remains available as an E-1 OUTCOME. What does ship regardless is the user affordance, which covers every case a narrowed grant would drop. + +REFUTATION B — "make the host authoritative." SURVIVES, and is honored more cheaply than before. Ownership stays on local disk, top-level, main-owned, read synchronously inside `setLocalWorkspaceSession` during quit with the host down (D8). Everything this design changes is the record's KEY and WHAT MAY TRANSITION IT — never where it lives or how it is read. The host is consulted only while connected, and only for "which shells are in your Map?", "is this the same shell I bound?" (incarnation) and "are you the same process?" (relayInstanceId) — three questions it answers from data it already holds. Critically, D4's deletion of retire-on-absence is what keeps refutation B intact under load: a design that retired durable ownership because a remote listing timed out would have made the host authoritative by accident. + +REFUTATION C — a second authority architecture. Untouched, and this revision deletes more than the last: no decision table, no `hostEpoch`, no `os.uptime` math, no per-platform boot semantics, no paneKey transfer/alias layer, no attach-time identity apparatus, no orphan-ownership classifier, no second durable record. + +WHERE THE CUT IS. Plane 1 (delivery identity, credit ledger, chunk-and-ack, binary payloads, loopback WebSocket) proceeds in parallel. The cut is DURABILITY SCOPE vs EVIDENCE SOURCE, and this revision now applies that rule to all four inferences the prior round left standing: an error string means dead (deleted, D2), absence from a list means dead (deleted, D4/D5), a delivery-checkpoint flag means alive (deleted, D3), an arithmetic clock means rebooted (never built, D3). What remains on the wire is two optional fields: `relayInstanceId` on the grant and `paneKey` on the process summary. RC3 is entirely Plane 1's. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-overview.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-overview.md new file mode 100644 index 00000000000..ca48bdb9e64 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/design-overview.md @@ -0,0 +1,255 @@ +# Terminal session correctness — design overview + +Plain-language explanation of what breaks, why, and what we changed. No prior +context needed. + +--- + +## 1. The cast of characters + +When you look at a terminal in Orca, five different things are lined up behind +that one rectangle on screen. + +```mermaid +flowchart LR + subgraph YOU["What you see"] + PANE["Pane
a rectangle in a tab"] + end + subgraph APP["Orca's bookkeeping"] + BIND["Binding
this pane uses that shell"] + LEASE["Lease
a note saying: we own
a remote shell
"] + end + subgraph MACHINE["The actual computer"] + PTY["PTY
the shell process"] + HOST["Host
your Mac, or an SSH box"] + end + + PANE -->|bound to| BIND + BIND -->|points at| PTY + LEASE -->|claims| PTY + PTY -->|runs on| HOST +``` + +The pane is what you see. The **PTY** is the real shell process doing the work. +The **binding** is the note that connects them. On a remote machine there is also +a **lease** — a second note saying "we still own that remote shell." + +**Everything that went wrong is one of those notes pointing at the wrong thing.** + +--- + +## 2. The bug, in one picture + +You are working on an SSH machine. Your network hiccups. Orca reconnects. + +**What should happen:** your two terminals come back, same shells, same work. + +**What actually happened:** + +```mermaid +flowchart TD + A["You have 2 terminals"] --> B["Network hiccup"] + B --> C["Orca reconnects"] + C --> D["Now you have
19 terminals"] + D --> E["Hiccup again"] + E --> F["Now 20.
Most are ghosts you
never opened"] + + style D fill:#ffe6e6,stroke:#cc0000 + style F fill:#ffcccc,stroke:#cc0000 +``` + +That is a real report: **2 → 19 → 20**. Meanwhile the remote machine fills up +with shells nobody is using, until it refuses to start any more. + +A second, worse version: your AI coding agent gets **resumed twice**. Two copies +of `claude` writing into the same conversation file. One report had **five**. + +--- + +## 3. Why it happened — three root causes + +### Cause 1: the lease forgot which pane it belonged to + +Each lease is a note saying "we own remote shell X." The note _had_ a field for +"which pane," but nobody checked it. + +```mermaid +flowchart LR + subgraph BEFORE["Before — lease identified by shell only"] + P1["Pane A"] --> L1["Lease: shell-1"] + P1 -.->|reconnect makes
a new shell| L2["Lease: shell-2"] + P1 -.->|and another| L3["Lease: shell-3"] + N1["Nothing retires
the old notes"] + end + style N1 fill:#ffe6e6,stroke:#cc0000 +``` + +Every reconnect added a note and removed none. Next reconnect, Orca dutifully +restored **all** of them — one pane per stale note. + +**Fix:** a lease is now identified by _which pane_ it belongs to, not just which +shell. One pane, one live lease. Older notes are retired. + +> Retired means **marked expired, not killed**. The remote shell is deliberately +> left running — losing a note is not proof the shell died. + +### Cause 2: reconnecting could _create_ panes + +The function that says "pane A uses shell X" was also allowed to _invent_ pane A +if it didn't exist. That is correct when you open a new terminal. It is very +wrong when reconnecting. + +```mermaid +flowchart TD + R["Reconnect finds a
lease for shell-7"] --> Q{"Does its pane
still exist?"} + Q -->|"Yes"| OK["Reattach. Correct."] + Q -->|"No — before"| BAD["Invent the pane.
Ghost appears."] + Q -->|"No — after"| GOOD["Refuse. Leave the shell
running, unbound."] + + style BAD fill:#ffcccc,stroke:#cc0000 + style GOOD fill:#e6ffe6,stroke:#00aa00 +``` + +**Fix:** reattach now says _"bind only, never create."_ Spawning a new terminal +still creates, exactly as before. + +### Cause 3: a living shell was reported as dead + +The remote side has two different bad-news messages: + +| Real meaning | What it was reported as | +| ------------------------------------------------------------- | ------------------------------ | +| "This shell is gone." | `SESSION_EXPIRED` ✅ correct | +| "Shell is fine, I just need to re-establish the output pipe." | `SESSION_EXPIRED` ❌ **wrong** | + +Orca's reaction to "expired" is to start a fresh shell — and because it passes +the old session id along, the AI agent gets resumed a second time. **That is the +duplicate-agent bug.** + +**Fix:** the second case gets its own message, and respawning now requires +_positive proof_ the shell is gone. Anything unrecognised means "unknown", and +unknown never justifies starting a replacement. + +--- + +## 4. The one rule underneath all of it + +```mermaid +flowchart LR + E["Evidence"] --> A{"What does it
prove?"} + A -->|"Shell exited"| D["DEAD — cleanup allowed"] + A -->|"Can't reach it"| U["UNKNOWN"] + A -->|"Timed out"| U + A -->|"Not in a list"| U + A -->|"Tried 3 times"| U + U --> N["Do nothing destructive.
Wait. Retry. Ask."] + + style D fill:#e6ffe6,stroke:#00aa00 + style U fill:#fff4e6,stroke:#dd8800 + style N fill:#fff4e6,stroke:#dd8800 +``` + +**Unknown is not dead.** A disconnect, a timeout, an empty list, or three failed +retries tell you nothing about whether a process is alive. Every bug above is +some version of treating silence as a death certificate. + +We also made the liveness check able to _say_ "unknown". It used to return only +yes/no — so a provider whose network was down had no way to express "I can't +see, don't ask me" and answered "no", meaning dead. + +--- + +## 5. What we changed + +Six changes, ~214 lines of production code total. + +| # | Change | Stops | +| --- | ----------------------------------------------- | ----------------------------------------------- | +| 1 | Reattach binds, never creates | Ghost panes | +| 2 | Leases identified by pane | 2 → 19 → 20 growth | +| 3 | Heal already-corrupted lease data | Existing installs stuck at 20 | +| 4 | "Needs re-establishing" ≠ "expired" | Duplicate agent resume | +| 5 | Liveness can answer "unknown" | Live shells declared dead | +| 6 | One PTY's failure can't drop the shared channel | One bad pane killing every session on that host | + +### Change 6 in a picture + +```mermaid +flowchart TD + subgraph B["Before"] + X1["Pane 3 can't re-prove
its output stream"] --> X2["Give up after N tries"] + X2 --> X3["Drop the entire
connection to that host"] + X3 --> X4["Every pane, file transfer
and git command dies"] + end + subgraph A["After"] + Y1["Pane 3 can't re-prove
its output stream"] --> Y2["Park pane 3 only"] + Y2 --> Y3["Its shell keeps running.
Siblings untouched."] + end + style X4 fill:#ffcccc,stroke:#cc0000 + style Y3 fill:#e6ffe6,stroke:#00aa00 +``` + +### And a guard on every keystroke + +Orca queues your typing. If a pane switches to a different shell mid-flight, +queued keystrokes could land on the **new** shell. + +```mermaid +flowchart LR + K["Keystroke for shell-1"] --> C{"Is shell-1 still
this pane's shell?"} + C -->|"Yes"| S["Deliver"] + C -->|"No — pane moved on"| R["Refuse"] + C -->|"Pane unknown"| S2["Deliver
unknown ≠ stale"] + + style R fill:#fff4e6,stroke:#dd8800 +``` + +We did this **without changing the wire format** — Orca already keeps two lookup +tables in lock-step, so if they disagree, that _is_ proof the id is stale. No new +data is sent per keystroke. + +--- + +## 6. The approach we rejected + +A previous attempt built a **new authority architecture beside the old one**: ++60,903 lines of production code. It fixed **none** of the three root causes — +they were still present, untouched, underneath. + +```mermaid +flowchart LR + subgraph W["Rejected"] + O1["Old system
(3 bugs)"] + N1["New system
+60,903 lines"] + O1 -.->|"bugs still here"| O1 + end + subgraph R["Taken"] + O2["Old system
(3 bugs fixed)
+214 lines"] + end + style N1 fill:#ffcccc,stroke:#cc0000 + style O2 fill:#e6ffe6,stroke:#00aa00 +``` + +A second proposal of mine was also rejected in review — it would have added a +_second_ identity system beside an existing one, which is the same mistake in +miniature. Three of its factual claims turned out to be false when checked +against the code. + +**The lesson both times:** the machinery mostly existed already. The bug was that +it wasn't being _called_. + +--- + +## 7. What is still open + +| Thing | State | +| ------------------------ | -------------------------------------------------------------------------------- | +| The three root causes | Fixed | +| Duplicate agent resume | Root cause fixed; the codebase still carries 3 older patches for it | +| Orphaned remote shells | Left running on purpose. Not reachable from the UI yet — needs a recovery screen | +| The keystroke quarantine | Still needed. We proved deleting it re-opens a real `rm -rf` hazard | + +**On that last one:** there is a safety module that drops the tail of a half-typed +line after a recovery, because `echo hi; rm -rf x` can otherwise arrive as +`cho hi; rm -rf x` — the shell rejects `cho` and then happily runs `rm -rf x`. We +tried to delete it. We proved by experiment that we cannot, yet. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/finalized-design.html b/docs/reference/terminal-session-correctness-handoff-2026-08-07/finalized-design.html new file mode 100644 index 00000000000..afe8bcbbc86 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/finalized-design.html @@ -0,0 +1,275 @@ + + + + + + Terminal Architecture — Finalized Design + + + +
+
+

Terminal Architecture — Finalized Design

+

Synthesis of the “one protocol, three routes” proposal with a control-plane track it does not cover

+
+ +
+
Adopt
Data-plane proposal
+
+1 track
Control plane (missing)
+
REFUTED
“Delete the lease”
+
~374
Lines of reconciliation
+
~390
Remoteness branches
+
+ +
+

Verdict in one paragraph

+

The proposal is correct and its root cause is real — I verified it. Adopt it. But it is a data-plane design: framing, encoding, credit windows, backpressure. The bug that started this work is a control-plane bug, and none of its thirteen steps touch the records involved. The two tracks are independent and can run in parallel. My shipped work is a stopgap on the second track, framed around a symptom rather than a cause, and most of it should be deleted once the real fix lands.

+
+ +

1 · Two planes, one system

+

Nearly every disagreement here dissolves once you separate these.

+
+
What each plane owns⤢ zoom
+

proposal covers this

proposal is silent

CONTROL PLANE — who owns what

which pane owns
which shell

what survives
a restart

what may be
destroyed

DATA PLANE — moving bytes

framing · encoding

credit windows
backpressure

reconnect & resume

13 steps

0 steps
2 → 19 → 20 survives all 13

proposal covers this

proposal is silent

CONTROL PLANE — who owns what

which pane owns
which shell

what survives
a restart

what may be
destroyed

DATA PLANE — moving bytes

framing · encoding

credit windows
backpressure

reconnect & resume

13 steps

0 steps
2 → 19 → 20 survives all 13

+
+

Verified: none of the ladder’s core files reference the lease or binding records at all. You could ship all thirteen steps and still get 19 ghost panes on the third reconnect.

+ +

2 · The data-plane root cause — verified

+

This is the strongest finding in either document, and it is correct.

+

Orca copied a well-known persistent protocol’s 13-byte frame header, and kept two of its nine message types:

+
export const MessageType = { Regular: 1, KeepAlive: 9 } as const
+// dropped: Control · Ack · Disconnect · ReplayRequest · Pause · Resume · None
+

The seven dropped are exactly the ones that make the protocol persistent. The ACK field that survived feeds only unackedTimestamps — a seq→timestamp map read solely by the death timer. Nothing is retained; nothing is replayed.

+
+
Why three ledgers exist⤢ zoom
+

transport gives
no delivery guarantee

SSH stack rebuilds
retain + replay

runtime RPC rebuilds
retain + replay

daemon rebuilds it
lossily on purpose

three ledgers · three sets of bugs
4,847 lines in one of them

transport gives
no delivery guarantee

SSH stack rebuilds
retain + replay

runtime RPC rebuilds
retain + replay

daemon rebuilds it
lossily on purpose

three ledgers · three sets of bugs
4,847 lines in one of them

+
+
+

This reframes the duplication as three teams correctly solving a missing primitive, not carelessness. Fix the transport and the duplication loses its reason to exist. That is a genuine root cause — the framing I shipped earlier (“identity compared with the wrong key”) named a symptom class instead.

+
+ +

3 · Your principle, confirmed twice over

+

“SSH should behave like local, plus its own reconnection logic.” The codebase already proves it — for the other routes.

+
function getProvider(connectionId) {
+  if (!connectionId) return localProvider          // local AND daemon — one slot
+  const provider = sshProviders.get(connectionId)  // SSH — a parallel registry
+}
+
+
Three strategies, one exception⤢ zoom
+

the exception

SSH
neither

rides the local path
wearing a connectionId tag

~390 remoteness branches
+ 25 instanceof checks

works today

daemon
substitutes

swap the provider slot
0 branches added

paired runtime
encapsulates

hidden behind a transport
mostly negative guards

the exception

SSH
neither

rides the local path
wearing a connectionId tag

~390 remoteness branches
+ 25 instanceof checks

works today

daemon
substitutes

swap the provider slot
0 branches added

paired runtime
encapsulates

hidden behind a transport
mostly negative guards

+
+

The daemon is a 3,604-line provider that adds zero branches to the shared spine. SSH gets a second registry, and the tag then leaks outward as a condition ~390 call sites re-derive independently. Your instinct was not a preference — SSH is the only route that broke a pattern the codebase already implements correctly twice.

+ +

4 · What I got wrong

+ + + + + + + + +
ClaimStatusEvidence
“Identity compared with the wrong key” is the root causeSymptomThe real cause is one layer down — a transport with no delivery guarantee, and a tag instead of a substitution
My change consolidatesInverted~310 of ~405 added lines are SSH-only special case; every new function in the largest file is lease machinery
The superseded-keystroke fence protects reconnectInert thereIts maps have two writers, both spawn paths; relay reattach never populates them, so the guard permits every reattached PTY
“Less code proves a better design”Too bluntThe right control-plane fix is roughly net-neutral in lines; the payoff is a dissolved failure class, not a smaller diff
+
+

The fence failure is the thesis in miniature

+

A guard placed on the shared spine silently does not apply to the one route that does not ride the spine. That is not a coding slip — it is the predicted failure mode of tag-based divergence, and it happened to me while I was writing the fix for it.

+
+ +

5 · The control-plane defect

+

Two questions, one record, keyed for neither.

+
+
The key inversion⤢ zoom
+

today: one record

two different questions

which shell does
this pane own?

which shells exist
that nobody owns?

lease
keyed by (target, ptyId)
pane identity is optional payload

pane uniqueness is not structural
→ bolt on supersession, ranking,
rollback, dual matchers

~374 lines of reconciliation
9 states where records disagree

today: one record

two different questions

which shell does
this pane own?

which shells exist
that nobody owns?

lease
keyed by (target, ptyId)
pane identity is optional payload

pane uniqueness is not structural
→ bolt on supersession, ranking,
rollback, dual matchers

~374 lines of reconciliation
9 states where records disagree

+
+

Because the lease is keyed by shell rather than pane, “one pane, one live shell” is not expressible — it has to be enforced. My +209 lines are that enforcement: supersession, rank comparison, deferral, rollback. They exist only to compensate for the key.

+ +

Why the obvious fixes are both wrong

+ + + + + + +
ProposalVerdictWhy
Merge the lease into the pane bindingBlockedA lease must be able to name a live shell no pane owns, and must outlive the binding — expiry deletes the binding, then authorizes recovery for 30s
Delete the lease; let the host be authoritativeRefutedSee below — tested adversarially and it failed on all five probes
+
+
Why the host cannot be the authority⤢ zoom
+

no

no

no

make the remote host
the source of truth

does it hold
the state durably?

PTY table is an in-memory Map
no persistence layer at all

can the client
read pane identity back?

listProcesses and attach never return it
attach only compares, then throws
the one RPC that returns it has 0 callers

is the host reachable
when it matters?

the decisive one:
a synchronous disk read during quit
cannot become an RPC to a host that is down

no

no

no

make the remote host
the source of truth

does it hold
the state durably?

PTY table is an in-memory Map
no persistence layer at all

can the client
read pane identity back?

listProcesses and attach never return it
attach only compares, then throws
the one RPC that returns it has 0 callers

is the host reachable
when it matters?

the decisive one:
a synchronous disk read during quit
cannot become an RPC to a host that is down

+
+

I verified all three personally. The client-side record is load-bearing precisely because it works offline.

+ +

6 · The proposed control-plane fix

+

Don’t merge the records and don’t delete one. Give each question the key that answers it.

+
+
Split by question, not by transport⤢ zoom
+

after

OWNERSHIP
keyed by (host, pane)
same key local already uses

INVENTORY
keyed by (host, ptyId)
shells with no owner

which shell does
this pane own?

which shells exist
that nobody owns?

one pane, one shell
structural, not enforced

reattach work list ·
disconnected cleanup UI

supersession, ranking, rollback,
dual matchers all become unnecessary

after

OWNERSHIP
keyed by (host, pane)
same key local already uses

INVENTORY
keyed by (host, ptyId)
shells with no owner

which shell does
this pane own?

which shells exist
that nobody owns?

one pane, one shell
structural, not enforced

reattach work list ·
disconnected cleanup UI

supersession, ranking, rollback,
dual matchers all become unnecessary

+
+

Ownership becomes the same shape for local, daemon and SSH — one record per pane per host, with transport-specific payload (lease state and timestamps for SSH, nothing extra for local). That is your principle applied at the record layer. Inventory becomes its own small list, because “a live shell nobody owns” is genuinely a different fact, not a degenerate ownership row.

+

The 30-second recovery grant survives as a terminal state on the pane-keyed record, so nothing load-bearing is lost. And the offline consumers keep reading local disk synchronously, exactly as today.

+ +

7 · Where the proposal needs correcting

+ + + + + + + + +
Claim in the proposalAssessment
“Main is no longer in the data path at all” for a phone on an SSH hostOverstated — the pivot step forwards the host’s loopback socket to a port on your machine. Pairing, E2EE and the broker remain main’s. The ledger duplication collapses; the hop does not.
Target is “one wire contract”Incomplete — no step migrates the local daemon onto it. After the final step you have two protocols, not one. There is an unstated additional step, and it is large.
“The method layer is already transport-agnostic”True, and it volunteers its own counterexample. But 191 remoteness branches sit in the renderer above that boundary — including five separate re-declarations of one predicate — and no step addresses them.
Measured encoding cost (wire and CPU)Honestly reported — it states plainly that the absolute throughput is not a bottleneck, and argues from where the cost is paid instead. Not oversold.
+ +

8 · Combined roadmap

+
+
Two independent tracks⤢ zoom
+

independent — run in parallel

CONTROL PLANE — added here

pin behaviour with
oracles that bite

re-key ownership
by pane

split out
orphan inventory

delete the
compensating code

DATA PLANE — adopt as written

see it · capability hello

unify types · ledger ·
chunk-ack · lanes

binary payloads

boring first connect

SSH becomes
a port-forward

independent — run in parallel

CONTROL PLANE — added here

pin behaviour with
oracles that bite

re-key ownership
by pane

split out
orphan inventory

delete the
compensating code

DATA PLANE — adopt as written

see it · capability hello

unify types · ledger ·
chunk-ack · lanes

binary payloads

boring first connect

SSH becomes
a port-forward

+
+

The tracks touch disjoint files, so they can proceed simultaneously. The control-plane track should land its oracles first, because re-keying a durable record is a migration with a corruption story, and the existing tests pin the current key rather than the intended behaviour.

+ +

9 · What happens to the shipped work

+ + + + + + + + + + +
ChangeNowAfter the control-plane track
Reattach binds, never createsHolds the lineKeep — correct at any key
Pane-keyed lease supersession (+209)Holds the lineDelete — the key makes it structural
Corrupted-lease healingNeeded for existing installsFolds into the migration
“Needs re-establishing” ≠ “expired”Fixes duplicate agent resumeKeep — an error-taxonomy fix, orthogonal
Three-valued livenessCorrect generalizationKeep
Superseded-keystroke fenceInert on reattachFix or withdraw — decision needed
+ +

10 · Verification status

+

Stated explicitly, because two earlier claims in this program were retracted after checking.

+ + + + + + + + + + + + +
FindingStatus
Only 2 of 9 message types kept; ACK feeds the death timer onlyPersonally verified
Daemon substitutes via the provider slot; SSH uses a parallel registryPersonally verified
Pane maps have two writers, both spawn; fence inert on reattachPersonally verified
Relay PTY table is in-memory only; identity RPC has no production callerPersonally verified
Lease consulted from a synchronous, offline disk pathPersonally verified
Method layer transport-agnostic (0 / 0 / 27 references)Personally verified
~390 branch count, LOC ratios, the 9 disagreement states, ~374 reconciliation linesAgent-reported, spot-checked
Encoding throughput measurements in the proposalNot re-measured
+ +

11 · Decisions needed

+ + + + + + + + +
#Decision
1Adopt the data-plane proposal as written? My review found no defect in its reasoning — only two overstated claims and one missing step. It is independent of everything below.
2Approve the control-plane track? Re-keying a durable record needs a migration and a corruption story. It is roughly net-neutral in lines and deletes a failure class rather than a file.
3The inert fence — populate the pane maps on the reattach path, or withdraw the guard and its test? Shipping it as-is means a test asserting a protection that does not apply where it matters.
4The open PRs — merge as a stopgap that keeps the reported bug closed, or hold them and go straight at the control-plane track?
+ +
+ Companion to report.html (evidence for the shipped work). Click any diagram to zoom · scroll to scale · drag to pan. +
+
+ +
×
scroll to zoom · drag to pan · Esc to close
+ + + + diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/github-overlap-query.graphql b/docs/reference/terminal-session-correctness-handoff-2026-08-07/github-overlap-query.graphql new file mode 100644 index 00000000000..5008d103cec --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/github-overlap-query.graphql @@ -0,0 +1,324 @@ +query TerminalSessionCorrectnessRelatedWork { + repository(owner: "stablyai", name: "orca") { + n8129: issueOrPullRequest(number: 8129) { + ...IssueDetails + ...PullRequestDetails + } + n8275: issueOrPullRequest(number: 8275) { + ...IssueDetails + ...PullRequestDetails + } + n8585: issueOrPullRequest(number: 8585) { + ...IssueDetails + ...PullRequestDetails + } + n8618: issueOrPullRequest(number: 8618) { + ...IssueDetails + ...PullRequestDetails + } + n9034: issueOrPullRequest(number: 9034) { + ...IssueDetails + ...PullRequestDetails + } + n9092: issueOrPullRequest(number: 9092) { + ...IssueDetails + ...PullRequestDetails + } + n9093: issueOrPullRequest(number: 9093) { + ...IssueDetails + ...PullRequestDetails + } + n9138: issueOrPullRequest(number: 9138) { + ...IssueDetails + ...PullRequestDetails + } + n9562: issueOrPullRequest(number: 9562) { + ...IssueDetails + ...PullRequestDetails + } + n9585: issueOrPullRequest(number: 9585) { + ...IssueDetails + ...PullRequestDetails + } + n9819: issueOrPullRequest(number: 9819) { + ...IssueDetails + ...PullRequestDetails + } + n9820: issueOrPullRequest(number: 9820) { + ...IssueDetails + ...PullRequestDetails + } + n9827: issueOrPullRequest(number: 9827) { + ...IssueDetails + ...PullRequestDetails + } + n9833: issueOrPullRequest(number: 9833) { + ...IssueDetails + ...PullRequestDetails + } + n10118: issueOrPullRequest(number: 10118) { + ...IssueDetails + ...PullRequestDetails + } + n10208: issueOrPullRequest(number: 10208) { + ...IssueDetails + ...PullRequestDetails + } + n10235: issueOrPullRequest(number: 10235) { + ...IssueDetails + ...PullRequestDetails + } + n10385: issueOrPullRequest(number: 10385) { + ...IssueDetails + ...PullRequestDetails + } + n10415: issueOrPullRequest(number: 10415) { + ...IssueDetails + ...PullRequestDetails + } + n10744: issueOrPullRequest(number: 10744) { + ...IssueDetails + ...PullRequestDetails + } + n11006: issueOrPullRequest(number: 11006) { + ...IssueDetails + ...PullRequestDetails + } + n11265: issueOrPullRequest(number: 11265) { + ...IssueDetails + ...PullRequestDetails + } + n11339: issueOrPullRequest(number: 11339) { + ...IssueDetails + ...PullRequestDetails + } + n11342: issueOrPullRequest(number: 11342) { + ...IssueDetails + ...PullRequestDetails + } + n11495: issueOrPullRequest(number: 11495) { + ...IssueDetails + ...PullRequestDetails + } + n11574: issueOrPullRequest(number: 11574) { + ...IssueDetails + ...PullRequestDetails + } + n11575: issueOrPullRequest(number: 11575) { + ...IssueDetails + ...PullRequestDetails + } + n11596: issueOrPullRequest(number: 11596) { + ...IssueDetails + ...PullRequestDetails + } + n11622: issueOrPullRequest(number: 11622) { + ...IssueDetails + ...PullRequestDetails + } + n11729: issueOrPullRequest(number: 11729) { + ...IssueDetails + ...PullRequestDetails + } + n11800: issueOrPullRequest(number: 11800) { + ...IssueDetails + ...PullRequestDetails + } + n11801: issueOrPullRequest(number: 11801) { + ...IssueDetails + ...PullRequestDetails + } + n11803: issueOrPullRequest(number: 11803) { + ...IssueDetails + ...PullRequestDetails + } + n11804: issueOrPullRequest(number: 11804) { + ...IssueDetails + ...PullRequestDetails + } + n11904: issueOrPullRequest(number: 11904) { + ...IssueDetails + ...PullRequestDetails + } + n12036: issueOrPullRequest(number: 12036) { + ...IssueDetails + ...PullRequestDetails + } + n12134: issueOrPullRequest(number: 12134) { + ...IssueDetails + ...PullRequestDetails + } + n12140: issueOrPullRequest(number: 12140) { + ...IssueDetails + ...PullRequestDetails + } + n12220: issueOrPullRequest(number: 12220) { + ...IssueDetails + ...PullRequestDetails + } + n12241: issueOrPullRequest(number: 12241) { + ...IssueDetails + ...PullRequestDetails + } + n12264: issueOrPullRequest(number: 12264) { + ...IssueDetails + ...PullRequestDetails + } + n12339: issueOrPullRequest(number: 12339) { + ...IssueDetails + ...PullRequestDetails + } + n12447: issueOrPullRequest(number: 12447) { + ...IssueDetails + ...PullRequestDetails + } + n12448: issueOrPullRequest(number: 12448) { + ...IssueDetails + ...PullRequestDetails + } + n12456: issueOrPullRequest(number: 12456) { + ...IssueDetails + ...PullRequestDetails + } + n12474: issueOrPullRequest(number: 12474) { + ...IssueDetails + ...PullRequestDetails + } + n12477: issueOrPullRequest(number: 12477) { + ...IssueDetails + ...PullRequestDetails + } + n12568: issueOrPullRequest(number: 12568) { + ...IssueDetails + ...PullRequestDetails + } + n12600: issueOrPullRequest(number: 12600) { + ...IssueDetails + ...PullRequestDetails + } + n12634: issueOrPullRequest(number: 12634) { + ...IssueDetails + ...PullRequestDetails + } + n12683: issueOrPullRequest(number: 12683) { + ...IssueDetails + ...PullRequestDetails + } + n12699: issueOrPullRequest(number: 12699) { + ...IssueDetails + ...PullRequestDetails + } + n12702: issueOrPullRequest(number: 12702) { + ...IssueDetails + ...PullRequestDetails + } + n12743: issueOrPullRequest(number: 12743) { + ...IssueDetails + ...PullRequestDetails + } + n12749: issueOrPullRequest(number: 12749) { + ...IssueDetails + ...PullRequestDetails + } + n12751: issueOrPullRequest(number: 12751) { + ...IssueDetails + ...PullRequestDetails + } + n12760: issueOrPullRequest(number: 12760) { + ...IssueDetails + ...PullRequestDetails + } + n12768: issueOrPullRequest(number: 12768) { + ...IssueDetails + ...PullRequestDetails + } + n12798: issueOrPullRequest(number: 12798) { + ...IssueDetails + ...PullRequestDetails + } + n12882: issueOrPullRequest(number: 12882) { + ...IssueDetails + ...PullRequestDetails + } + n12903: issueOrPullRequest(number: 12903) { + ...IssueDetails + ...PullRequestDetails + } + n12987: issueOrPullRequest(number: 12987) { + ...IssueDetails + ...PullRequestDetails + } + n13013: issueOrPullRequest(number: 13013) { + ...IssueDetails + ...PullRequestDetails + } + n13110: issueOrPullRequest(number: 13110) { + ...IssueDetails + ...PullRequestDetails + } + n13111: issueOrPullRequest(number: 13111) { + ...IssueDetails + ...PullRequestDetails + } + p13110: pullRequest(number: 13110) { + ...ReviewDetails + } + p13111: pullRequest(number: 13111) { + ...ReviewDetails + } + } +} + +fragment IssueDetails on Issue { + number + title + url + state + stateReason + updatedAt +} + +fragment PullRequestDetails on PullRequest { + number + title + url + state + isDraft + merged + reviewDecision + mergeable + mergeStateStatus + headRefName + baseRefName + additions + deletions + changedFiles + updatedAt + commits(last: 1) { + nodes { + commit { + oid + statusCheckRollup { + state + } + } + } + } +} + +fragment ReviewDetails on PullRequest { + reviewThreads(first: 100) { + nodes { + isResolved + isOutdated + comments(last: 1) { + nodes { + url + author { + login + } + } + } + } + } +} diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/goalposts.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/goalposts.md new file mode 100644 index 00000000000..d6842d0d563 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/goalposts.md @@ -0,0 +1,683 @@ +# Goalposts and proof contract + +This file answers one question: **what exact evidence is required before an +agent may write “proven”?** + +The current status is **0/8 proven goalposts** and **2/13 proven +journeys**. Status may change only from evidence produced on the same rebased, +converged release candidate. Historical snapshot tests and independently useful +narrow PRs may be cited as partial evidence but cannot promote a row. + +## Recorded user decisions + +These amend the contract above. Only the user may add to this list. + +### D1 — G6 relaxed from strictly net-negative (2026-08-07) + +> "It's okay if we must increase LOC but try not to." + +G6's pass condition is no longer a strict inequality against the frozen +baseline. It is now: **minimise added production code, and justify every net +addition against the correctness it buys.** A net-positive total does not fail +G6 on its own; an unjustified one does. + +Why this was needed: the deletion budget the plan assumed does not exist. An +entrypoint-rooted import graph over all 20 real build entrypoints found that +51 of the 53 candidate files in `src/relay/*pty-source-*`, +`src/shared/pty-consumer-*`, and `src/main/ipc/ssh-pty-*` are reachable and +value-instantiated on live paths. Only 2 files (263 LOC) are unreachable, and 2 +of the candidates did not exist at the baseline so deleting them earns no +credit. Against roughly +1,021 LOC to offset, a strict inequality was not +reachable without deleting load-bearing code — which the governing rule forbids. + +Still binding: correctness may not be weakened to reduce line count, and a +replacement architecture added beside the old one does not earn its lines. + +## Proven journeys + +### Journey evidence not yet sufficient to promote + +**Journey 2 (daemon half).** `tests/e2e/daemon-restart-session-liveness.spec.ts`, +3 tests. Two mutations each redden exactly one clause, on macOS and Linux: +reverting three-valued `hasPty` reddens only the unknown-not-dead clause; +widening the sole-provider fallback reddens only the stale-generation clause. +The lead re-verified the first mutation independently. **Missing: physical WSL**, +which the journey names explicitly. That host is now unblocked (the distro has a +provisioned default user) and the run is outstanding. + +**Journey 12.** `tests/e2e/cross-version-wire/`, 13 tests against a real published +baseline. Reverting the restore-required publication to expiry reddens 7 of 13; +restore greens. Lead-verified. **Missing: live skew.** These are in-process wire +tests. The original ledger named live paired-runtime and SSH skew as the gap, and +an in-process decoder test does not close it. + +**Journey 4.** Sibling-pane isolation on one host reddens when +`mux.dispose('connection_lost')` is restored. **The cross-host clause cannot be +proven by mutation**: a mux belongs to one relay session per SSH target, so its +dispose cannot cross a host boundary — the cross-host test stayed green under the +mutation, which is the empirical receipt. That clause rests on +isolation-by-construction, and saying otherwise would be a false claim. + +**Journey 6.** `tests/e2e/ssh-maxsessions-remote-pid-binding-identity.spec.ts`, +4 tests against a real Docker OpenSSH container configured `MaxSessions 1`, the +cap read back from `sshd -T` inside each test. Three of the four clauses +discriminate, clause-selectively, in single runs (the spec is not `serial`, so a +red test never reports the others as "did not run"): + +- dropping `mayCreate: false` from the reattach binding write reddens only the + authority-reconnect test, with the unowned leaf grafted into the `local` + partition; +- marking leases `terminated` instead of `detached` in `beginShutdownDetach` + reddens only the two restart tests, with a cold-spawned shell beside the + surviving one. + +**Missing: the transport-disconnect clause does not discriminate.** Four guard +removals were tried and it stayed green under all of them, including publishing +`SSH_SESSION_EXPIRED` in place of `SSH_SOURCE_RESTORE_REQUIRED` and making +`isProvenSshSessionGoneError` return true for every error. A sever that leaves +the detached relay holding its delivery record reattaches through the checkpoint +path, so no reattach failure is ever classified and the respawn-requires-proof +guards are off that path. Inducing `restoreRequired` needs a lost or mismatched +delivery record, which this fault does not produce. That clause is therefore a +forward guard and cannot promote the row. Also missing: only Docker-on-macOS was +run; the explicit-close/proven-teardown retirement clause is not covered. + +**Journey 13.** Not proven. One of ten named dimensions measured. The +`isSupersededPtyId` fence costs roughly 14ns per call, but it was measured on +lifted predicates in plain Node, not through real Electron IPC — that part is an +inference, not a measurement. + +### Correction: Journey 12's cross-version tests exercise a route production does not have + +Recorded earlier that the cross-version suite "confirms the new +`SSH_SOURCE_RESTORE_REQUIRED` token mutates nothing on an old client." That +claim is withdrawn. + +An attempt to build a LIVE two-process skew oracle established that the token +never crosses a version boundary at all. It is minted in main +(`src/main/providers/ssh-pty-provider.ts:110`) and consumed in the same app's +renderer (`pty-connection.ts:8833`, `:9080`) over Electron IPC — always one +version. The only cross-version terminal boundary, paired client to HUB runtime, +goes through `remote-runtime-pty-transport.ts`, whose sole respawn trigger is +`SSH_SESSION_EXPIRED` (line 1481), and whose reattach never reaches +`SshPtyProvider.spawn`. + +The in-process suite injects the token into `terminal.resolvePane`, which is a +pure lookup and not a route production takes. So those 13 tests are a decoder +guard, not evidence about old clients. + +Two consequences, both good: the wire-compatibility risk this branch was thought +to introduce **does not exist**, because there is no version boundary for the new +token to cross. And Journey 12 needs a different oracle entirely — one aimed at a +boundary that is genuinely cross-version. + +### Journey 6 — evidence, and why it is not promotable + +`tests/e2e/ssh-maxsessions-remote-pid-binding-identity.spec.ts`, 4 tests, each +with its own container and Electron profile, against real OpenSSH with +`MaxSessions 1` read back from `sshd -T` rather than assumed. Remote pids are +read on the container two independent ways and must agree, each carrying its +kernel start time. + +Two mutations discriminate and are disjoint: removing `mayCreate: false` reddens +only the reconnect clause; marking leases `terminated` instead of `detached` at +quit reddens only the two restart clauses. + +**Not promotable:** the "same remote PID and exact binding survive a transport +disconnect" clause is a forward guard. Four separate guard removals left it +green. It asserts a real property, but nothing shipped is load-bearing for it, +so it cannot be claimed as proof of this branch's work. + +### Journey 3 — evidence, and why it is not promotable + +`tests/e2e/ssh-lazy-discovery-skipped-host-restart.spec.ts`, 3 tests, two real +containers, sampling sshd's own accept log and live session census 20+ times over +22 seconds with the in-use host as a positive control. + +**Not promotable:** no mutation reddens clause 3 alone. The genuine cross-host +lease-scoping guard is load-bearing, but removing it breaks the sibling host +during setup, so the failure carries no clause information. + +### Journey 2 — Daemon and physical WSL (proven 2026-08-08) + +Oracle: `tests/e2e/daemon-restart-session-liveness.spec.ts`, 3 tests, plus +`tests/e2e/helpers/daemon-shell-process-identity.ts`. The PTY leader is a real +login shell that reports `$$` back through the production write path +(`DaemonPtyRouter.write` -> daemon socket -> PTY), and that pid is resolved to a +kernel start time, so a look-alike respawn cannot pass as a survivor. + +It replaced a spec that never crossed the daemon boundary and whose successor +generation owned nothing, which made "the live successor is neither killed nor +replaced" vacuous. + +| Environment | Result | Discrimination watched | +| -------------------------------------------- | -------- | --------------------------------------------------- | +| macOS 26.3.1 arm64 | 3 passed | 2 mutations, each reddening one clause | +| Ubuntu 24.04 x86_64 native | 3 passed | same 2 mutations, same single-clause reds | +| WSL2 Ubuntu 26.04 on a physical Windows host | 3 passed | reverting three-valued `hasPty` reddens test 1 only | + +Clause-selective on all three. The spec runs `mode: 'serial'`, so a red test 1 +reports 2 and 3 as "did not run" rather than passing — selectivity was therefore +established by re-running 2 and 3 _alone under the same mutation_ and watching +them stay green, not by assuming it. + +Mutation A (`hasPty` reverted to `activeSessionIds.has(id)`) reddens only the +unknown-not-dead clause. Mutation B (widening the sole-provider fallback in +`daemon-session-owner-resolution.ts`) reddens only the stale-generation clause. +The lead independently reproduced Mutation A on macOS. + +Also confirmed on the WSL host, independently of the spec: an Orca WSL-mode +terminal now starts and returns real output. It could not start before — the +distro had no provisioned default Unix user, so every interactive `wsl.exe` +launch blocked on first-run provisioning. + +Limits, stated rather than implied: + +- The WSL run used `ELECTRON_RUN_AS_NODE=1`, which is what this oracle needs + (real daemon processes and real PTYs, no renderer). It does **not** show that + Electron's GUI starts under WSL; no display server was started and that + remains an open question for any journey needing a window. +- WSL evidence is against `d74f5ed0eae` and on Node 22 rather than the required 24. The other two platforms ran the same oracle on Node 24. +- `src/main/providers` is red on that distro for an unrelated reason: + `local-pty-shell-ready.test.ts` pins an exact OSC 133 marker count and saw 7 + splits where it expects 4. The WSL run attributed that to bash 5.3.9, but that + is **not** the cause — macOS runs the same bash 5.3.9 and the spec passes there + 67/67. The trigger is environmental to that distro, most plausibly a + system-wide bashrc contributing prompt hooks, and the underlying defect is that + the spec asserts an absolute count of markers it does not own. Outside this + journey's surface, so left for its owner rather than reinterpreted blind — but + it means "the unit suites are green on WSL" would be false. + +### Journey 1 — Local macOS, Linux, and Windows (proven 2026-08-08) + +Oracle: `tests/e2e/local-terminal-restart-binding-identity.spec.ts`. Two tests — +the same pane, full binding and OS shell process survive renderer reload and app +restart; and a stale pre-spawn session write is rejected instead of retiring the +live binding. + +Process identity is proved by the shell reporting its own pid through the +production write path, plus the kernel-reported start time, so a recycled pid +cannot pass as a survivor. + +| Platform | Result | Discrimination watched | +| --------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| macOS 26.3.1 arm64 | 2 passed | mutation reddens; restore greens | +| Ubuntu 24.04 x86_64, native | 2 passed | 4 cycles, incl. deleting `restorableBindings` reconciliation — reddens test 2 only | +| Windows 11 26200, native | 2 passed | A: forcing `shutdownDaemon()` in will-quit reddens test 1 (pid 13756 -> 8852, start times 5.4s apart). B: disabling the same reconciliation reddens test 2 only | + +Every run used an isolated TMPDIR, because the harness keys its seeded-repo +pointer on a machine-global tmpdir path and concurrent runs can both fabricate +and mask a red. + +Selectivity holds on two platforms: mutation B reddens only the stale-operation +test and leaves the restart test green, so the two clauses are independently +proved rather than jointly. + +Residual limit, stated: "every stale exact operation" is proved for the +pre-spawn session-write class. Local `pty:write`/`resize`/`signal` are fenced by +`isSupersededPtyId` with its own oracle, but that fence compares a binding, not +an incarnation — see `binding-identity-design.md`. + +## Universal proof rule + +A gate is `proven` only when both exist: + +1. the complete behavior is reachable through every named production path; and +2. the named proof exercises that behavior and its failure boundaries on the + final candidate. + +Every proof receipt must record: + +- candidate commit SHA and exact merge base; +- unfixed baseline SHA used for red/green discrimination; +- exact command or manual journey protocol; +- OS, architecture, filesystem, runtime, Git, SSH, daemon, relay, client, and + host versions relevant to that journey; +- UTC start/end time, exit status, counts, and artifact/log location; +- the production caller, persistence boundary, transport, and cleanup path + exercised; +- the expected oracle and the observed result; and +- independent reviewer identity and unresolved-finding count. + +For a new regression oracle, demonstrate that it fails for the intended reason +on the unfixed baseline and passes on the candidate. A test that passes both is +a forward guard and cannot prove the fix. + +## G0 — One design contract + +**Current status: partial.** + +G0 is proven only when: + +- every reachable production path follows one reconciled identity, host + boundary, operations, delivery, migration, compatibility, and minimal-shape + contract; +- there is one final-host authority service, thin transport adapters, one app + projection/controller, and one bounded pre-cutover legacy importer; +- no adapter or renderer owns a parallel authority state machine; +- all retained existing primitives are mapped by semantics, not similar names; +- the lost-consumer/compaction liveness gap has a safe, bounded, authenticated, + operator-reachable resolution that does not infer death from time; and +- an independent production-graph audit finds no contradictory path. + +The design document alone, a behavior contract, or focused tests do not prove +G0. + +## G1 — One final-host authority + +**Current status: partial.** + +G1 is proven only when local, daemon, WSL, direct SSH, nested SSH, paired +runtime, and remote server all resolve: + +- a stable identity minted or validated by the final PTY-owning host; +- a canonical host-local namespace for worktree, folder, and floating + workspaces; +- one exact pane-generation/PTY-incarnation binding; +- host connections keyed by final-host identity with lazy discovery; +- concurrent host isolation; and +- namespace-local admission, failure, grant, handover, and retirement. + +`connectionId`, SSH target ID, client repository ID, path spelling, or +`worktreeId` may be routing metadata. Their existing names and usage counts are +not proof that they satisfy final-host identity or namespace semantics. + +Proof requires the applicable live journeys below, including simultaneous hosts +and independent client/host updates. + +## G2 — Exact operations only + +**Current status: partial.** + +G2 is proven only when input, resize, signal, close, output, and exit are fenced +by the full binding captured before any await: + +- authority host; +- namespace; +- pane generation; +- owner/writer incarnation; +- physical PTY; +- PTY incarnation; and +- negotiated operation/source generation where applicable. + +Stale, partial, absent, timed-out, disconnected, or unknown evidence must not +affect a successor. An authoritative operation must never retry through an +ID-only provider call or a legacy mutation path. + +Proof must cover all operations across local, daemon, WSL, SSH, paired runtime, +remote server, renderer fallback, restart, concurrent replacement, and both +mixed-version directions. Store-row counts and source-text assertions are not +sufficient. + +## G3 — Durable ordered delivery + +**Current status: partial.** + +G3 is proven only when the final production design provides all observable +properties below, even if its internal mechanism differs from the preserved +construction design: + +- complete boundary snapshot before later events; +- producer held while boundary/replay is established; +- contiguous replay before reconciliation and live resume; +- durable semantic outcomes, including exit and state needed by a newly + attached consumer; +- durable idempotent main-process projection before acknowledgement; +- final-host-owned cumulative acknowledgement or an explicitly approved + equivalent with the same crash/replay guarantees; +- renderer snapshot-plus-delta observation; +- app, renderer, host, and transport restart resume; +- gap detection and resnapshot without silent omission; +- bounded memory, queues, pages, listeners, timers, and retained output; +- independent consumer retirement and safe compaction liveness; and +- no app-side duplicate cursor, settlement, receipt, or suffix-reconciliation + authority. + +Proof must include crash-before/after-ACK cuts, lost responses, disconnected +replay, gap recovery, slow/stalled consumers, retired and permanently lost +consumers, paired/remote restart, mixed versions, and scale. + +## G4 — One-way legacy cutover + +**Current status: partial.** + +G4 is proven only when each namespace performs, in order: + +1. explicit capability negotiation; +2. a brief legacy-write freeze; +3. exact non-mutating inventory; +4. a deterministic import plan; +5. validation with ambiguity kept visible and non-destructive; +6. one self-contained durable authority commit; +7. topology attachment; and +8. exact client opening through the authoritative path. + +There must be no dual writer, destructive inference, authority-to-legacy +fallback, or second durable migration catalog after cutover. Old peers remain +on an unchanged isolated legacy surface or fail before mutation. + +Proof requires crash cuts at every phase, replay from the self-contained commit, +ambiguous-row isolation, independent namespace failure, and legacy-writer and +reconciliation deletion. + +## G5 — Wire and platform compatibility + +**Current status: not started.** + +G5 is proven only when all exchanged changes follow the remote-wire +compatibility contract and the final candidate passes: + +- old client to new host; +- new client to old host; +- native macOS; +- native Linux at Ubuntu 20.04 / glibc 2.31 compatibility floor; +- native Windows; +- physical WSL, including Git Bash/`.cmd` boundaries where relevant; +- Docker OpenSSH; +- daemon; +- direct and nested SSH; +- paired runtime; +- remote server; +- git worktree; +- folder workspace; +- floating workspace; and +- drive-letter and UNC namespace paths. + +Run both skew directions independently across every changed deployment boundary: +app↔daemon, app↔SSH relay/final host, paired client↔paired runtime, remote +client↔remote server, and mobile/E2EE RPC where affected. A single in-process +codec test or one client/host pairing cannot stand in for this matrix. + +New opcodes or semantics require explicit capability negotiation. An optional +field that parses on an old peer does not by itself prove that old behavior +remains correct. + +Mocking `process.platform`, running Linux inside Docker, or passing in-process +wire unit tests does not prove the corresponding native or live-skew row. + +## G6 — Simpler, minimised production code + +**Current status: partial; structural clauses remain open.** + +Decision D1 replaces the original strict inequality: the final integrated +program must minimise production source and justify every net addition against +the correctness it buys. + +The default baseline is +`5ed45739e94bdf6460364e033bfcec9b32c0b42a`, the base recorded by GitHub for +PR #12600. This broader program subsumes #12600. Changing the baseline requires +an explicit user decision recorded before more implementation begins. + +G6 is proven only when: + +- aggregate program-attributable production source net LOC is **minimised and + every net addition justified** against the frozen baseline — see decision D1 + under "Recorded user decisions", which replaced the original strict + inequality once the assumed deletion budget was shown not to exist; +- every program-attributable prerequisite merged after the baseline and every + stacked PR is included, even if a later rebase places it in `main`; +- overlapping changes are recomputed from the frozen baseline to the final tree + so additions and later deletions are not double-counted; +- unrelated upstream or user deletions cannot offset program additions; +- production, test, documentation, CI/runner, generated, and vendored changes + are reported separately; +- every new production module is reachable from a real entrypoint; +- no test fixture remains under production compilation; +- there is one identity comparison, transition implementation, exact-operation + client, mutation admission path, and delivery state machine; +- no re-export shim or one-type module exists solely to preserve construction + layering; +- no superseded quarantine, sliding-window, retry-verdict, reconciliation, + duplicate cursor, receipt ledger, legacy writer, or migration bridge remains + reachable after cutover; and +- an independent reachability and duplicate-state-machine audit is clean. + +Tests or docs cannot offset positive production LOC. A smaller narrow PR is not +proof if the final stack remains net positive. Deleting correctness or platform +coverage to hit the number is prohibited. + +Classify by behavior, not directory name: shipped runtime code, migration code, +and build-time code that enforces a shipped artifact invariant are production; +test-only runners and fixtures are tests even when misplaced, and their presence +under production compilation independently fails this gate. Publish the final +file-by-file classification so the count cannot be moved between buckets. + +### G6 clause assessment (2026-08-08) + +Checked against the current branch rather than assumed: + +| Clause | State | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| aggregate net production LOC minimised and justified (D1) | +228, each addition justified in its commit; 201 LOC deleted after verifying unreachability from all 20 build entrypoints | +| every new production module reachable from a real entrypoint | holds — no new unreachable module was added | +| no test fixture under production compilation | not audited on this branch | +| one identity comparison / transition / exact-op client / admission path / delivery state machine | **fails** — several remain, and this is the clause the rejected binding proposal would have made worse by adding a second identity comparison beside `resolveStablePaneOwner` | +| no re-export shim or one-type module for layering | holds for this branch's additions | +| **no superseded quarantine, sliding-window, retry-verdict, reconciliation, duplicate cursor, receipt ledger, legacy writer, or migration bridge reachable** | **fails** — `terminal-input-quarantine.ts` is imported by `pty-connection.ts:98` and `terminal-pane-recovery.ts:6` | +| independent reachability and duplicate-state-machine audit clean | not run | + +On the quarantine specifically: it is **not** subsumed by the superseded-PTY +fence, and claiming otherwise would be wrong. The fence refuses writes aimed at +a stale ptyId. The quarantine guards the user's _subsequent_ typing — the tail +of a half-typed line — landing on the successor shell under its current and +correct ptyId, which the fence never sees. + +Deleting it therefore requires contract property B: a _different_ shell surfaces +unresolved and never silently receives the pane, at which point there is no +mangled tail to suppress. That is a behaviour change to the recovery path, not a +deletion, and an earlier attempt to shortcut it was rejected for reintroducing +the `echo hi; rm -rf x` hazard by disarming per-pane state that is keyed per-tab. + +G6 is therefore not promotable, and its blocking clauses are structural rather +than arithmetic. + +### The input quarantine is load-bearing, not superseded (2026-08-08) + +G6's clause lists "no superseded quarantine ... remains reachable" and +`terminal-input-quarantine.ts` was assumed to be one. It is not, and the +evidence is direct. + +**The hazard is live.** Disabling the single call site in `pty-connection.ts` +and running the pane's own oracle reproduces it verbatim, lead-verified: + + AssertionError: expected "vi.fn()" to not be called with arguments: + [ 'cho hi; rm -rf x' ] + +Deleting the module without a replacement re-opens `rm -rf` execution. + +**Contract property B was costed by building it, not estimated.** Threading the +incarnation to the renderer compiles at **+26 production LOC**, and completing it +(publishing an incarnation from `resolveTerminalPane`, plus a new exported reader +for the module-private `ptyIncarnationById` map) is about **+33**. The +cross-remount state the comparison needs must outlive the destroyed pane, so it +becomes a module of roughly the size of the one being deleted — the two in-tree +precedents are 88 and 86 lines. Adding a renderer-side identity comparison would +also worsen G6's already-failing "one identity comparison" clause. Floor: about +**+140 production LOC to delete 88**. + +**And the route is not uniformly available.** `RuntimeTerminalCreate` and +`RuntimeTerminalResolvePane` carry no `incarnationId`; remote connect results are +built without one; and the transport latches `resolvePaneUnavailable` when a host +answers `method_not_found`. Mixed client/host versions are the normal state, and +an optional field does not make an old host publish it. So a paired client reads +_unknown_ — which under this program's own governing rule is not proof of "same +shell". Requiring proof makes every remote reattach surface unresolved; not +requiring it needs a fallback, and the only correct fallback is this quarantine. +Either way the module stays reachable. + +`endpointReplaced` is also routine rather than rare — a daemon death remounts +every live pane — so property B would convert each into a manual per-pane +reconnect, which is the coverage deletion G6 explicitly prohibits. + +**Consequence:** this clause of G6 cannot be closed by deletion. Either the +clause is amended to recognise the module as load-bearing, or the program accepts +a net-positive change to replace it with something weaker on remote hosts. That +is a user decision (call it D5), not one to assume. + +### G6 clause: test fixtures under production compilation (audited 2026-08-08) + +Audited by importer rather than filename, then checked against what the build +actually emits. **The clause is already satisfied on the meaning that matters, +and cannot be closed by moving files on the other meaning.** + +36 candidates; 4 have genuine production importers and are correctly placed. The +other 32 (~3,300 LOC) have zero non-test importers. + +**They do not ship.** Spot-checked the emitted bundle for +`terminal-restore-parity`, `ipcEventsTestHarness`, `storeTestHelpers` and +`sshRelayNativeDepsInstallFixture`: none appears in `out/`. Rollup drops them +because no production entrypoint reaches them. Under "compiles into the shipped +product", this clause holds today. + +**Moving them would close nothing under the other reading.** +`config/tsconfig.node.json` and `config/tsconfig.tc.web.json` declare `include` +globs such as `../src/main/**/*` with **no `exclude` at all**. A `__tests__/` +directory is matched by that glob exactly as any other path is, and so is every +`*.test.ts` file in the repo. Relocating 32 fixtures would not remove one file +from typecheck scope. + +A sweep was started and stopped once this was verified, rather than landing 32 +moves across areas this program does not own for no measurable gain. + +If the intent behind the clause is that typecheck scope should exclude test code, +that is a repo-wide tsconfig change affecting every test file — different work +with a different owner, and it should be stated as such rather than pursued by +relocating fixtures. + +One genuine defect was found and fixed while auditing: +`terminal-pane/xterm-bypass-event-fixture.ts` and +`terminal-pane/__fixtures__/xterm-bypass-event.ts` were byte-identical apart from +an import path, and the `__fixtures__` copy had zero importers — a half-finished +move left in place. The dead copy is deleted and the live one completed its move. + +## G7 — No regression and reviewable comprehensive change + +**Current status: not started.** + +G7 is proven only on the rebased, converged candidate after G0–G6 and all +thirteen journeys are proven. It requires: + +- correctness and security gates; +- A/B input latency and output throughput; +- backpressure and bounded-memory results; +- renderer/app/daemon/relay restore and startup results; +- large-pane, long-session, and multi-host scale results; +- native packaging/startup on macOS, Linux, and Windows; +- WSL, Docker SSH, paired, remote, folder, floating, worktree, drive, and UNC + coverage; +- both live mixed-version directions; +- final categorized LOC census; +- independent repository review with no unresolved P0–P2 findings; +- release-readiness review with no unresolved correctness, security, + compatibility, or performance findings; and +- a detailed comprehensive PR whose claims match the receipts. + +Before implementation, record a performance protocol that makes “no +regression” falsifiable: + +- fixed candidate and baseline builds, hardware, OS, power mode, network shape, + pane/session population, payloads, and background-load policy; +- warm-up policy, randomized A/B order, sample count, raw-data location, and + statistical method; +- input latency, output throughput, memory, backpressure, restore, startup, and + large-pane metrics with directionality; +- deterministic ceilings for writes, scans, queues, listeners, timers, and + allocations on hot paths; and +- a predeclared equivalence/no-regression bound no larger than measured baseline + noise. A nonzero bound handles measurement noise; it is not permission for a + known slowdown and requires explicit user approval. + +Unless an independently reviewed protocol justifies another count, use at least +five warm-up trials and thirty measured trials per latency/startup/restore +configuration, retain raw samples, and report confidence intervals. Throughput, +backpressure, and memory tests must also include a fixed-duration steady-state +run and a leak-slope result. Choose all workloads and thresholds before looking +at candidate results. + +Green CI, thousands of tests, mergeability, or “reviewable for what shipped” do +not prove G7. + +## Thirteen required production journeys + +Every row is currently **not proven**. + +The issue-to-journey matrix in +[`related-open-work.md`](./related-open-work.md#mandatory-issue-to-journey-matrix) +is part of these journeys, not optional context. Every bound incident needs a +red-on-baseline/green-on-candidate oracle, or explicit evidence plus user +acceptance that it is unrelated. + +| # | Journey | Required oracle | +| --: | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Local macOS, Linux, and Windows | The same pane, full binding, and OS process survive renderer and app restart; every stale exact operation is rejected. Run natively on all three OSes. | +| 2 | Daemon and physical WSL | The same PTY survives client and daemon reconnect/restart boundaries; generation skew fails closed without killing or replacing a live successor. | +| 3 | Lazy discovery and skipped-host restart | An unused host is not probed eagerly. After a restart that skipped it, lazy rediscovery restores only that host's sessions and never adopts host-current or sibling-host state. | +| 4 | Concurrent multi-host connections | At least two distinct final-host connections operate simultaneously. One host's disconnect, CAS, timeout, or failure cannot affect the other. | +| 5 | Namespace-partial admission failure | One namespace on a multiplexed connection fails challenge/CAS/grant publication while another commits. Only the failed host-plus-namespace is fenced. | +| 6 | Docker OpenSSH with `MaxSessions=1` | The same remote PID and exact binding survive disconnect and client restart. Authority restart imports exactly or exposes unresolved recovery without creating, killing, or adopting. Explicit close or exact proven teardown durably retires the lease and process; unknown ownership stays visible and recoverable rather than being killed. Count actual remote processes, panes, tabs, bindings, leases, and session-cap slots before and after a settle interval. | +| 7 | Two independent Docker SSH hosts | Two simultaneous final hosts keep endpoint credentials, principals, namespaces, sessions, cursors, failures, and cleanup completely isolated. | +| 8 | Paired client and remote server | The final host remains authoritative across independently updated peers, pairing reconnect, client restart, and remote-runtime restart. | +| 9 | Worktree, folder, floating, drive, and UNC namespaces | Each resolves the same stable host-local namespace across spelling/restart changes, without using client repository ID or target ID as identity. | +| 10 | Stable proof and exact retry | One bounded device proof identity admits fresh process/session nonces. A lost response retries the exact challenge/request; changed, replayed, cross-host, cross-namespace, or host-current state is rejected. | +| 11 | Identity reset and re-enrollment | Crash-resumable host retirement, relay revoke acknowledgement, transport closure, local credential removal, and atomic successor publication occur in order. Offline and old peers remain explicitly pending. | +| 12 | Mixed versions in both directions | No unknown opcode or ungranted publication mutates state. Unsupported challenge, grant, delivery, or operation semantics stay on isolated legacy behavior or fail before mutation. | +| 13 | Performance and scale | Under the predeclared protocol above, input/output latency, throughput, backpressure, memory, reconnect/restore, startup, large-pane, long-session, and multi-host ceilings show no regression against the fixed baseline. Raw samples, confidence intervals, deterministic counters, and leak slopes satisfy their predeclared bounds. | + +## Cross-cutting correctness cases + +Every relevant journey must exercise: + +- stale, missing, unknown, rejected, timed-out, and disconnected evidence; +- concurrent replacement and sibling-host/namespace isolation; +- lost request and lost response; +- cancellation and partial setup cleanup; +- crash immediately before and after every durable boundary; +- restart from disk rather than process-memory state; +- duplicate and out-of-order delivery; +- gaps, overflow, and slow/stalled consumers; +- explicit close versus detach; +- eventual exact retirement after explicit close or proven teardown while + uncertain ownership remains intact and visible; +- legacy data with missing optional fields; +- relay/daemon incarnation reuse; +- sleep/resume and clock movement where timers schedule retries; +- exact remote process/PID census, not only persisted-row state; and +- cleanup that requires positive identity proof. + +## Forbidden proof substitutions + +- A mock is not a native-platform journey. +- A source grep is not a production call-path journey. +- A row marked `expired` is not proof that its remote process exited. +- Optional pane metadata plus an O(n) repair scan is not structural uniqueness. +- An empty list from an unavailable provider is not proof of absence. +- A timer or retry budget is not proof of death. +- A broad test count is not a correctness oracle. +- A test that passes unfixed code is not evidence that a change fixed the bug. +- An open or green PR is not shipped behavior. +- Historical construction receipts are not proof for a rebased candidate. +- Prior art or an uncited LOC comparison cannot delete a requirement. + +## Promotion template + +Before changing any row to `proven`, add a receipt containing: + +```text +Gate or journey: +Candidate SHA: +Merge-base SHA: +Unfixed/red SHA: +Production path exercised: +Exact command or manual protocol: +Environment and versions: +Expected oracle: +Red result: +Green result: +UTC start/end: +Artifact/log: +Independent reviewer: +Unresolved P0/P1/P2: +LOC/performance impact: +``` + +If any field is missing, the row remains partial or not started. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/new-design-goalposts.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/new-design-goalposts.md new file mode 100644 index 00000000000..fce53501a7c --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/new-design-goalposts.md @@ -0,0 +1,386 @@ +# New design — goalposts + +Tracks the design approved on 2026-08-09 (`design-explained.html`, detail in +`counsel-design.html`). Updated as work lands. Progress in every status update +is reported against this file. + +## How to read a status + +| Status | Means | +| --- | --- | +| **PROVEN** | An oracle asserts the behaviour, removing the production guard **reddens** that oracle, and the mutation was verified to actually land before the result was believed. | +| **ORACLE RED** | The oracle is written and currently fails for the right reason. The production change is not written yet. This is the intended pre-implementation state. | +| **NOT STARTED** | No oracle. | +| **BLOCKED** | Waiting on another goalpost or an owner decision. | + +A green test is **not** a status. This program shipped three guards that passed +their tests while sitting off the route production takes; "PROVEN" exists to +make that impossible to claim by accident. + +--- + +## Scoreboard + +| | Count | +| --- | --- | +| Step goalposts proven | **7 of 7** (one deleted as unreachable) | +| Global goalposts proven | **5 of 6** — G1 missed, see below | +| Scope removed by evidence | S7 (death rule) — never built | +| Oracle clauses green | 26 | +| Oracle clauses red (awaiting implementation) | 0 | +| Net production lines, correctness work | **+13** | +| Net production lines, incl. the approved affordance | **+83** | +| Net test lines | +2,578 | + +**G1 is not met, and that is reported rather than smoothed over.** The design's +net-negative target assumed the remaining steps were collapses. Three were +(S3 −21, S8 −32, and the relay half of S5), but two genuinely add code: the +single `bindPaneShell` producer (+60, since one function replaces three +divergent call sites without those sites shrinking much) and the D1 +disconnected-pane affordance (+70), which is a new product surface the owner +approved — a feature, not a refactor. Excluding the affordance the correctness +work is +13, i.e. roughly a wash. See "G1" below for the full accounting. + +--- + +## Step goalposts + +### S1 — An identity mismatch is never read as death · **PROVEN** + +*Guarantee.* The relay reports a pane-identity mismatch by saying the pty was +not found. It found it — comparing is how it noticed. That must never reach a +respawn decision as proof of death. + +- Oracle: `src/main/providers/ssh-pty-identity-mismatch-is-not-death.test.ts`, + `src/renderer/src/components/terminal-pane/reattach-failure-classification.test.ts` +- Clauses: 7 + 3 +- Mutations proven: restoring the destructive wrap reddens 2 clauses; deleting + the classifier guard reddens 1 — clause-selective, each proven separately. +- Landed: `e2524b0472f` + +### S2 — Pane identity is not sent on reattach · **PROVEN** + +*Guarantee.* Moving a pane to another tab must never make its terminal +unreachable. + +- Oracle: same file, `reattach does not ask the relay to police pane identity` (2 clauses) +- Also inverted an existing test that pinned the removed behaviour, so the new + intent stays covered rather than silently dropped. +- Works against **already-deployed relays**: the relay's comparison is + presence-guarded, so not sending the fields disarms it everywhere. No wire + change, no redeploy. +- Landed: `c51be8072ba` + +### S3 — A failed reattach never fabricates an exit · **PROVEN** + +*Guarantee.* On an unproven not-found, the pane is not told the program exited, +ownership is not deleted, provider state is not cleared, and the lease is not +expired. The case routes into the non-destructive recovery branch that already +exists. + +- Oracle: `src/main/ssh/ssh-relay-reattach-exit-proof.test.ts` — 8 green +- Mutation proven: restoring the destructive block reddens 6 of 8 clauses; the + 2 producer pins stay green, so the mutation is clause-selective. +- Two tests pinned the deleted premise ("attach verifies liveness before + answering not-found") and were **inverted**, not patched. +- Shipped with the disconnected-pane affordance below, since panes now stay + visible instead of silently respawning. +- Landed: `c19f1b386b4` (−21 production lines) + +### S4 — One partition per (target, pane) · **PROVEN** + +*Guarantee.* A pane that re-leases under a new relay id across reconnects ends +with exactly **one** live claim; the predecessor is superseded, not left live. + +- Oracle: `src/main/ssh-pane-binding-partition.test.ts` — 7 green (one clause added) +- The highest-value goalpost: the mechanism behind the reported 2 → 19 → 20. +- Mutation proven as a **2×2**, because the two edits mask each other: + + | reader | load fold | result | + | --- | --- | --- | + | hedge (original) | off | 6 red — baseline | + | hedge | off | 4 red — the 2 source-text clauses now green | + | local-only | off | 1 red — the reader carries 3 clauses | + | hedge | **on** | **all green** ← the fold masks the reader | + | local-only | on | all green | + + That fourth row is why an **eighth clause was added**: with the fold shipping, + the fold erases the divergent copy at boot, so the reader guard would have + shipped unproven — precisely the failure mode G5 exists to catch. The new + clause rewrites `ssh:` mid-session (orphan adoption still writes + there) and reddens when the hedge is restored, pinning the reader on its own. +- Five clauses in `ipc/pty.test.ts` pinned the two-partition shape and were + **inverted** to the single home, each keeping an arity check so a re-added + partition argument fails loudly. +- Side effect found while verifying: the renderer never hydrated the `ssh:*` + partition (`listKnownRuntimeHostIds` filters to `runtime:*`), so the Issue + #217 force-quit binding protection had never worked for SSH panes. It does now. +- Landed: `2733c59879b` (+9 production lines — the call sites shrank; the fold + is new state repair) + +### S5 — The superseded-pane fence is live on the reattach path · **PROVEN** + +*Guarantee.* After a relay-driven reattach binds a pane, a stale write aimed at +the superseded predecessor is **refused**. It used to be permitted, because the +fence's bookkeeping was only written by spawn. + +- Oracle: `src/main/ssh/ssh-relay-session-reattach-pane-fence.test.ts` — 4 green + (one clause added) +- Collapsed to one `bindPaneShell` producer used by the relay reattach and both + spawn handlers. Error policy stays at the call sites because it genuinely + differs: a caller that just created a shell must clean it up on a failed + durable write; a caller that merely reattached must not detach anything. +- Mutation proven, both sub-guards isolated: + - drop the `rememberPaneKeyForPty` call → 3 clauses redden + - prefer the stored `tabId` over the live layout → 1 clause reddens +- That second clause is **new**. Every pre-existing clause used one tabId on + both sides, so a producer that simply forwarded `lease.tabId` would have gone + green and shipped the moved-pane bug unnoticed. Only the leaf half of a pane + key is remint-stable; `detachTerminalPaneToTab` moves a live pane and its PTY. +- Two source-text clauses were **strengthened**: they used to require the relay + to hold a `persistPtyBinding` call and merely forbade an ssh-partition + argument. The relay now has none, so they assert **zero** direct binding + writes there — a second bind producer is exactly the defect being removed. +- Repaired a latent false green: the "persistence fails" case in + `ssh-relay-session-reconnect-incarnation` was passing because a missing mock + made the call throw a TypeError that happened to emit the asserted + `console.error`. The failure is now injected at the producer. +- Landed: `0f409055d3f` (+60 production lines — the one step that grows) + +### S6 — Settle whether the 30s recovery grant executes at all · **PROVEN — it is dead code** + +*Result.* It cannot execute for a real SSH pane. Verified personally: + +- The lease stores a **relay-native** pty id, normalized on write + (`persistence.ts:7184`, comment: "app ids are global"). +- The caller passes the **app-form** id (`orca-runtime.ts:16478` ← `toAppSshPtyId`). +- The comparison is raw `lease.ptyId === ptyId` (`orca-runtime.ts:6310`) with no + normalization, so the two forms can never be equal. +- The branch is also unreachable for a local pane, since it requires an SSH lease. +- Its covering test seeds both sides as the same literal with a null + connectionId — a shape production cannot produce. + +### S7 — The death rule · **DELETED on S6's evidence** + +Not built. The arbitration machinery existed to referee a branch that never +executes. Per the design: "if E-1 shows the grant branch unreachable, E-2 is +deleted and the marker simply never fires, which is the safe end state." + +### S8 — Remove the dead recovery-grant path · **PROVEN** + +*Guarantee.* Deleting it changes no behaviour, because it has none. + +- Oracle: `src/main/runtime/ssh-pane-recovery-grant-reachability.test.ts`, written + and green **before** the deletion, so inertness is demonstrated rather than assumed. +- It mints **both** id forms from the production helpers rather than as two + hand-typed literals, so it tracks the real namespace split instead of + restating it, and seeds a lease qualifying on every other predicate (state, + worktree, tab, leaf, grace window). Anti-vacuity clauses pin that control + actually reaches the gate rather than bailing out earlier. +- Mutation proven **before** deleting: normalizing the `lease.ptyId === ptyId` + comparison makes the grant fire and reddens the oracle. That is the exact fix + someone would reach for, so the oracle is pinned to unreachability, not to the + throw. +- Deleted: the grant tail, the `terminalPaneRecoveryByIdentity` dedup map (whose + only consumer was the grant), and the dead `ptyId` parameter. +- **Not** deleted, because over-deleting here breaks users: `getRecentExpiredSshLease`, + `hasRecentExpiredSshLeasePane` and `SSH_PANE_RECOVERY_GRACE_MS` all stay. Their + other two callers pass `ptyId` undefined, which short-circuits the broken + comparison — those are live and feed headless-mobile terminal-tab visibility. +- Also **not** done: deleting only the gate while keeping the spawn. That would + have granted a respawn to every disconnected pane — a change in the dangerous + direction. The refusal is what stays. +- Three tests pinned the grant and were **inverted**; a fourth is now + tautological and carries a comment saying so rather than being left hollow. +- Honest limit, recorded in the oracle: unreachable **by construction** for SSH + panes; for a local pane, unreachable only up to a random-UUID collision. +- Landed: `7d44315437a` (−32 production lines) + +### Product affordance (D1) — **SHIPPED with S3** + +A pane that cannot be verified renders as disconnected with two explicit actions +— "Try again" and "Start a new terminal" — instead of silently respawning. + +- No new IPC channel: the silent-respawn decision was always renderer-local. + Both actions are things the code already did, moved behind a click. +- Copy constraint enforced **as an oracle**, not as a review note: the rendered + text must match no death verb and show no wire token. STYLEGUIDE.md:236 already + forbids result verbs without result data, and a failed attach is not result data. +- `TerminalRemoteRuntimeReconnectBanner` → `TerminalPaneDisconnectedBanner`; it + now serves any transport. Existing i18n key strings kept verbatim so no shipped + translation breaks; the SSH copy is additive. +- Landed: `5e1b57bb2f9` (+70 production lines) + +--- + +## Global goalposts + +### G1 — Net production code is negative · **NOT MET (+83 this phase)** + +Counted from the pre-work merge base, production only. Reported as a miss rather +than reframed until it passes. + +| Step | Net production | +| --- | --- | +| S3 — collapse the fabricated exit | **−21** | +| S4 — one partition | +9 | +| S5 — one bind producer | **+60** | +| S8 — delete the dead grant | **−32** | +| D1 affordance (new product surface) | **+70** | +| Banner rename (pure move, no behaviour) | +36 of the above, not real growth | +| **Correctness work only (S3–S8)** | **+13** | +| **Total this phase** | **+83** | + +Why it missed. The target assumed the remaining steps were collapses. Three were. +Two were not, for reasons worth stating: + +- **S5 (+60).** One producer replacing three divergent call sites only shrinks + the code if those sites were duplicating the whole bind. They were not — they + each did *part* of it differently, which is exactly the defect. The producer is + net-new; the call sites shrank by 7 lines. Collapsing the two spawn handlers' + surrounding logic as well would buy the difference back, but it would reorder + side effects that existing ordering assertions pin, so it was left alone. +- **D1 affordance (+70).** A new user-facing surface the owner approved. Features + add lines; counting it against a refactor budget would be the wrong pressure — + the way to make this number go negative would be to delete the affordance. + +Where the remaining slack is, if the goal is to be met later: steps P and K of +the design (the leaf-keyed record replacing `SshRemotePtyLease`, and the lease +readers ported onto it) are the deletions this phase deferred. + +### G2 — No redeploy required for the user-visible fixes · **PROVEN for S1–S8** + +Fixes must work against relays already installed on people's hosts. Every step +that landed is client-side only: + +- S1, S2 — proven previously. +- S3 — deletes client-side reactions to a relay message; the relay is unchanged. +- S4 — client-local persistence layout only; nothing crosses the wire. +- S5 — client-local in-memory fence maps and the durable binding. +- S8 — deletes a client-side branch. +- D1 — renderer only. + +**No relay redeploy is required for any of it**, which matters because the +reported failure is happening on hosts people have already deployed. + +### G3 — Wire compatibility · **SATISFIED — nothing on the wire changed** + +Clients and hosts update independently. This phase added **no** RPC parameter, +no stream opcode and no published field, so there is nothing to negotiate. The +orphan projection that would have added one optional field belongs to step W, +which is not in this phase. + +One wire-adjacent behaviour change is worth naming for reviewers: `terminal.recoverPane` +(RPC) now always refuses for a disconnected pane. The method still exists and its +signature is unchanged, so older clients get a refusal rather than a +`method_not_found` — and the renderer already handles refusal, because that is +what the branch did in practice anyway. + +### G4 — Cross-platform · **SATISFIED by construction** + +macOS, Linux, Windows, WSL. No oracle added in this phase shells out, and none +uses `echo $$` or `ps` — they assert against persisted state, in-memory maps and +rendered text. No rule that landed concludes anything from a relay restart or +from whether a shell survives a hard relay death, which is the Windows-divergent +question the design deliberately refuses to depend on. The affordance copy holds +on every platform precisely because it never claims the shell died. + +### G5 — Every guard is proven live on the production route · **PROVEN for S1–S8** + +For each new guard, an oracle must redden when the **producer** is removed — not +only when the guard itself is removed. + +This exists because it had failed three times here: an inert `mayCreate`, a +keystroke fence inert on reattach, and a respawn gate on a minority path. S5 is +the remediation of the second. + +**It nearly failed a fourth time in this phase, and the rule caught it.** S4's +reader guard (`durablyBoundPtyIdForPane` reading one partition) initially showed +*no* mutation response: restoring the ssh-first hedge left all six clauses green, +because the load fold had already erased the divergent copy at boot. The guard +was correct and would have shipped unproven. The fix was an added clause that +rewrites the ssh partition **mid-session**, which reddens on the hedge and pins +the reader independently of the fold. + +Two further near-misses found and closed the same way: +- S5's clauses all used one tabId on both sides, so "compose the paneKey from + the current tab" was unpinned — a producer forwarding `lease.tabId` would have + gone green. A moved-pane clause now pins it. +- A case in `ssh-relay-session-reconnect-incarnation` was a **latent false + green**: it passed because a missing mock threw a TypeError that happened to + emit the `console.error` it asserted. Now injected at the producer. + +### G6 — No `max-lines` disables · **HOLDING** + +Per AGENTS.md. No per-file bumps either. + +--- + +## Definition of done + +| | Criterion | Status | +| --- | --- | --- | +| 1 | S1–S5 and S7 PROVEN, or S7 deleted on S6's evidence | **MET** — S1–S6 and S8 proven; S7 deleted on S6's evidence | +| 2 | G1–G6 satisfied, each with evidence recorded here | **PARTIAL** — G2–G6 met; **G1 missed at +83**, accounted for above | +| 3 | The reported failures covered by an oracle that reddens without the fix | **MET.** Pane cardinality: S4's ten-reconnect clause, plus an E2E spec driving three real reconnects against a Docker relay (passes). Duplicate resume: the classification clauses, plus an E2E spec where the **host itself** records every shell launch (passes). Writing the second one is what exposed that RC2 was still live — see below | +| 4 | No guard shipped without a producer-side mutation proving it is reachable | **MET** — and it caught one guard that would otherwise have shipped unproven (see G5) | + +### Found after the goalposts were met + +Two defects surfaced *after* every step goalpost was proven, and both were invisible to the unit +oracles that had already gone green. Recorded because they are the most useful evidence in this +phase about where these oracles stop reaching. + +**RC2 survived S3 — found by writing the E2E test.** `7cd7fef927f`. +The reported duplicate agent resume was not fixed. `reattachSshPtySession` maps every relay +not-found to `SSH_SESSION_EXPIRED`, and `isProvenSshSessionGoneError` returned true for it, so the +renderer's reattach arm still respawned. The E2E harness produced the shape directly: a stalled +relay is superseded by a fresh one with no memory of `pty-1`, while the old shells keep running +under the stopped process. The new relay answers not-found for a live shell. + +A not-found proves an exit only if the relay process that minted the pty is the one answering — +design D3 row 2, gated on `relayInstanceId`, which step E-2 never built. `SSH_SESSION_EXPIRED` is +not independent evidence: its only producer is that same mapping, and the token's own doc comment +claimed "the host proved the session is gone", which it never did. + +So `isProvenSshSessionGoneError` returns false. This is also what makes the D1 affordance +load-bearing rather than near-unreachable. The respawn tails are deliberately kept — the design +preserves the grant as a conditional for E-2 — with a clause pinning that nothing reaches them. + +**The fold left half a fence behind — found by adversarial review.** `994733d8b1a`. +`persistPtyBinding` writes the binding and its incarnation into the same partition, and the +incarnation is what its CAS compares. The fold moved only `ptyIdsByLeafId`, so after upgrade the +guard stayed in the partition nothing reads and the CAS compared `undefined` against `undefined`. +Not data loss and not a wrong-shell bind, but a guard silently weakened by a migration is the exact +shape this program keeps finding. + +### Residuals, stated rather than closed quietly + +- **Orphan adoption still writes the `ssh:` partition.** + `adoptTerminalOrphansFromInventory` (via `tryGetWorkspaceSessionHostIdForWorktree`) + writes pane bindings there. S4's reader ignores that partition, so supersession + is unaffected and the guarantee holds — but the write now lands somewhere + nothing reads. Harmless today, and a trap for whoever touches it next. Belongs + with step W. +- **The load fold moves leaf bindings only.** It deliberately does not touch + `tabsByWorktree[*].ptyId` in the ssh partition: that field is a tab-level + pointer no supersession path reads, and nulling it without a local counterpart + to move it to would be data loss. Narrowing the fold to what the defect + actually requires is why `reassignSshTargetId` needed no inversion. +- **The main-side detached branch still has no renderer signal.** S3 made the + main process stop lying; the affordance covers the renderer-initiated reattach + arms. A relay-driven reattach failure remains silent to the user. Closing it + needs a `pty:detached` channel — deferred deliberately, not overlooked. + +## Deliberately out of scope + +- The data-plane work (transport delivery guarantee, binary payloads, one credit + ledger). Real and separately justified, but independent of these goalposts. +- Rebuilding the authority architecture rejected earlier at +60,903 lines. + +## Owner decisions + +| | Decision | Status | +| --- | --- | --- | +| D1 | An unverifiable pane becomes visibly disconnected with two actions, instead of silently respawning | **Approved 2026-08-09** (implicit in approving the design; flagged for correction if not intended) | +| D2 | Whether the older gate/journey framing is rescoped or retired now that this design supersedes it | **Open** | diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/related-open-work.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/related-open-work.md new file mode 100644 index 00000000000..0d20afdf08e --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/related-open-work.md @@ -0,0 +1,341 @@ +# Related GitHub work + +This is a curated overlap map, not a merge queue. States were verified against +GitHub on 2026-08-08 UTC and must be refreshed before any rebase, merge, close, +or implementation decision. + +Rules: + +- Do not stack PRs merely because they appear in the same section. +- “Conflict” means semantic or file overlap that requires one coherent design, + not an instruction to merge both. +- A related PR can supply diagnosis, tests, or a small reusable primitive + without becoming a dependency. +- Landing a related PR does not promote G0–G7 or one of the thirteen journeys + unless the final converged tree passes that gate's complete proof. +- GitHub issue/PR text is context, not authority over the user's goal. + +## Immediate incident and competing implementations + +- [Issue #11729 — SSH remote environment not restored after login on Rocky Linux + 9.4](https://github.com/stablyai/orca/issues/11729) — **open**. This is the + named STA-3077 customer incident. Its final acceptance must include Rocky + Linux SSH, repeated reconnect, the same PID/process/session/transcript + identity, restored workspace environment, visible pane count, and actual + remote relay PTY/process count. +- [PR #13111 — stop reconnect grafting panes, stacking leases, and respawning + live shells](https://github.com/stablyai/orca/pull/13111) — **open**, current + branch, green checks, no approval. It is narrow containment and leaves remote + shell reclamation unresolved. One major Docker settle review thread remains + [unresolved](https://github.com/stablyai/orca/pull/13111#discussion_r3739665033). +- [PR #12264 — stop reconnect from grafting ghost terminal + panes](https://github.com/stablyai/orca/pull/12264) — **open and conflicting**. + It targets the same incident and overlaps persistence, PTY, SSH relay, and E2E + files. Mine its diagnosis and discriminating artifacts; do not stack it + wholesale with #13111. +- [PR #12743 — contain reattach to existing panes, quarantine + orphans](https://github.com/stablyai/orca/pull/12743) — **open and + conflicting**. It shares `mayCreate: false` and broader relay coverage, but + quarantine must be judged against the no-reconciliation final design. +- [PR #12456 — reattach on `restoreRequired` instead of expiring a live + session](https://github.com/stablyai/orca/pull/12456) — **open**. It addresses + the #12448 branch through retry rather than cold respawn. Treat it as a + semantic alternative or complementary recovery path only after choosing one + exact restore protocol. +- [PR #9820 — reap orphaned relay PTYs before session-cap + exhaustion](https://github.com/stablyai/orca/pull/9820) — **open**. Its + time-based remote kill conflicts with unknown-is-not-dead and #13111's + deliberate non-kill behavior. Use it as incident evidence, not a safe default + dependency. +- [PR #12798 — opt-in zmx-backed durable SSH + terminals](https://github.com/stablyai/orca/pull/12798) — **open**. This is a + broad architectural alternative for final remote PTY ownership with direct + file overlap. Evaluate capability-by-capability; never blend it into the + current model accidentally. + +## Open incident issues that should become explicit oracles + +- [Issue #9819 — SSH relay leaks orphaned PTYs until the 50-session + cap](https://github.com/stablyai/orca/issues/9819) — explicit close, + disconnected close with a lost shutdown response, and worktree teardown must + durably retry retirement of the exact lease and process. Uncertain sessions + must survive visibly until resolved. Repeated reconnect must reclaim actual + relay PIDs/session slots rather than accumulate toward the cap. +- [Issue #9034 — SSH reconnect repeatedly spawns detached PTYs for one + pane](https://github.com/stablyai/orca/issues/9034) — count actual remote PTYs + and prove bounded one-pane ownership across repeated reconnect. +- [Issue #11006 — transient SSH disconnect treats live relay PTYs as dead and + duplicate-respawns agents](https://github.com/stablyai/orca/issues/11006) — + disconnect with a live process must remain unresolved/reattachable and must + not start another agent. +- [Issue #12447 — closed SSH tabs resurrect and auto-resume old + sessions](https://github.com/stablyai/orca/issues/12447) — explicit close must + persist its pending tombstone before a kill RPC, survive a lost reply plus app + and relay restart, retry after handshake, reclaim the exact remote PTY, and + never recreate UI or automatic resume. +- [Issue #12448 — `restoreRequired` is misreported as session + expiry](https://github.com/stablyai/orca/issues/12448) — source recovery must + replay/repaint on the same PID and binding without starting a replacement + `--resume`; identity drift, timeout, or unknown state must not become proof of + process death or cold resume authority. +- [Issue #12699 — SSH sleeping-agent wake sweep forks live remote + sessions](https://github.com/stablyai/orca/issues/12699) — all wake/resume + paths must share the same exact liveness and identity contract. +- [Issue #12683 — remote-runtime disconnect spends recovery on stale same-handle + reattach](https://github.com/stablyai/orca/issues/12683) — paired/web terminal + recovery must fence generations and retain automatic liveness. +- [Issue #10208 — duplicate terminal tab on worktree session + restore](https://github.com/stablyai/orca/issues/10208) — local/worktree + restore must prove the same pane and process rather than creating a duplicate. + +These issues are separate customer-visible symptoms. A single structural model +should make their shared invalid transitions impossible, while each issue keeps +its own discriminating regression journey. + +## Daemon, relay generation, and liveness work + +The acceptance matrix must also reproduce these open lifecycle incidents: + +- [Issue #11904 — tab close with a broken binding orphans the daemon + session](https://github.com/stablyai/orca/issues/11904) — close intent must be + durable before transport work and eventually retire the exact process. +- [Issue #8585 — detached relay generations are never + reaped](https://github.com/stablyai/orca/issues/8585) — termination must name + the exact relay generation; path/PID reuse or a failed connection cannot kill + a successor. +- [Issue #9138 — updates leave old daemon generations and sessions + alive](https://github.com/stablyai/orca/issues/9138) and + [issue #11342 — stale daemon/PTY generations leak across upgrade and + close](https://github.com/stablyai/orca/issues/11342) — upgrade must converge + without invisible sessions, guessed ownership, or unbounded retention. +- [Issue #10415 — Windows daemon crash on unkillable PTY and protocol + bump](https://github.com/stablyai/orca/issues/10415) — native Windows must + preserve live old-generation sessions or expose exact unresolved recovery; + one unkillable PTY cannot crash the daemon. +- [Issue #8275 — worktree teardown kills unrelated split-pane + sessions](https://github.com/stablyai/orca/issues/8275) — teardown and failure + must remain exact-namespace/exact-binding scoped. + +- [PR #12882 — publisher-owned daemon endpoint + replacement](https://github.com/stablyai/orca/pull/12882) — **open and + mergeable** when checked. It provides single-writer endpoint publication and + three-valued liveness. Reconcile it before editing overlapping daemon paths; + do not assume the older handoff's merge order is still current. +- [PR #11622 — fence daemon session ownership across + generations](https://github.com/stablyai/orca/pull/11622) — **open** and held + behind further audit per its description. Strong explicit + owned/unavailable/ambiguous semantics, but broad overlap makes it design input, + not an automatic dependency. +- [PR #9833 — report local PTY inventory + readiness](https://github.com/stablyai/orca/pull/9833) — **open**. Its + pending/ready/stale distinction is reusable context for unknown-is-not-dead. +- [PR #12760 — reap only the proven relay + generation](https://github.com/stablyai/orca/pull/12760) — **open**. It adds + exact relay generation ownership before termination and conflicts in + `ssh-relay-session.ts`; reconcile before designing remote shell cleanup. +- [PR #8618 — reap a detached relay after failed + reconnect](https://github.com/stablyai/orca/pull/8618) — **open** and an older + competing predecessor to #12760. Do not combine both ownership schemes. +- [PR #12749 — wait for a disconnected PTY owner's full + grace](https://github.com/stablyai/orca/pull/12749) — **open**. Useful owner + admission and grace context; timers may schedule retry but cannot independently + authorize takeover or destruction. +- [PR #12702 — stop sleeping-agent wake sweep from forking live SSH + sessions](https://github.com/stablyai/orca/pull/12702) — **open**. Complementary + #12699 work that must converge on the same ownership/liveness behavior; it + need not share an internal primitive unless the reconciled design calls for + one. +- [PR #10118 — durable persistence write + seam](https://github.com/stablyai/orca/pull/10118) — **open**. It overlaps + `persistence.ts` and is relevant to durability and main-thread performance; + reconcile before large persistence changes. + +## Paired runtime, remote server, and E2EE lifecycle work + +These open issues are mandatory inputs to the paired/remote/platform journeys: + +- [Issue #11495 — paired viewer loses attachments across update/restart while + host PTYs remain alive](https://github.com/stablyai/orca/issues/11495) — the + reported large host population is a strong restore/scale oracle; each pane + must return to the same host PTY/process. +- [Issue #11265 — paired terminals stall despite live TCP + sockets](https://github.com/stablyai/orca/issues/11265) — transport connectivity + is not delivery liveness; recovery must resume output without an unrelated RPC + kick. +- [Issue #11803 — remote stop respawns tabs from a stale + owner](https://github.com/stablyai/orca/issues/11803) — exact durable retirement + must remain retired after host/client restart. +- [Issue #12241 — paired-host session partitions grow without + bound](https://github.com/stablyai/orca/issues/12241) — paired and scale + journeys must prove bounded state and safe lost-consumer + retirement/compaction liveness. +- [Issue #11574 — same-server re-pairing changes host identity and strands + sessions](https://github.com/stablyai/orca/issues/11574) — stable final-host + identity must survive re-pairing without adopting another host. +- [Issue #9827 — investigate WSL session + restoration](https://github.com/stablyai/orca/issues/9827) and + [issue #11339 — WSL commands are not restored after + restart](https://github.com/stablyai/orca/issues/11339) — the daemon/WSL + journey must run on physical WSL and preserve both shell commands and agent + sessions. + +Additional open incident inputs must be triaged into a named journey or ruled +unrelated with explicit evidence and user acceptance: + +| Issue | Required question | +| ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| [#11800 — paired null-PTY terminal ghosts](https://github.com/stablyai/orca/issues/11800) | Does host topology advancement retire exact placeholders without inference or a permanent timer reconciler? | +| [#9092 — remote runtime fails after macOS sleep](https://github.com/stablyai/orca/issues/9092) | Does generation-fenced reconnect recover after sleep with bounded resources and no identity change? | +| [#9585 — remote ghost tabs after host restart](https://github.com/stablyai/orca/issues/9585) | Are exit/retirement outcomes durable and idempotent across host restart? | +| [#9562 — remote host session restarts empty](https://github.com/stablyai/orca/issues/9562) | Does the complete boundary plus replay restore terminal state after server restart? | +| [#12568 — no PTY provider after SSH relay recovery/update](https://github.com/stablyai/orca/issues/12568) | Does lazy rediscovery restore the exact host/provider generation? | +| [#10385 — mobile remains falsely connected after RPC stalls](https://github.com/stablyai/orca/issues/10385) | Can E2EE/mobile liveness recover when transport looks connected but RPC is stalled? | +| [#12140 — mobile pairing socket closes immediately](https://github.com/stablyai/orca/issues/12140) | Do capability, identity, and E2EE negotiation fail explicitly and recover across LAN/Tailscale? | +| [#8129 — mobile events lost while disconnected](https://github.com/stablyai/orca/issues/8129) | Are semantic outcomes durable and replayed to a disconnected/backgrounded consumer? | + +- [PR #11575 — preserve host identity across same-server + re-pairing](https://github.com/stablyai/orca/pull/11575) — **open**. Direct + identity context for the paired reconnect journey. +- [PR #12768 — restore paired snapshots at the source + grid](https://github.com/stablyai/orca/pull/12768) — **open**. Complementary + host-snapshot authority work with renderer file overlap. +- [PR #9093 — recover remote runtime streams after client + wake](https://github.com/stablyai/orca/pull/9093) — **open**. Provides + generation-cancelled bounded-backoff reconnect context. +- [PR #10235 — self-heal remote subscriptions after server + restart](https://github.com/stablyai/orca/pull/10235) — **open**. Relevant to + E2EE session loss hidden by a live relay transport. +- [PR #11596 — recover falsely connected mobile RPC + sessions](https://github.com/stablyai/orca/pull/11596) — **open and + conflicting**. Broad mobile/E2EE reconnect context; do not absorb its parallel + lifecycle machinery without a full state-machine audit. +- [PR #12036 — stop blocking E2EE handshake on synchronous ACL + writes](https://github.com/stablyai/orca/pull/12036) — **open and conflicting**. + Preserve its metadata-versus-correctness durability distinction and measured + Windows performance constraint during identity lifecycle work. +- [PR #12134 — refresh stale capabilities before + pairing](https://github.com/stablyai/orca/pull/12134) — **open**. Capability + freshness and reauthentication are required mixed-version/pairing context. +- [PR #11804 — make remote stop retirement + durable](https://github.com/stablyai/orca/pull/11804) — **open**. Strong + complementary evidence for exact persisted owner routing and host-side + retirement acknowledgement. +- [PR #12987 — distinguish an absent worktree from an empty tab + list](https://github.com/stablyai/orca/pull/12987) — **open**. Reusable + unknown-versus-authoritative-empty semantics. +- [PR #12751 — preserve tabs when a snapshot reports + none](https://github.com/stablyai/orca/pull/12751) — **open** and a competing + less-exact alternative to #12987; its described multi-client non-convergence + must not become the final model. +- [PR #12339 — stop remote workspace pulls from resurrecting closed + tabs](https://github.com/stablyai/orca/pull/12339) — **open**. Direct topology + reconciliation context for explicit close and stale snapshots. +- [PR #13013 — stop stale snapshot applies from erasing fresh terminal + tabs](https://github.com/stablyai/orca/pull/13013) — **open**. Relevant legacy + snapshot race; decide whether its machinery is deleted by the final authority + cutover rather than layering another permanent reconciler. +- [PR #12903 — retry snapshot tabs whose paths resolve after + apply](https://github.com/stablyai/orca/pull/12903) — **open**. Deferred + hydration is relevant legacy-importer context and may become deletable after + authoritative namespace resolution; do not retain it by default. + +## Delivery, backpressure, and lifecycle alternatives + +- [Draft PR #12220 — keep SSH alive when a terminal outruns a slow + link](https://github.com/stablyai/orca/pull/12220) — **open draft**. Useful G3 + and performance evidence, but its own description has behavioral blockers and + a stalled-consumer wedge. Do not treat it as merge-ready. +- [PR #10744 — durable lost-worker archive and mixed-version SSH + revive](https://github.com/stablyai/orca/pull/10744) — **open** and broad. It + is major architectural context for exact close, outcomes, retirement, and + mixed versions, with substantial overlap. Mine proof and semantics rather + than stacking blindly. +- [PR #11801 — prune stale remote tab + ghosts](https://github.com/stablyai/orca/pull/11801) — **open**. Its snapshot + omission plus timer policy is relevant but may conflict with the rule that + absence/time alone cannot prove destructive cleanup. + +## Mandatory issue-to-journey matrix + +This table binds customer incidents to the thirteen journeys in +[`goalposts.md`](./goalposts.md#thirteen-required-production-journeys). Closing +an issue or merging a narrow PR does not remove its oracle. Each row must be red +on an unfixed baseline and green on the final candidate, or the user must accept +explicit evidence that the issue is unrelated. + +| Open issue(s) | Journey(s) | Mandatory discriminating outcome | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| [#11729](https://github.com/stablyai/orca/issues/11729) | 6, 9, 13 | Rocky Linux reconnect preserves the same workspace, transcript, pane, binding, PID, and environment without PTY growth. | +| [#9819](https://github.com/stablyai/orca/issues/9819), [#9034](https://github.com/stablyai/orca/issues/9034) | 6, 13 | Reconnect cannot accumulate detached PTYs/session slots; explicit close and teardown reclaim the exact process, including lost-response retry. | +| [#11006](https://github.com/stablyai/orca/issues/11006), [#12448](https://github.com/stablyai/orca/issues/12448), [#12699](https://github.com/stablyai/orca/issues/12699) | 2, 6 | Disconnect, source recovery, and wake keep the same live PID/session and never start a duplicate resume without proof of death. | +| [#12447](https://github.com/stablyai/orca/issues/12447), [#11904](https://github.com/stablyai/orca/issues/11904) | 2, 6 | Durable close intent survives lost RPC, app/daemon/relay restart, retries exact retirement, reclaims the process, and never resurrects UI. | +| [#10208](https://github.com/stablyai/orca/issues/10208) | 1, 9 | Worktree switch/restore preserves one exact pane/process and does not duplicate a tab. | +| [#8585](https://github.com/stablyai/orca/issues/8585) | 2, 6, 12 | Cleanup affects only the proven relay generation across reconnect and version change; ID/path reuse cannot kill a successor. | +| [#9138](https://github.com/stablyai/orca/issues/9138), [#11342](https://github.com/stablyai/orca/issues/11342) | 2, 12, 13 | Upgrade/restart converges old daemon generations and their PTYs without invisible sessions, leaks, or destructive guessing. | +| [#8275](https://github.com/stablyai/orca/issues/8275) | 1, 2, 5 | Worktree teardown cannot terminate a sibling namespace or split-pane session. | +| [#10415](https://github.com/stablyai/orca/issues/10415) | 1, 2, 5, 12 | Native Windows handles an unkillable PTY and protocol bump without daemon crash, live-session loss, or cross-session damage. | +| [#9827](https://github.com/stablyai/orca/issues/9827), [#11339](https://github.com/stablyai/orca/issues/11339) | 2, 9 | Physical WSL restart restores the same shell command and agent session under the exact namespace/binding. | +| [#12568](https://github.com/stablyai/orca/issues/12568) | 3, 6, 12 | Relay recovery/update lazily rediscovers the same SSH host/provider and restores only its exact sessions. | +| [#11495](https://github.com/stablyai/orca/issues/11495), [#11574](https://github.com/stablyai/orca/issues/11574) | 4, 8, 10, 12, 13 | Paired restart/re-pair preserves stable host identity and every reported live host PTY at scale across independent updates. | +| [#11265](https://github.com/stablyai/orca/issues/11265), [#9092](https://github.com/stablyai/orca/issues/9092) | 8, 13 | Live-but-stalled transport and sleep/wake automatically resume bounded delivery without an unrelated RPC kick or identity replacement. | +| [#11803](https://github.com/stablyai/orca/issues/11803), [#9585](https://github.com/stablyai/orca/issues/9585), [#11800](https://github.com/stablyai/orca/issues/11800) | 3, 8 | Remote stop/host topology outcome remains durably retired after restart; no stale-owner tab or null-PTY ghost returns. | +| [#9562](https://github.com/stablyai/orca/issues/9562), [#8129](https://github.com/stablyai/orca/issues/8129) | 3, 8, 13 | Complete boundary plus replay restores disconnected/restarted consumers without an empty session or lost semantic outcome. | +| [#12241](https://github.com/stablyai/orca/issues/12241) | 8, 11, 13 | Paired partitions and retained-consumer state remain bounded; lost-consumer retirement safely restores compaction liveness. | +| [#12683](https://github.com/stablyai/orca/issues/12683) | 8, 12 | Stale same-handle reconnect is generation-fenced and automatic recovery remains live across independent peer versions. | +| [#10385](https://github.com/stablyai/orca/issues/10385), [#12140](https://github.com/stablyai/orca/issues/12140) | 8, 10, 12 | False-connected or rejected E2EE/pairing state fails explicitly and reauthenticates without stale identity, capability, or session adoption. | + +Journeys 4, 5, 7, 10, and 11 remain mandatory even where no single issue fully +specifies them. This matrix adds incident oracles; it never narrows the journey +definitions. + +## Original containment/refactor line + +- [PR #12600 — break Activity and terminal React 185 + loops](https://github.com/stablyai/orca/pull/12600) — **merged**. It is current + containment/background context, not the whole program and not a release gate. +- [PR #12634 — replace React 185 timers with structural + handoffs](https://github.com/stablyai/orca/pull/12634) — **open**. This is the + direct structural follow-up for deleting #12600's window/timer brakes and must + be reconciled with the broader terminal-session model. +- [PR #13110 — sandboxed preload artifact + guard](https://github.com/stablyai/orca/pull/13110) — **open**, independent of + #13111, green at its head, no approval. Its unresolved major review says raw + source matching can reject safe strings/comments; resolve or supersede that + [finding](https://github.com/stablyai/orca/pull/13110#discussion_r3739646949) + before calling it ready. + +## Already merged base context + +These were described as open in older notes but were merged when this handoff +was written: + +- [PR #12474 — isolate same-path folder workspace PTY + identity](https://github.com/stablyai/orca/pull/12474) +- [PR #12477 — stop a closed remote workspace window reading + Ready](https://github.com/stablyai/orca/pull/12477) +- [PR #12600 — React/terminal loop containment](https://github.com/stablyai/orca/pull/12600) + +Refresh `main` and recalculate conflicts; do not follow the stale sequence +`#12882 → #12474 → #12477 → #13111` as written. + +## Required GitHub refresh before action + +At minimum, re-query: + +```bash +gh pr view 13111 --repo stablyai/orca --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,headRefOid,baseRefOid,url +gh pr view 13110 --repo stablyai/orca --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,headRefOid,baseRefOid,url +gh issue view 11729 --repo stablyai/orca --json state,title,updatedAt,url +``` + +Refresh the complete catalog in one batched request: + +```bash +handoff_query_text="$(tr '\n' ' ' < docs/reference/terminal-session-correctness-handoff-2026-08-07/github-overlap-query.graphql)" +gh api graphql -f query="$handoff_query_text" +``` + +The query includes current PR state/check summaries and unresolved-thread state +for #13110/#13111. Read PR bodies/diffs only for the slice being changed. Do not +close, comment, merge, push, or checkout a PR from the handoff audit without +explicit authorization. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/report.html b/docs/reference/terminal-session-correctness-handoff-2026-08-07/report.html new file mode 100644 index 00000000000..4497d1f42e4 --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/report.html @@ -0,0 +1,376 @@ + + + + + + + Terminal Session Correctness — Design & Test Report + + + +
+
+

Terminal Session Correctness

+

Design & test report · branch nwparker/sta-3077-reattach-pane-cardinality · PRs #13110, #13111

+
+ +
+
+214
Production lines
+
+60,903
Rejected approach
+
12
Oracles that bite
+
2 / 13
Journeys proven
+
0 / 8
Gates proven
+
2
Claims retracted
+
+ +
+

The one-sentence version

+

Every bug here is the same bug — identity compared with the wrong key, or not compared at all. A previous attempt added a second identity system beside the first at a cost of 60,903 lines and fixed none of the three root causes. This fixes all three in 214.

+
+ +

1 · What sits behind one terminal

+

Five separate things line up behind the rectangle you see.

+
+
Anatomy of a terminal⤢ zoom
+

The real computer

Orca's bookkeeping

What you see

bound to

points at

claims

runs on

Pane
a rectangle in a tab

Binding
this pane uses that shell

Lease
we own a remote shell

PTY
the shell process

Host
your Mac, or an SSH box

The real computer

Orca's bookkeeping

What you see

bound to

points at

claims

runs on

Pane
a rectangle in a tab

Binding
this pane uses that shell

Lease
we own a remote shell

PTY
the shell process

Host
your Mac, or an SSH box

+
+

The PTY is the real shell doing the work. The binding is the note connecting it to your pane. On a remote machine a lease is a second note saying “we still own that shell.” Every failure below is one of those notes pointing at the wrong thing.

+ +

2 · The reported failure

+
+
Reconnect growth — a real customer report⤢ zoom
+

2 terminals

network hiccup

reconnect

19 terminals

hiccup

20 terminals
most are ghosts

2 terminals

network hiccup

reconnect

19 terminals

hiccup

20 terminals
most are ghosts

+
+

The remote machine also fills with unused shells until it refuses to start more. A second, worse variant: an AI coding agent resumed twice — two claude processes writing to one conversation file. One report reached five.

+ +

3 · Three root causes

+ +

Cause 1 — the lease forgot its pane

+

A lease identified a shell but never checked which pane it belonged to. Every reconnect added a note; nothing removed one.

+
+
Lease accumulation⤢ zoom
+

reconnect

reconnect

Pane A

lease → shell-1

lease → shell-2

lease → shell-3

nothing retires
the old notes

next reconnect restores
all three

reconnect

reconnect

Pane A

lease → shell-1

lease → shell-2

lease → shell-3

nothing retires
the old notes

next reconnect restores
all three

+
+

FIXED A lease is identified by its pane. One pane, one live lease. Superseded leases are marked expired, not killed — the remote shell keeps running, because losing a note is not proof the shell died.

+ +

Cause 2 — reconnecting could create panes

+
+
Reattach decision⤢ zoom
+

yes

no · before

no · after

reconnect finds a lease

does its pane
still exist?

reattach — correct

invent the pane
👻 ghost appears

refuse
shell left running, unbound

yes

no · before

no · after

reconnect finds a lease

does its pane
still exist?

reattach — correct

invent the pane
👻 ghost appears

refuse
shell left running, unbound

+
+

FIXED Reattach binds only. Opening a new terminal still creates, exactly as before.

+ +

Cause 3 — a living shell reported as dead

+ + + + + + +
Real meaningReported asConsequence
This shell is goneSESSION_EXPIREDcorrect
Shell is fine — output pipe needs re-establishingSESSION_EXPIREDrespawn → agent resumed twice
+

FIXED The second case has its own message, and respawn now requires positive proof. Anything unrecognised is “unknown”, which never justifies a replacement.

+ +

4 · The rule underneath all of it

+
+
Unknown is not dead⤢ zoom
+

shell exited

can't reach it

timed out

absent from a list

3 failed retries

evidence

what does it prove?

DEAD
cleanup allowed

UNKNOWN

nothing destructive
wait · retry · ask

shell exited

can't reach it

timed out

absent from a list

3 failed retries

evidence

what does it prove?

DEAD
cleanup allowed

UNKNOWN

nothing destructive
wait · retry · ask

+
+

The liveness check also became three-valued. It previously returned yes/no, so a provider whose socket was down could only answer “no” — meaning dead — when the honest answer was “I can’t see”.

+ +

5 · What changed

+ + + + + + + + + + +
#ChangePrevents
1Reattach binds, never createsGhost panes
2Leases identified by pane2 → 19 → 20 growth
3Heal already-corrupted lease dataExisting installs stuck at 20
4“Needs re-establishing” ≠ “expired”Duplicate agent resume
5Liveness can answer “unknown”Live shells declared dead
6One PTY’s failure can’t drop the shared channelOne bad pane killing every session on a host
+
+
Change 6 — blast radius⤢ zoom
+

after

pane 3 can't re-prove
its output stream

park pane 3 only

its shell keeps running
siblings untouched

before

pane 3 can't re-prove
its output stream

give up after N tries

drop the whole
host connection

every pane, file transfer
and git command dies

after

pane 3 can't re-prove
its output stream

park pane 3 only

its shell keeps running
siblings untouched

before

pane 3 can't re-prove
its output stream

give up after N tries

drop the whole
host connection

every pane, file transfer
and git command dies

+
+
+

No wire change

+

The keystroke guard adds nothing to the payload. Orca already keeps two lookup tables in lock-step, so when they disagree that is proof the id is stale — a purely server-side check.

+
+ +

6 · How we decide a test is worth trusting

+
+

This happened to us twice

+

An end-to-end test was reported as proving the reconnect fix. It passed with the fix and with it removed — retracted. Separately, a guard shipped with no production caller at all; every test stayed green because they called the capability directly.

+
+
+
The four-step proof⤢ zoom
+

stays green

1 · run it
green

2 · delete a guard
in production code

3 · run it
MUST go red

4 · restore
green again

worthless
say so — don't ship
it as proof

stays green

1 · run it
green

2 · delete a guard
in production code

3 · run it
MUST go red

4 · restore
green again

worthless
say so — don't ship
it as proof

+
+

Delete a real guard, not the test. Prefer one clause at a time — a mutation reddening exactly one claim proves the claims independently. Watch it fail yourself: six of twelve oracles were personally re-verified, and two of those re-checks overturned the original claim.

+ +

7 · Why “same id” is not good enough

+

The most valuable lesson here. Break the quit path so it destroys shells instead of detaching, then restart:

+
tab id    same ✓
+pane id   same ✓
+pty id    same ✓
+OS pid    13756 → 8852   ✗
+start     02:01:29.337 → 02:01:34.728   ✗
+
+Every id-only restart test stays green here.
+Your shell is gone.
+
+
Proving the process really survived⤢ zoom
+
KernelShellOrcaTestKernelShellOrcaTestrestart the apptype "echo MARKER=$$"through the real write pathMARKER=13756start time of 13756?02:01:29.337ask againMARKER=13756start time of 13756?02:01:29.337 — same process ✓
KernelShellOrcaTestKernelShellOrcaTestrestart the apptype "echo MARKER=$$"through the real write pathMARKER=13756start time of 13756?02:01:29.337ask againMARKER=13756start time of 13756?02:01:29.337 — same process ✓
+
+ +

8 · Journey status

+ + + + + + + + + + + + +
#JourneyStateWhy
1Local restart — macOS · Linux · WindowsPROVENClause-selective on all three platforms
2Daemon & physical WSLPROVENClause-selective on macOS, Linux, WSL2
4Concurrent multi-hostBY CONSTRUCTIONA mux is per-host — dispose cannot cross hosts, so there is nothing to break
3Lazy discoveryNO SELECTIVE MUTATIONRemoving the real guard breaks setup before the clause is reached
6Docker MaxSessions=1PARTIAL2 clauses redden; a third survived four guard removals
12Mixed versionsWITHDRAWNThe token never crosses a version boundary in production
13Performance & scaleIN PROGRESS1 of 10 dimensions measured; rest running
5, 10, 11Device proof · identity reset · namespace admissionNO SUBJECTThe code does not exist. No oracle is writable at any effort.
+
+
Why a property may resist proof⤢ zoom
+

yes

no — true by
construction

no code exists

property to prove

is a shipped guard
protecting it?

remove it → red
provable

nothing to remove
not provable by mutation

nothing to test
not writable

yes

no — true by
construction

no code exists

property to prove

is a shipped guard
protecting it?

remove it → red
provable

nothing to remove
not provable by mutation

nothing to test
not writable

+
+
+

Read this carefully

+

“True by construction” is a good outcome — the property holds because of how the code is shaped, not because a guard watches it. It simply cannot be demonstrated by breaking something. Reporting it as proven would be false.

+
+ +

9 · Traps that can fake a result

+ + + + + + + + +
TrapEffectMitigation
Shared temp directory — the harness writes a pointer to a machine-wide pathConcurrent runs can fake a red and hide a real oneIsolated TMPDIR per run
Stale build — e2e runs a built appYou tested the old codeCheck build timestamp against source edit
Mutation silently didn’t applyTest stays green, looks like “no teeth” — wrong conclusionVerify the mutation landed before believing the result
Serial mode reports “did not run”A skip mistaken for a passRe-run the others alone under the same mutation
+

Two of our own tests were broken in ways only real hardware revealed: one failed on every Linux run (a single unpolled read where its sibling polls for 15s), and one could not execute at all on Windows (echo $$ and ps don’t exist there).

+ +

10 · Open decisions

+ + + + + + + + +
IDDecisionBlocks
D2Re-scope G4? It demands an architecture where 0 of 394 files exist, measured at +62k LOC — the approach that already failed at 0/13.G4, G1, G3
D3Strike or defer J5 / J10 / J11? They have no production subject.3 journeys
D4Architectural gates need a “reviewed diff + file list” receipt; the doc’s red-SHA template makes them structurally unpromotable.G0, G1, G4
D5The input quarantine is load-bearing, not superseded. Deleting it re-opens a verified rm -rf hazard. Amend the clause, or accept something weaker on remote hosts?G6
+
+

The hazard, verified

+

Disable the quarantine and the oracle reproduces it exactly: echo hi; rm -rf x arrives as cho hi; rm -rf x. The shell rejects cho and then runs rm -rf x. The replacement was built and costed at roughly +140 lines to delete 88 — and it does not work on remote hosts at all, because old hosts never publish the incarnation it needs.

+
+ +

11 · Corrections made along the way

+

Included because a report without them is not trustworthy.

+ + + + + + + + + + +
ClaimOutcome
“The reconnect e2e proves the fix”Retracted — passed with the fix removed, twice, isolated
“Cross-version tests confirm old clients are safe”Withdrawn — they exercise a route production never takes
“mayCreate fixes reattach”Was inert — no production caller for several commits
“A branded binding type is the fix”Rejected — three claims false; would have added a second identity system
“Fixtures compile as production”Corrected — none ship; the sweep was stopped
“bash 5.3.9 causes the WSL failure”Corrected — macOS runs the same version and passes
+ +
+ Generated for review alongside design-overview.md, test-overview.md and goalposts.md. + Click any diagram to zoom · scroll to scale · drag to pan. +
+
+ +
+ × +
+
scroll to zoom · drag to pan · Esc to close
+
+ + + + diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/resume-plan.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/resume-plan.md new file mode 100644 index 00000000000..62c4274d5ea --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/resume-plan.md @@ -0,0 +1,275 @@ +# Resume plan and validation record + +This plan preserves the comprehensive objective while allowing independently +safe stacks. It does not require reviving the 814-path construction snapshot. + +## First safe commands + +Run from the primary worktree before editing: + +```bash +pwd +git status --short --branch --untracked-files=all +git rev-parse HEAD origin/main +git rev-list --left-right --count HEAD...origin/main +git branch --list 'nwparker/react185-authority-snapshot' +git show --stat --oneline fddb19f6977 +gh pr view 13111 --repo stablyai/orca --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,headRefOid,baseRefOid,url +``` + +Expected handoff checkpoint before other changes: + +- branch `nwparker/sta-3077-reattach-pane-cardinality`; +- HEAD `5369479be2953f45cea9ab5cfcde756dd9660548`; +- snapshot branch and commit present; +- only this handoff folder and its `.gitignore` allow-list are new handoff work. + +If the branch, HEAD, or dirty paths differ, inventory and preserve them before +continuing. Never reset, clean, overwrite, or switch away from unknown user work. + +## Phase 0 — Reconcile reality before design or code + +1. Refresh `origin/main` with `git fetch origin main`—never `git pull`—and + refresh the live state/reviews of every PR in + [`related-open-work.md`](./related-open-work.md) that touches the intended + slice. +2. Recalculate the candidate merge base, categorized LOC, changed-file overlap, + and failing/obsolete tests. +3. Freeze the program accounting baseline before implementation. The default is + `5ed45739e94bdf6460364e033bfcec9b32c0b42a` (the base of #12600). Build an + aggregate carry-in ledger for every program-attributable PR already merged + after it; do not measure only the last PR in a stack. +4. Read the final diff of #13111, #12264, and #12743 with `gh pr view` and + `gh pr diff`, or in disposable isolated worktrees. Never use `gh pr checkout` + or switch branches in the primary worktree. Select or design one coherent + lease/reattach model; do not combine mutually inconsistent quarantine, kill, + and non-kill policies. +5. Reconcile #12882 before overlapping daemon-endpoint integration and #12760 + before overlapping relay-generation cleanup. Neither blocks unrelated SSH + proof work by declaration. +6. Treat the preserved snapshot as a local-only mine, not a branch to finish. + Inspect it with `git show fddb19f6977:` or in a disposable isolated + worktree; never switch the primary worktree to it. + +Decision output required before implementation: + +- exact incident mechanisms being eliminated; +- exact authority/identity semantics retained or changed; +- explicit remote-shell lifecycle and user recovery behavior; +- explicit lost-consumer liveness/compaction behavior; +- PR/stack boundaries and dependency order; +- production modules expected to be deleted; and +- tests that will discriminate the baseline from the candidate; and +- a predeclared performance protocol with fixed workloads, samples, + statistical/noise bounds, deterministic counters, and raw-data locations. + +## Phase 1 — Build discriminating journeys first + +Before relying on a code change, create or repair oracles that reproduce the +failure on an unfixed baseline. + +### STA-3077 Docker SSH oracle + +The Docker journey must: + +- run a real OpenSSH server with `MaxSessions=1` verified from the server; +- create a known pane and record tab, leaf, binding, relay PTY, and remote PID; +- seed or naturally reproduce duplicate/stale lease state from the field; +- exercise disconnect, client restart, reconnect, and authority/relay restart; +- wait an explicit settle interval after successful reattach; +- recensus visible panes, tabs, exact bindings, persisted leases, relay PTYs, + and actual remote processes/PIDs; +- prove no pane or shell is created, rebound, lost, or silently killed; +- prove explicit unresolved recovery for state that cannot be established; and +- exercise explicit close, lost shutdown response, reconnect retry, and + worktree teardown; prove exact remote PID/session-slot reclamation while an + uncertain sibling survives; and +- fail for the intended reason on the unfixed baseline. + +A clean reconnect that passes on both revisions is not this oracle. + +### Duplicate-agent oracle family + +Cover transient SSH loss, `restoreRequired`, sleeping-agent wake, worktree +switch, and closed-tab restart. Assert process count and transcript/session +ownership, not just pane/store state. No path may start a second `--resume` +process while the first process is live or unknown. + +### Daemon and remote oracles + +Cover unknown inventory, endpoint handover, daemon restart, relay generation +reuse, client sleep/wake, remote-runtime restart, and stale subscription repair. +A retry limit may end an attempt or surface a failure; it may not itself prove a +session dead or authorize destructive replacement. + +## Phase 2 — Reconcile and approve the long-term design + +The implementation design must explicitly settle: + +- final-host identity versus client routing aliases; +- canonical host-local namespace for worktree, folder, floating, drive, and UNC + forms; +- structural one-active-binding/lease ownership rather than optional metadata + plus repair scans; +- exact operation fencing across every transport; +- explicit detach, close, retirement, orphan recovery, and process-reclamation + operations; +- durable outcome/replay semantics across app, renderer, host, and transport + restarts; +- mixed-version capability and isolated legacy behavior; +- lost-device consumer retirement and compaction liveness; +- one-way migration/cutover; and +- the four-role deletion oracle and minimised, justified production-code target. + +Reuse existing pane, PTY, incarnation, CAS, and three-valued liveness primitives +where their semantics match. Do not equate client routing IDs with host identity +or namespace without proving the full semantics. + +If the chosen design differs from the preserved normative design, write an +explicit mapping for every invariant and every journey, identify what changes, +show equal or stronger safety/liveness, and obtain the user's approval. A +handoff author or implementation agent cannot approve that scope change alone. + +## Phase 3 — Implement as a convergent stack + +Stacks are allowed for reviewability. Temporary production stopgaps are not the +end state. + +A sensible dependency shape is: + +1. discriminating journey harnesses and behavior oracles; +2. final shared identity, liveness, and exact-binding primitives; +3. local/daemon/WSL/SSH/relay/paired/remote adapters using those primitives; +4. durable outcome, projection, reset, and recovery lifecycle; +5. one-way migration and capability cutover; +6. deletion of superseded writers, ledgers, repair scans, timers used as verdicts, + and duplicate state machines; retain `terminal-input-quarantine.ts` until a + replacement passes its destructive-input oracle; and +7. full platform, skew, performance, packaging, and independent review proof. + +Each stack layer must be safe and tested, but the comprehensive status remains +0/8 until the final integrated candidate satisfies the complete gates. Do not +advertise the authoritative capability or claim program completion mid-stack. + +## Phase 4 — Run the complete proof matrix + +Use [`goalposts.md`](./goalposts.md) as the checklist. All thirteen production +journeys and every row in the mandatory +[`issue-to-journey matrix`](./related-open-work.md#mandatory-issue-to-journey-matrix) +are required. At minimum the final matrix must include: + +- real macOS, Linux floor, Windows, and WSL; +- local, daemon, direct SSH, nested SSH, paired runtime, and remote server; +- one Docker host with `MaxSessions=1` and two simultaneous Docker hosts; +- git worktree, folder, floating, drive, and UNC workspaces; +- old/new peers in both directions at every changed app/daemon, SSH relay, + paired-runtime, remote-server, and mobile/E2EE boundary; +- app, renderer, daemon, relay, and remote-runtime restart; +- crash cuts around durable operations and identity reset; +- unknown/timeout/disconnect/lost-response/concurrent-replacement cases; +- actual remote PID and process accounting; and +- A/B performance and memory results under the predeclared protocol, including + raw samples, confidence intervals, deterministic counters, and leak slopes. + +## Phase 5 — Delete, census, rebase, and review + +1. Trace every new production module from a real entrypoint. +2. Delete unreachable modules and fixtures in production trees. +3. Delete all superseded legacy writers and reconciliation state machines after + cutover. +4. Rebase onto the actual PR base. +5. Rerun all journeys and static/package checks on the rebased SHA. +6. Report production, tests, docs, CI/runner, generated, and vendored LOC + separately. +7. Minimise aggregate production source net LOC against the frozen pre-program + baseline, including all program-attributable carry-in and stack layers, and + justify every net addition as required by D1. +8. Run an independent repository review and the release-readiness checklist. +9. Resolve every P0–P2 finding. +10. Only then prepare the comprehensive PR and ask the user to approve any + deliberate design change. + +## Validation status at this handoff + +This was a documentation and read-only audit turn. No product test command was +rerun, so this handoff claims no fresh local product-test pass. + +Exact validation commands run for this handoff: + +```bash +git status --short --branch --untracked-files=all +git rev-parse HEAD origin/main +git rev-list --left-right --count HEAD...origin/main +git merge-base HEAD origin/main +git diff --numstat --no-renames "$(git merge-base HEAD origin/main)"..HEAD +gh pr view 13111 --repo stablyai/orca --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,headRefOid,baseRefOid,url +handoff_query_text="$(tr '\n' ' ' < docs/reference/terminal-session-correctness-handoff-2026-08-07/github-overlap-query.graphql)" +gh api graphql -f query="$handoff_query_text" +pnpm exec oxfmt --check docs/reference/terminal-session-correctness-handoff-2026-08-07/*.md docs/reference/terminal-session-correctness-handoff-2026-08-07/*.graphql +git diff --check +``` + +Outcomes: + +- repository commands exited 0 and produced the branch/SHA/distance recorded in + `README.md`; +- the current-HEAD numstat reproduced `+309` production, `+914` tests/E2E, + `+146` docs, `+43` CI/config, and `+1,412` total net LOC; +- the reproducible GraphQL catalog returned all 65 referenced items and one + unresolved, non-outdated review thread on each of #13110 and #13111; +- all 30 linked issues appear in the mandatory issue-to-journey matrix and the + reusable GraphQL query; +- #13111 was open, non-draft, mergeable/clean, with 47 successful and 5 skipped + checks and no approval decision; and +- formatting and whitespace checks exited 0 after documentation formatting. + +Verified in this worktree: + +- repository branch, HEAD, merge base, local `origin/main`, branch distance, + and clean pre-documentation status; +- snapshot branch/commit presence and the 814-path preservation claim; +- current source implementation of the narrow #13111 behavior and gaps; +- current categorized #13111 diff census; +- original G0–G7, thirteen journeys, and PR proof contract; and +- live GitHub PR/issue state through batched GraphQL queries. + +Live GitHub verification at the time of writing showed: + +- #13111: open, non-draft, mergeable/clean, checks successful, no approval, one + unresolved major review thread; +- #13110: open, non-draft, checks successful, no approval, one unresolved major + review thread; +- #12264 and #12743: open competing STA-3077 implementations; +- #12474, #12477, and #12600: merged; and +- the other items in `related-open-work.md`: open unless explicitly labeled + merged or draft. + +These states are ephemeral and must be refreshed. + +Historical pause receipts from the 60,903-line construction snapshot remain +construction evidence only. They do not prove the current branch, G0–G7, or any +required journey. + +## Stop conditions + +Stop and return to the user before: + +- narrowing or replacing a named goalpost; +- accepting a correctness/performance tradeoff; +- deciding that remote orphan shells may be killed or leaked permanently; +- changing wire semantics without a compatibility design; +- shipping a positive-production-LOC comprehensive stack; +- merging, closing, commenting on, or force-updating external PRs; or +- deleting preserved user work. + +## Short takeover prompt + +> Continue the comprehensive terminal-session correctness program from +> [`README.md`](./README.md). Preserve the fixed status of **0/8 proven gates +> and 0/13 proven journeys** until every proof in +> [`goalposts.md`](./goalposts.md) passes on one rebased candidate. Reconcile the +> conflicting open work in [`related-open-work.md`](./related-open-work.md), +> build discriminating real SSH/daemon/paired/remote/cross-platform journeys, +> remove root causes and superseded reconciliation, minimise and justify every +> production-code addition per D1, and finish with no correctness or performance +> regression. diff --git a/docs/reference/terminal-session-correctness-handoff-2026-08-07/test-overview.md b/docs/reference/terminal-session-correctness-handoff-2026-08-07/test-overview.md new file mode 100644 index 00000000000..29083dfbb2a --- /dev/null +++ b/docs/reference/terminal-session-correctness-handoff-2026-08-07/test-overview.md @@ -0,0 +1,277 @@ +# Terminal session correctness — test design + +How we decide a test is worth trusting, what we built, and what we could not +prove. Read [`design-overview.md`](./design-overview.md) first. + +--- + +## 1. The problem with "the tests pass" + +A green test proves nothing on its own. It might pass because the code is +correct, or because the test never looked. + +```mermaid +flowchart TD + T["Test is green"] --> Q{"Would it go red if
we broke the code?"} + Q -->|"Yes"| G["Real evidence"] + Q -->|"No"| W["Worthless.
Green either way."] + Q -->|"Never checked"| U["Unknown.
Treat as worthless."] + + style G fill:#e6ffe6,stroke:#00aa00 + style W fill:#ffcccc,stroke:#cc0000 + style U fill:#fff4e6,stroke:#dd8800 +``` + +This is not hypothetical. **It happened to us twice:** + +- An end-to-end test was reported as proving the reconnect fix. It passed with + the fix **and** with the fix removed. Retracted. +- A guard was added, every test stayed green, and the guard had **no production + caller at all**. The capability existed; nothing used it. Tests passed the + whole time because they called the capability directly. + +--- + +## 2. The rule we adopted: the four-step proof + +Nothing counts as evidence until it has been through this loop. + +```mermaid +flowchart LR + S1["1. Run it
green"] --> S2["2. Delete the guard
from production code"] + S2 --> S3["3. Run it
MUST go red"] + S3 --> S4["4. Put the guard back
green again"] + S3 -.->|"stays green"| F["Test is worthless.
Say so. Don't ship it
as proof."] + + style S3 fill:#e6ffe6,stroke:#00aa00 + style F fill:#ffcccc,stroke:#cc0000 +``` + +Three rules that make this honest rather than theatre: + +**Delete a real guard, not the test.** The mutation goes in _production_ code. If +you tweak the test until it fails, you have proved nothing. + +**Prefer one clause at a time.** If a test has three claims, a good mutation +reddens exactly one and leaves the other two green. That proves the claims +_independently_ rather than as a bundle. + +**Watch it fail yourself.** A report saying "it went red" is not the same as +seeing it. Of the twelve oracles here, six were personally re-verified, and two +of those re-checks overturned the original claim. + +### The trap that nearly fooled us twice + +```mermaid +flowchart TD + M["Apply mutation"] --> C{"Did the mutation
actually land?"} + C -->|"No — silent no-op"| X["Test stays green.
You conclude 'no teeth'.
Wrong conclusion."] + C -->|"Yes"| R["Now the result
means something"] + + style X fill:#ffcccc,stroke:#cc0000 +``` + +Twice a search-and-replace matched the wrong line and changed nothing. The test +stayed green and looked like a failed oracle. **Always verify the mutation landed +before believing the result.** + +--- + +## 3. The three layers of test + +```mermaid +flowchart TD + subgraph L1["Unit — milliseconds"] + U1["Pure logic.
Does the rule compute
the right answer?"] + end + subgraph L2["Integration — seconds"] + I1["Real Electron app.
Real restarts.
Real shell processes."] + end + subgraph L3["End-to-end — minutes"] + E1["Real Docker container
running real OpenSSH.
Real network faults."] + end + L1 --> L2 --> L3 + L1 -.->|"fast, narrow"| N1[" "] + L3 -.->|"slow, real"| N2[" "] + style N1 fill:none,stroke:none + style N2 fill:none,stroke:none +``` + +The rule of thumb: **assert the strongest thing you can actually observe.** + +--- + +## 4. Why "same id" is not good enough + +The most valuable lesson from this work. + +A restart test naturally asks: _is it the same terminal?_ The easy check is +whether the ids match. That check is **too weak**, and we can prove it. + +```mermaid +flowchart TD + B["Break the quit path so it
destroys shells instead of
detaching from them"] --> R["Restart the app"] + R --> C1["tab id: same ✅"] + R --> C2["pane id: same ✅"] + R --> C3["pty id: same ✅"] + R --> C4["OS process: DIFFERENT ❌
pid 13756 → 8852"] + C3 --> W["A weak test passes here.
Your shell is gone."] + C4 --> S["Our test fails here."] + + style W fill:#ffcccc,stroke:#cc0000 + style S fill:#e6ffe6,stroke:#00aa00 +``` + +So the test asks the shell to report its **own process id** through the real +input path, then reads that process's **kernel start time**. Same id _and_ same +start time means the same process really survived — a recycled pid cannot pass. + +```mermaid +sequenceDiagram + participant T as Test + participant A as Orca + participant S as Shell + participant K as Kernel + T->>A: type "echo MARKER=$$" + A->>S: (through the real write path) + S-->>T: MARKER=13756 + T->>K: start time of 13756? + K-->>T: 02:01:29.337 + Note over T: restart the app + T->>S: ask again + S-->>T: MARKER=13756 + T->>K: start time of 13756? + K-->>T: 02:01:29.337 ✅ same process +``` + +--- + +## 5. What is covered + +### Journey 1 — a terminal survives restart · **PROVEN** + +Two claims: the same pane, binding and **OS process** survive a reload and an app +restart; and a stale operation is refused. + +| Platform | Result | Mutation A
(destructive quit) | Mutation B
(remove stale-write guard) | +| ------------------ | ------ | --------------------------------- | ----------------------------------------- | +| macOS | 2 pass | red | red | +| Linux, native | 2 pass | red | red | +| Windows 11, native | 2 pass | **red — only claim 1** | **red — only claim 2** | + +The two mutations hit **different claims**, which is what proves them separately. + +### Journey 2 — daemon and WSL · **PROVEN** + +| Environment | Result | Mutation A
(liveness can't say "unknown") | Mutation B
(widen owner fallback) | +| --------------- | ------ | --------------------------------------------- | ------------------------------------- | +| macOS | 3 pass | red — claim 1 only | red — claim 3 only | +| Linux, native | 3 pass | red — claim 1 only | red — claim 3 only | +| WSL2 on Windows | 3 pass | red — claim 1 only | — | + +> **A subtlety worth knowing.** These tests run in order, so when the first one +> fails the others report "did not run" — that is a _skip_, not a pass. To prove +> the mutation really only hit claim 1, we re-ran claims 2 and 3 **alone, with +> the mutation still applied**, and watched them stay green. + +### Other oracles that bite + +| Oracle | Mutation that reddens it | +| ---------------------------- | ------------------------------------------------ | +| Reconnect grafts no pane | Remove "bind, never create" | +| Superseded-keystroke fence | Remove the guard from the handlers | +| Guard is actually wired up | Remove the call sites, keep the function | +| Workspace ids don't collide | Restore the suffix-stripping comparison | +| Wire compatibility | Restore the wrong "expired" message | +| `rm -rf` hazard stays closed | Disable the quarantine → `cho hi; rm -rf x` runs | + +That last one is why we did **not** delete the quarantine module. + +--- + +## 6. What we could not prove, and why + +This is the honest half. + +```mermaid +flowchart TD + P["Property we want
to prove"] --> Q{"Is there a shipped
guard protecting it?"} + Q -->|"Yes"| M["Remove it → test reddens.
Provable"] + Q -->|"No — it's true
by construction"| C["Nothing to remove.
Not provable by mutation"] + Q -->|"No code exists
at all"| N["Nothing to test.
Not writable"] + + style M fill:#e6ffe6,stroke:#00aa00 + style C fill:#fff4e6,stroke:#dd8800 + style N fill:#ffcccc,stroke:#cc0000 +``` + +| Journey | Why not proven | +| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| Two hosts don't interfere | True **by construction** — each host has its own channel, so there is no shared thing to break. Four attempts to redden it failed, correctly. | +| Lazy host discovery | One claim has no mutation that hits it alone; removing the real guard breaks setup before the claim is reached. | +| `MaxSessions=1` reconnect | Two claims redden. A third survived **four** different guard removals — nothing shipped protects it. | +| Mixed versions, live | The new message **never crosses a version boundary** in production. Our in-process tests exercise a route the real app doesn't take. Withdrawn. | +| Performance | 1 of 10 required dimensions measured. The keystroke guard costs ~14ns, but measured outside the real app. | +| Three others | The features they test **do not exist** in the code. No test can be written. | + +**"True by construction" is a good outcome, not a failure** — it means the +property holds because of how the code is shaped, not because a guard is +watching. It just can't be demonstrated by breaking something. + +--- + +## 7. Environment traps that can fake a result + +Real problems we hit, worth knowing before trusting any run. + +```mermaid +flowchart TD + subgraph T1["Shared temp directory"] + A1["Test harness writes a pointer
to a machine-wide temp path"] --> A2["Two runs at once
overwrite each other"] + A2 --> A3["Can fake a red
and hide a real one"] + end + subgraph T2["Stale build"] + B1["e2e runs a built app"] --> B2["Edit source, forget rebuild"] + B2 --> B3["You tested the old code"] + end + style A3 fill:#ffcccc,stroke:#cc0000 + style B3 fill:#ffcccc,stroke:#cc0000 +``` + +So every run isolates its temp directory, and we check build timestamps against +source edits before believing a result. + +Two more, found by running on machines we don't develop on: + +- A test failed on **every** Linux run. Not a product bug: it read a value once, + immediately after a reload, where its sibling helper polls for 15 seconds. +- A test could not run on **Windows at all** — it used `echo $$` and `ps`, which + don't exist there. The Windows claim wasn't unproven, it was _unprovable_. + +Both were bugs in tests we wrote, found only by running on the real platform. + +--- + +## 8. Scoreboard + +```mermaid +pie showData + title Journeys + "Proven with discrimination" : 2 + "Oracle exists, cannot discriminate" : 5 + "No code exists to test" : 3 + "Not yet attempted" : 3 +``` + +| Measure | Value | +| ------------------------------- | ----------- | +| Journeys proven | **2 of 13** | +| Gates proven | **0 of 8** | +| Oracles that bite | 12 | +| …personally re-verified | 6 | +| Claims retracted after checking | 2 | +| Production code added | +214 lines | + +The retraction count is the number to look at. Two claims that looked green were +withdrawn after checking. That is the process working — and the reason to trust +the two journeys that survived it. diff --git a/docs/reference/worktree-scan-fingerprint.md b/docs/reference/worktree-scan-fingerprint.md new file mode 100644 index 00000000000..f82d453a82c --- /dev/null +++ b/docs/reference/worktree-scan-fingerprint.md @@ -0,0 +1,274 @@ +# Steady-state worktree rescan: Git-admin fingerprint gate + +## Status + +Adopted for the main-process worktree resolution cache +(`OrcaRuntimeService.listRepoWorktreesForResolution`). It keeps the existing +30-second freshness contract for externally created, removed, moved, locked, and +re-checked-out worktrees while removing the `git worktree list` subprocess that +previously ran for every registered repository every 30 seconds. + +## Context + +A production trace (10 registered repositories, 3 h 27 min) recorded 4,272 +`git worktree` invocations and 8,663 total Git subprocesses. The invocations +arrived in full-fleet sweeps roughly every 30.5 s — one sweep per repository per +`WORKTREE_SCAN_CACHE_TTL_MS`. + +### What actually expires the cache + +The originating report assumed some specific terminal/status/orchestration +request was invalidating the 30-second cache. That is not what happens, and the +distinction changes the fix: + +- `resolvedWorktreeCache` (the whole-fleet snapshot) has a **1-second** TTL + (`RESOLVED_WORKTREE_CACHE_TTL_MS`). Any caller polling faster than 1 Hz + recomputes the snapshot. +- `computeResolvedWorktrees` fans out over **every** registered repo + (`src/main/runtime/orca-runtime.ts`), calling + `listRepoWorktreesForResolution` per repo. +- That per-repo call is backed by `worktreeScanCache` with a **30-second** TTL. + When it expires, the next poll shells out. + +So no request "expires" the 30-second cache. It expires on wall-clock time, and +whichever poller arrives first afterwards pays a full-fleet `git worktree list` +fan-out. The many high-frequency callers — `listTerminals` without a selector, +`showTerminal`, `getWorktreePs`, `listManagedWorktrees`, +`resolveWorktreeSelector`, orchestration authority refresh — only determine +*who* pays, not *how often*. Steady-state subprocess volume is therefore +`repos / 30 s`, independent of poll rate, which is exactly the observed +~1 sweep / 30.5 s. + +The in-Orca mutation surface is already event-driven: create, remove, rename, +folder-rename, sparse edits, repo add/update/remove, SSH reconnect, and +mixed-version remote invalidation all call +`invalidateWorktreeScanCacheForRepo` / `invalidateResolvedWorktreeCache` +(≈40 call sites). The 30-second TTL exists for exactly one reason: discovering +worktree changes made **outside** Orca (`git worktree add/remove/move/prune`, +`git checkout` in another worktree, `rm -rf` of a worktree directory). + +That is a filesystem question, and the filesystem can answer it without a +subprocess. + +## Goals + +- Remove the periodic all-repository `git worktree list` fan-out in steady + state. +- Preserve the current ≈30 s discovery latency for externally created, removed, + moved, pruned, locked/unlocked, and re-checked-out worktrees. +- Keep a bounded reconciliation so anything the cheap probe cannot observe still + converges. +- Change nothing for SSH repos, WSL-routed repos, folder workspaces, bare repos, + or hosts where the probe cannot resolve Git's admin layout. +- Fail open: any probe error must behave exactly like today (run the real scan). + +## Non-goals + +- Changing `RESOLVED_WORKTREE_CACHE_TTL_MS` or the whole-fleet snapshot shape. +- Changing the renderer-facing `worktrees:list` / `worktrees:listAll` IPC scan + cache in `src/main/ipc/worktrees.ts` (separate 5 s cache, invalidated by + `registerWorktreeChangeInvalidator`, not a polling source in the trace). +- Scoping `resolveWorktreeSelector` to a single repository. See + "Rejected alternatives". +- Adding a filesystem watcher per repository. +- Any wire/RPC/persisted-schema change. + +## Design + +Introduce a cheap, subprocess-free **Git worktree admin fingerprint** for a +local repository, and consult it before re-running a scan whose TTL has expired. + +### Fingerprint inputs + +`readRepoWorktreeAdminFingerprint(repoPath)` in +`src/main/runtime/repo-worktree-admin-fingerprint.ts` resolves the repo's Git +common directory without a subprocess (read `.git`; if it is a `gitdir:` file, +follow it and then its `commondir`; if `.git` is absent, treat `repoPath` as a +bare gitdir), then records: + +| Input | External change it catches | +| --- | --- | +| sorted entry names of `/worktrees` | `worktree add`, `worktree remove`, `worktree prune` | +| existence of `repoPath` | main checkout deleted | +| `/packed-refs` mtime + size | a tip moved while its loose ref is packed away | +| `/reftable` mtime + size | a tip moved under the reftable backend | +| per checkout: `HEAD` contents | branch switch, detach (the detached oid is in HEAD itself) | +| per checkout: contents of the ref HEAD names | a plain `git commit`, `reset`, or `fetch` that moves the tip | +| per entry: `gitdir` contents | `worktree move`, `worktree repair` | +| per entry: `locked` presence | `worktree lock` / `unlock` | +| per entry: existence of the path named by `gitdir` | a worktree directory deleted with `rm -rf` (flips `prunable`) | + +"per checkout" covers the main worktree and each linked worktree. Reading the +ref HEAD names is what makes an ordinary commit visible: committing rewrites +`refs/heads/` and leaves `HEAD` untouched, but moves the oid +`git worktree list --porcelain` prints. A symref target is only followed when it +is a relative path under `refs/`, so a hand-edited `HEAD` cannot steer the probe +outside the ref store. + +Every input is a `stat`, `readdir`, or small `readFile` on an already-hot inode, +and the fingerprint depends on nothing but the repo path — no prior scan result +is threaded in. Per-repo fan-out is capped at 8 concurrent linked-worktree +probes, mirroring `SPARSE_CHECKOUT_DETECTION_CONCURRENCY`. A 10-repo fleet with +10 worktrees each costs a few hundred filesystem calls per 30 s window versus 10 +process spawns; the spawns dominate by orders of magnitude, and process-table +churn was the reported symptom. + +The fingerprint is a NUL-delimited string; any read failure yields `null`, which +the caller treats as "cannot prove unchanged". + +### Cache decision + +`listRepoWorktreesForResolution` gains one branch on the expired-TTL path: + +```text +cached entry exists, same generation + runtimeKey, TTL expired + └─ probe eligible? (no connectionId, no wslDistro, fingerprint recorded) + ├─ no → real scan (today's behaviour) + └─ yes → read fingerprint now + ├─ null or different → real scan + ├─ equal, last real scan < 5 min → extend TTL, no subprocess + └─ equal, last real scan ≥ 5 min → real scan (bounded reconcile) +``` + +`WORKTREE_SCAN_ADMIN_RECONCILE_INTERVAL_MS` is 5 min, matching the existing +`WORKTREE_SCAN_AGENT_SCRATCH_TTL_MS` precedent. A cached result whose scan +failed (`ok: false`) is never extended, so a transient Git failure still retries +on the 30 s TTL. + +### Git version compatibility + +Every path the probe reads is part of Git's on-disk layout well before the 2.25 +baseline in [`git-compatibility.md`](./git-compatibility.md): `.git` as a +directory or `gitdir:` file, `commondir`, `worktrees//{HEAD,gitdir,locked}`, +`packed-refs`, and loose `refs/`. `reftable` arrived in 2.45; on older Git it +simply stats as missing, which is a stable value and therefore harmless. No new +Git command is introduced — this change only skips one. + +Agent-scratch repos already carry a 5-minute scan TTL +(`WORKTREE_SCAN_AGENT_SCRATCH_TTL_MS`), which equals the reconciliation +interval, so the gate never fires for them and their behaviour is unchanged. + +### Ordering + +The fingerprint stored with a scan result is captured **before** the scan runs. +A mutation landing while the scan is in flight therefore leaves the stored +fingerprint stale-by-construction, so the next probe sees a difference and +rescans. Capturing after the scan would let that mutation be masked forever. + +### Interaction with existing invalidation + +Untouched. `invalidateWorktreeScanCacheForRepo` deletes the entry (fingerprint +included) and bumps the generation, so every event-driven path still forces a +real scan on the next read. The fingerprint only ever *extends* an entry that +the TTL alone would have refreshed. + +## Freshness budget + +| Change | Before | After | +| --- | --- | --- | +| Orca-initiated create/remove/rename/sparse/repo edit | immediate (event) | immediate (event) | +| SSH reconnect / provider generation bump | immediate (event) | immediate (event) | +| External `worktree add/remove/move/prune/lock` | ≤ 30 s | ≤ 30 s | +| External `git checkout` / `commit` / `reset` in any worktree | ≤ 30 s | ≤ 30 s | +| External `rm -rf ` | ≤ 30 s | ≤ 30 s | +| External sparse-checkout pattern edit | ≤ 30 s | ≤ 5 min | +| Packed/reftable tip moved within one mtime tick at an equal file size | ≤ 30 s | ≤ 5 min | +| SSH / WSL repos, folder workspaces | unchanged | unchanged | + +The two regressions are bounded by the reconciliation interval and are both +changes Orca does not make itself. + +### Main-thread cost + +Both the scan and the probe are asynchronous, so neither "runs on the main +thread" in the naive sense — but they are not equally free there. Measured on +macOS with a 1 ms interval sampling event-loop lag while each ran 30 times +against a repo with 20 linked worktrees: + +| | wall per call | main-thread stall per call | worst single stall | +| --- | --- | --- | --- | +| `git worktree list` | 18.66 ms | 2.69 ms | 3.02 ms | +| fingerprint probe | 1.66 ms | 0.01 ms | 0.04 ms | + +`fs/promises` dispatches to libuv's threadpool, so ~99 % of the probe's latency +is off-thread. Spawning Git does not: `uv_spawn`, fd and pipe setup, and stdout +collection and decoding are real synchronous main-process work. Ten repos +refreshing together therefore cost ≈27 ms of event-loop stall per sweep before +this change and ≈0.1 ms after — this reduces main-thread pressure rather than +adding to it, which is why moving either side onto a worker thread would not +help. + +### Residual risk + +A repo registered at a UNC path (`\\wsl$\...`) but executed by the local Windows +Git runtime is still probed, because it is not WSL-routed from Orca's point of +view. The probe is correct there and strictly cheaper than the subprocess it +replaces, but its filesystem calls cross the 9p boundary like the existing +sparse-checkout probes already do. + +## Measured effect + +`src/main/runtime/worktree-scan-admin-fingerprint-gate.test.ts` drives the +reported steady state — 10 idle local repos, a caller polling at 1 Hz for 30 +simulated minutes — and counts `git worktree list` invocations: + +| | `git worktree list` per 30 min | per hour | +| --- | --- | --- | +| TTL only (before) | 600 | 1,200 | +| fingerprint gate (after) | 60 | 120 | + +A 90 % reduction, with the remainder being the bounded reconciliation. Repos +with genuine external activity keep rescanning at the 30 s cadence because the +fingerprint flips. + +Extrapolating to the original trace's shape (10 repos, 3 h 27 min): 4,272 +`git worktree` invocations would become ≈427. + +## Rejected alternatives + +**Raise `WORKTREE_SCAN_CACHE_TTL_MS` to 5 min.** One line, same subprocess +reduction, but it degrades *every* external-change latency to 5 min, including +the common "I ran `git worktree add` in a terminal" case. The fingerprint buys +the same reduction without that regression. + +**Per-repo `fs.watch` on `/worktrees`.** Lower latency, but adds +persistent watcher handles per repo, inherits recursive-watch platform +differences, and would need its own dormancy/rearm story. The existing watcher +infrastructure is scoped to workspace files; extending it to Git admin dirs is a +larger change with a worse risk profile for the same steady-state win. + +**Scope `resolveWorktreeSelector` to the owning repository.** The original brief +asks for this. `listTerminals` already avoids the fan-out for explicit worktree +ids via `buildResolvedWorktreeFromId` + +`listKnownResolvedWorktreesForExplicitTarget`. Extending that to +`resolveWorktreeSelector` means splitting the highest-fan-in method in the +runtime (38 call sites) and rebuilding lineage projection for a repo subset — +material regression risk. Once the fingerprint gate lands, the remaining +fan-out cost for a targeted call is a batch of stats, not a subprocess, so the +gain no longer justifies the risk. Tracked as follow-up, not in this change. + +## Test plan + +`src/main/runtime/repo-worktree-admin-fingerprint.test.ts` (real temp dirs, real +`git` binary — a mocked filesystem would only restate the assumptions): + +- stable across repeated reads with no change +- changes after `worktree add`, `worktree remove`, `worktree move`, + `worktree lock`, `checkout` in a linked worktree, `checkout` in the main + worktree, a commit in either, and `rm -rf` of a worktree directory +- still tracks a tip whose loose ref has been packed away by `git pack-refs` +- a linked worktree path and the main repo path produce the same fingerprint +- a bare repo resolves through its own gitdir and still tracks `worktree add` +- `null` for a non-Git directory and for a missing path + +`src/main/runtime/worktree-scan-admin-fingerprint-gate.test.ts`: + +- unchanged fingerprint suppresses the rescan past the 30 s TTL and re-arms it +- changed fingerprint rescans at the 30 s TTL +- the 5-minute reconciliation forces a rescan while the fingerprint is unchanged +- `notifyBranchRenamed` (event invalidation) still forces an immediate rescan +- a `null` fingerprint (probe failure) falls back to scanning +- SSH repos never consult the probe +- a failed scan is never extended +- concurrent callers share one probe and one scan +- the 1 Hz / 10-repo workload measurement above diff --git a/mobile/app/h/[hostId]/files/preview/[worktreeId].tsx b/mobile/app/h/[hostId]/files/preview/[worktreeId].tsx index 65412d51958..df60f8fc117 100644 --- a/mobile/app/h/[hostId]/files/preview/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/files/preview/[worktreeId].tsx @@ -10,6 +10,11 @@ export default function MobileFilePreviewRoute() { source?: string | string[] absolutePath?: string | string[] grantId?: string | string[] + terminal?: string | string[] + pathText?: string | string[] + cwd?: string | string[] + nativeChatTab?: string | string[] + nativeChatSession?: string | string[] line?: string | string[] column?: string | string[] name?: string | string[] diff --git a/mobile/app/h/[hostId]/session/[worktreeId].tsx b/mobile/app/h/[hostId]/session/[worktreeId].tsx index cf0f1dd7edb..123a1212eb0 100644 --- a/mobile/app/h/[hostId]/session/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/session/[worktreeId].tsx @@ -127,6 +127,15 @@ import type { TerminalLiveInputSender } from '../../../../src/terminal/terminal- import { isTerminalSendRpcAccepted } from '../../../../src/terminal/terminal-send-rpc-response' import { sendMobileTerminalQueryReply } from '../../../../src/terminal/mobile-terminal-query-reply' import { TERMINAL_QUERY_REPLY_INPUT_RUNTIME_CAPABILITY } from '../../../../../src/shared/protocol-version' +import { + addLegacyTerminalAttributionDisableRequest, + MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE, + withLegacyTerminalAttributionDisabledEnv +} from '../../../../../src/shared/legacy-terminal-attribution-env' +import { + assertMobileTerminalAttributionDisableSupported, + MOBILE_TERMINAL_CREATE_RPC_OPTIONS +} from '../../../../src/session/mobile-terminal-attribution-compat' import { useTerminalLiveInputCommit } from '../../../../src/terminal/use-terminal-live-input-commit' import { resolveMobileTerminalInputGate } from '../../../../src/terminal/terminal-input-connection-gate' import { @@ -917,6 +926,9 @@ export default function SessionScreen() { } | null>(null) const terminalUnsubsRef = useRef void>>(new Map()) const subscribingHandlesRef = useRef>(new Set()) + // Why: a lease-only subscribe never renders, so the reconciler needs to tell it apart + // from a stream that does — an uncovered handle holding one is a blank terminal. + const leaseOnlyHandlesRef = useRef>(new Set()) const initializedHandlesRef = useRef>(new Set()) const terminalDiagnosticsRef = useRef(new MobileTerminalDiagnostics()) // Why: bounds the scrollback→resubscribe fit loop per handle (STA-3337). @@ -1233,6 +1245,7 @@ export default function SessionScreen() { terminalUnsubsRef.current.get(handle)?.() terminalUnsubsRef.current.delete(handle) subscribingHandlesRef.current.delete(handle) + leaseOnlyHandlesRef.current.delete(handle) terminalDiagnosticsRef.current.terminalUnsubscribed(handle) subscribeSeqRef.current.set(handle, (subscribeSeqRef.current.get(handle) ?? 0) + 1) // Why: reset the high-water mark so a fresh subscription's first scrollback isn't dropped as stale. @@ -1265,6 +1278,7 @@ export default function SessionScreen() { clearNativeChatInputLease() terminalUnsubsRef.current.clear() subscribingHandlesRef.current.clear() + leaseOnlyHandlesRef.current.clear() initializedHandlesRef.current.clear() terminalDiagnosticsRef.current.clearTerminalCache() viewportResubscribeBudgetRef.current.clear() @@ -1331,6 +1345,11 @@ export default function SessionScreen() { } subscribingHandlesRef.current.add(handle) + if (covered) { + leaseOnlyHandlesRef.current.add(handle) + } else { + leaseOnlyHandlesRef.current.delete(handle) + } const seq = (subscribeSeqRef.current.get(handle) ?? 0) + 1 subscribeSeqRef.current.set(handle, seq) diagnostics.streamArmed(handle, seq, viewportRef.current) @@ -1519,6 +1538,7 @@ export default function SessionScreen() { streamRevision: coveredStreamRevision, subscriptionsRef: terminalUnsubsRef, subscribingRef: subscribingHandlesRef, + leaseOnlyRef: leaseOnlyHandlesRef, webReadyRef: webReadyHandlesRef, initializedRef: initializedHandlesRef, subscribe: subscribeToTerminal, @@ -3085,6 +3105,10 @@ export default function SessionScreen() { hostId, worktreeId, worktreeName: routeWorktreeName, + nativeChatSessionId: + activeSessionTab?.type === 'terminal' + ? (activeSessionTab.agentStatus?.providerSession?.id ?? null) + : null, activeHandleRef, terminalCwdRef, openBrowser: (url) => void handleCreateBrowserRef.current?.(url), @@ -3650,20 +3674,27 @@ export default function SessionScreen() { .slice(2, 10)}` try { - const response = await client.sendRequest('session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - afterTabId: activeSessionTabId ?? undefined, - clientMutationId, - ...(options?.startupCommand ? { command: options.startupCommand } : {}), - ...(options?.startupCommandDelivery - ? { startupCommandDelivery: options.startupCommandDelivery } - : {}), - ...(options?.agentPrompt ? { agentPrompt: options.agentPrompt } : {}), - ...(agent ? { agent } : {}), - activate: false, - select: true, - navigation: 'caller' - }) + const authority = await assertMobileTerminalAttributionDisableSupported(client) + const response = await client.sendRequest( + 'session.tabs.createTerminal', + { + worktree: `id:${worktreeId}`, + afterTabId: activeSessionTabId ?? undefined, + clientMutationId, + ...(options?.startupCommand ? { command: options.startupCommand } : {}), + ...(options?.startupCommandDelivery + ? { startupCommandDelivery: options.startupCommandDelivery } + : {}), + env: withLegacyTerminalAttributionDisabledEnv(undefined), + envToDelete: addLegacyTerminalAttributionDisableRequest(undefined), + ...(options?.agentPrompt ? { agentPrompt: options.agentPrompt } : {}), + ...(agent ? { agent } : {}), + activate: false, + select: true, + navigation: 'caller' + }, + { ...MOBILE_TERMINAL_CREATE_RPC_OPTIONS, expectedRuntimeId: authority.runtimeId } + ) if (response.ok) { const result = (response as RpcSuccess).result as TerminalCreateResult const created = result.tab @@ -3763,10 +3794,17 @@ export default function SessionScreen() { showToast(message, 1800) } } - } catch { - const message = options?.errorToast ?? 'Failed to create terminal' + } catch (error) { + const errorMessage = error instanceof Error ? error.message : null + const message = + errorMessage === MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE + ? errorMessage + : (options?.errorToast ?? errorMessage ?? 'Failed to create terminal') setCreateError(message) - if (options?.errorToast) { + if ( + options?.errorToast || + errorMessage === MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE + ) { triggerError() showToast(message, 1800) } diff --git a/mobile/fastlane/Fastfile b/mobile/fastlane/Fastfile index 6e66a72bada..204c14672b6 100644 --- a/mobile/fastlane/Fastfile +++ b/mobile/fastlane/Fastfile @@ -253,6 +253,9 @@ platform :ios do upload_to_testflight( api_key: api_key, app_identifier: BUNDLE_ID, + # distribute_only means there is no local .ipa to sniff, so fastlane would + # otherwise fall through to an interactive platform prompt and crash in CI. + app_platform: "ios", app_version: version, build_number: build_number, distribute_only: true, diff --git a/mobile/src/components/markdown-file-path-detection.ts b/mobile/src/components/markdown-file-path-detection.ts index 5e320a3f10c..c51151b9ebf 100644 --- a/mobile/src/components/markdown-file-path-detection.ts +++ b/mobile/src/components/markdown-file-path-detection.ts @@ -3,6 +3,8 @@ // viewer). We deliberately favor precision over recall: a missed path is a minor // annoyance, but a false positive on prose or a version number is a broken tap. +import { parseFileLinkLocation } from '../../../src/shared/file-link-location' + export type FilePathSegment = | { type: 'text'; value: string } | { type: 'file'; value: string; path: string } @@ -101,8 +103,6 @@ function hasMidTokenAt(candidate: string): boolean { return /[^\\/]@/.test(candidate) } -const LINE_SUFFIX_PATTERN = /^(.+?):([1-9]\d*)(?::([1-9]\d*))?$/ - /** * Split an agent-style `path:line(:col)` citation into its parts. Windows drive * colons are safe: only a trailing all-digit suffix is treated as a line ref. @@ -112,14 +112,14 @@ export function splitFilePathLineSuffix(pathText: string): { line: number | null column: number | null } { - const match = LINE_SUFFIX_PATTERN.exec(pathText) - if (!match) { + const parsed = parseFileLinkLocation(pathText) + if (!parsed || (parsed.line === null && parsed.column === null)) { return { path: pathText, line: null, column: null } } return { - path: match[1]!, - line: Number.parseInt(match[2]!, 10), - column: match[3] ? Number.parseInt(match[3], 10) : null + path: parsed.pathText, + line: parsed.line, + column: parsed.column } } diff --git a/mobile/src/components/mobile-markdown-preview-html.ts b/mobile/src/components/mobile-markdown-preview-html.ts index 8b2d247f8f2..8bb5fca0934 100644 --- a/mobile/src/components/mobile-markdown-preview-html.ts +++ b/mobile/src/components/mobile-markdown-preview-html.ts @@ -97,7 +97,7 @@ function attrValue(tag: string, name: string): string { const valueStart = cursor if (quote) { const valueEnd = tag.indexOf(quote, cursor) - if (valueEnd < 0) { + if (valueEnd === -1) { return '' } cursor = valueEnd + 1 diff --git a/mobile/src/components/mobile-markdown-preview-tag-stripper.ts b/mobile/src/components/mobile-markdown-preview-tag-stripper.ts index 90e3c3cc3cc..6eeca2aa612 100644 --- a/mobile/src/components/mobile-markdown-preview-tag-stripper.ts +++ b/mobile/src/components/mobile-markdown-preview-tag-stripper.ts @@ -191,7 +191,7 @@ function closingMarkupTagNames(value: string): Set { let cursor = 0 while (cursor < value.length) { const start = value.indexOf('<', cursor) - if (start < 0) { + if (start === -1) { return names } const end = findMobileMarkdownMarkupTagEnd(value, start + 1) @@ -228,7 +228,7 @@ export function stripMobileMarkdownMarkupTags(value: string): string { const closingTagNames = closingMarkupTagNames(value) while (cursor < value.length) { const start = value.indexOf('<', cursor) - if (start < 0) { + if (start === -1) { return output + value.slice(cursor) } output += value.slice(cursor, start) @@ -261,7 +261,7 @@ export function stripMobileMarkdownMarkupTags(value: string): string { !/[-:]/.test(name) && !knownMarkupTagNames.has(lowerName) && !closingTagNames.has(lowerName) - if (isNestedGeneric && nestedStart >= 0) { + if (isNestedGeneric && nestedStart !== -1) { output += value.slice(start, nestedStart) cursor = nestedStart continue diff --git a/mobile/src/files/MobileFilePreviewScreen.test.ts b/mobile/src/files/MobileFilePreviewScreen.test.ts index 1595454a12a..fa61f7351c6 100644 --- a/mobile/src/files/MobileFilePreviewScreen.test.ts +++ b/mobile/src/files/MobileFilePreviewScreen.test.ts @@ -39,6 +39,21 @@ describe('MobileFilePreviewScreen', () => { ).toBe(false) }) + it('treats native-chat artifact grants as read-only', () => { + expect( + isEditableMobileTerminalArtifactPreview( + { + status: 'ready', + kind: 'text', + content: '

Result

', + truncated: false, + byteLength: 15 + }, + true + ) + ).toBe(false) + }) + it('keeps dirty terminal artifact drafts protected while preview is waiting for reconnect', () => { const sourceKey = sourceKeyForPreview({ source: 'terminalArtifact', diff --git a/mobile/src/files/MobileFilePreviewScreen.tsx b/mobile/src/files/MobileFilePreviewScreen.tsx index 0879e02ec7e..3f56890243a 100644 --- a/mobile/src/files/MobileFilePreviewScreen.tsx +++ b/mobile/src/files/MobileFilePreviewScreen.tsx @@ -181,7 +181,8 @@ export function MobileFilePreviewScreen({ route }: Props) { ) const meta = previewParams ? `${worktreeLabel} - ${displayPath}` : 'Preview' const isEditableTerminalArtifact = - previewSource?.source === 'terminalArtifact' && isEditableMobileTerminalArtifactPreview(preview) + previewSource?.source === 'terminalArtifact' && + isEditableMobileTerminalArtifactPreview(preview, previewSource.readOnly === true) const canSaveArtifact = isEditableTerminalArtifact && draftSourceKeyRef.current === previewSourceKey && diff --git a/mobile/src/files/file-tree.ts b/mobile/src/files/file-tree.ts index 71f26ca155b..8a3e795ac2d 100644 --- a/mobile/src/files/file-tree.ts +++ b/mobile/src/files/file-tree.ts @@ -132,7 +132,7 @@ export function getDirectoryCacheState( ): DirectoryState | undefined { // Why: repository paths are arbitrary object keys; inherited keys like // "constructor" must not masquerade as loaded directory state. - return Object.prototype.hasOwnProperty.call(cache, relativePath) ? cache[relativePath] : undefined + return Object.hasOwn(cache, relativePath) ? cache[relativePath] : undefined } export function joinRelativePath(parentPath: string, name: string): string { diff --git a/mobile/src/files/mobile-file-preview-editability.ts b/mobile/src/files/mobile-file-preview-editability.ts index ff0fa18d3cb..d8ed196e5cb 100644 --- a/mobile/src/files/mobile-file-preview-editability.ts +++ b/mobile/src/files/mobile-file-preview-editability.ts @@ -3,7 +3,13 @@ import type { MobileFilePreviewSource } from './mobile-file-preview-request' -export function isEditableMobileTerminalArtifactPreview(preview: MobileFilePreviewResult): boolean { +export function isEditableMobileTerminalArtifactPreview( + preview: MobileFilePreviewResult, + readOnly = false +): boolean { + if (readOnly) { + return false + } return ( (preview.status === 'ready' && preview.kind !== 'image' && !preview.truncated) || preview.status === 'empty' diff --git a/mobile/src/files/mobile-file-preview-request.test.ts b/mobile/src/files/mobile-file-preview-request.test.ts index f7f77fabd19..fe15cad0b07 100644 --- a/mobile/src/files/mobile-file-preview-request.test.ts +++ b/mobile/src/files/mobile-file-preview-request.test.ts @@ -179,6 +179,47 @@ describe('mobile-file-preview-request', () => { }) }) + it('refreshes a native-chat artifact grant with the same transcript provenance', async () => { + const client = clientWithResponses([ + fail('terminal_file_grant_expired'), + ok({ + exists: true, + isDirectory: false, + openTarget: { + kind: 'absolute-file', + absolutePath: '/Users/ada/orca-plans/result.html', + grantId: 'grant-2', + readOnly: true + } + }), + ok({ content: '

Result

', truncated: false, byteLength: 15 }) + ]) + + const onTerminalArtifactSourceRefreshed = vi.fn() + await loadMobileFilePreview( + client, + { + source: 'terminalArtifact', + worktreeId: 'wt-1', + absolutePath: '/Users/ada/orca-plans/result.html', + grantId: 'grant-1', + pathText: '~/orca-plans/result.html', + nativeChatContext: { tabId: 'tab-1', sessionId: 'session-1' } + }, + undefined, + { onTerminalArtifactSourceRefreshed } + ) + + expect(client.sendRequest).toHaveBeenNthCalledWith(2, 'files.resolveTerminalPath', { + worktree: 'id:wt-1', + pathText: '~/orca-plans/result.html', + nativeChatContext: { tabId: 'tab-1', sessionId: 'session-1' } + }) + expect(onTerminalArtifactSourceRefreshed).toHaveBeenCalledWith( + expect.objectContaining({ grantId: 'grant-2', readOnly: true }) + ) + }) + it.each([ ['terminal_file_grant_expired'], ['terminal_file_grant_mismatch'], @@ -242,6 +283,25 @@ describe('mobile-file-preview-request', () => { }) }) + it('does not send writes for read-only native-chat artifacts', async () => { + const client = clientWith(ok({ ok: true })) + + await expect( + saveMobileTerminalArtifactPreview( + client, + { + source: 'terminalArtifact', + worktreeId: 'wt-1', + absolutePath: '/Users/ada/orca-plans/result.html', + grantId: 'grant-1', + readOnly: true + }, + '

Changed

' + ) + ).resolves.toMatchObject({ status: 'error' }) + expect(client.sendRequest).not.toHaveBeenCalled() + }) + it('does not refresh and retry a failed terminal artifact save without a base content check', async () => { const client = clientWithResponses([fail('terminal_file_grant_mismatch')]) diff --git a/mobile/src/files/mobile-file-preview-request.ts b/mobile/src/files/mobile-file-preview-request.ts index ff6cd755c50..63b61326654 100644 --- a/mobile/src/files/mobile-file-preview-request.ts +++ b/mobile/src/files/mobile-file-preview-request.ts @@ -116,6 +116,9 @@ export async function saveMobileTerminalArtifactPreview( content: string, options: TerminalArtifactSaveOptions = {} ): Promise { + if (source.readOnly) { + return previewError('This file is read-only') + } let writeSource = source if (typeof options.baseContent === 'string') { const verified = await verifyTerminalArtifactBaseContent( diff --git a/mobile/src/files/mobile-file-preview-route.test.ts b/mobile/src/files/mobile-file-preview-route.test.ts index ac1888ed46f..784313464ee 100644 --- a/mobile/src/files/mobile-file-preview-route.test.ts +++ b/mobile/src/files/mobile-file-preview-route.test.ts @@ -65,6 +65,8 @@ describe('mobile-file-preview-route', () => { terminal: 'term-1', pathText: 'result.json', cwd: '/tmp/run', + nativeChatTab: 'tab-1', + nativeChatSession: 'session-1', line: '12', column: '3' }) @@ -80,6 +82,8 @@ describe('mobile-file-preview-route', () => { terminal: 'term-1', pathText: 'result.json', cwd: '/tmp/run', + nativeChatTab: 'tab-1', + nativeChatSession: 'session-1', line: '12', column: '3' } diff --git a/mobile/src/files/mobile-file-preview-route.ts b/mobile/src/files/mobile-file-preview-route.ts index 1b277de7faa..f0e7dfbbf49 100644 --- a/mobile/src/files/mobile-file-preview-route.ts +++ b/mobile/src/files/mobile-file-preview-route.ts @@ -10,6 +10,8 @@ export type MobileFilePreviewRouteParams = { terminal?: string pathText?: string cwd?: string + nativeChatTab?: string + nativeChatSession?: string line?: string column?: string name?: string @@ -35,6 +37,8 @@ type RawPreviewRouteParams = { terminal?: MobileFilePreviewParamValue pathText?: MobileFilePreviewParamValue cwd?: MobileFilePreviewParamValue + nativeChatTab?: MobileFilePreviewParamValue + nativeChatSession?: MobileFilePreviewParamValue line?: MobileFilePreviewParamValue column?: MobileFilePreviewParamValue name?: MobileFilePreviewParamValue @@ -76,6 +80,8 @@ export function normalizeMobileFilePreviewRouteParams( terminal: optionalSingleParam(params.terminal), pathText: optionalSingleParam(params.pathText), cwd: optionalSingleParam(params.cwd), + nativeChatTab: optionalSingleParam(params.nativeChatTab), + nativeChatSession: optionalSingleParam(params.nativeChatSession), line: optionalSingleParam(params.line), column: optionalSingleParam(params.column), name: optionalSingleParam(params.name), diff --git a/mobile/src/files/mobile-file-preview-source.test.ts b/mobile/src/files/mobile-file-preview-source.test.ts index b5fec782cfc..9c326fd0278 100644 --- a/mobile/src/files/mobile-file-preview-source.test.ts +++ b/mobile/src/files/mobile-file-preview-source.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { sourceKeyForPreview } from './mobile-file-preview-source' +import { previewSourceFromRoute, sourceKeyForPreview } from './mobile-file-preview-source' describe('mobile-file-preview-source', () => { it('uses structured preview keys so colons in paths cannot collide', () => { @@ -25,4 +25,21 @@ describe('mobile-file-preview-source', () => { sourceKeyForPreview({ source: 'worktree', worktreeId: 'wt:1', relativePath: 'a:b.ts' }) ).toBe(JSON.stringify(['worktree', 'wt:1', 'a:b.ts'])) }) + + it('makes native-chat artifact previews read-only', () => { + expect( + previewSourceFromRoute({ + hostId: 'host-1', + worktreeId: 'wt-1', + source: 'terminalArtifact', + absolutePath: '/tmp/result.html', + grantId: 'grant-1', + nativeChatTab: 'tab-1', + nativeChatSession: 'session-1' + }) + ).toMatchObject({ + nativeChatContext: { tabId: 'tab-1', sessionId: 'session-1' }, + readOnly: true + }) + }) }) diff --git a/mobile/src/files/mobile-file-preview-source.ts b/mobile/src/files/mobile-file-preview-source.ts index b1b23757a6e..2c1f01631e6 100644 --- a/mobile/src/files/mobile-file-preview-source.ts +++ b/mobile/src/files/mobile-file-preview-source.ts @@ -15,7 +15,16 @@ export function previewSourceFromRoute( grantId: params.grantId, ...(params.terminal ? { terminalHandle: params.terminal } : {}), ...(params.pathText ? { pathText: params.pathText } : {}), - ...(params.cwd ? { cwd: params.cwd } : {}) + ...(params.cwd ? { cwd: params.cwd } : {}), + ...(params.nativeChatTab && params.nativeChatSession + ? { + nativeChatContext: { + tabId: params.nativeChatTab, + sessionId: params.nativeChatSession + }, + readOnly: true as const + } + : {}) } } if (!params.relativePath) { @@ -28,12 +37,12 @@ export function sourceKeyForPreview(source: MobileFilePreviewSource | null): str if (!source) { return null } - return source.source === 'terminalArtifact' - ? JSON.stringify([ - 'terminal', - source.worktreeId, - source.absolutePath, - source.terminalHandle ?? '' - ]) - : JSON.stringify(['worktree', source.worktreeId, source.relativePath]) + if (source.source !== 'terminalArtifact') { + return JSON.stringify(['worktree', source.worktreeId, source.relativePath]) + } + const key = ['terminal', source.worktreeId, source.absolutePath, source.terminalHandle ?? ''] + if (source.nativeChatContext) { + key.push(source.nativeChatContext.tabId, source.nativeChatContext.sessionId) + } + return JSON.stringify(key) } diff --git a/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts b/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts index a8864119be4..cbe5ffdebd8 100644 --- a/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts +++ b/mobile/src/files/mobile-terminal-artifact-grant-refresh.ts @@ -1,3 +1,4 @@ +import type { RuntimeNativeChatFileContext } from '../../../src/shared/runtime-types' import type { RpcClient } from '../transport/rpc-client' import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types' import { isTerminalArtifactGrantError } from './terminal-artifact-grant-error' @@ -12,6 +13,8 @@ export type MobileTerminalArtifactPreviewSource = { terminalHandle?: string pathText?: string cwd?: string + nativeChatContext?: RuntimeNativeChatFileContext + readOnly?: true } export type TerminalArtifactRetryOptions = { @@ -32,7 +35,8 @@ export async function refreshTerminalArtifactSourceAfterGrantFailure( worktree: `id:${source.worktreeId}`, pathText: source.pathText ?? source.absolutePath, ...(source.cwd ? { cwd: source.cwd } : {}), - ...(source.terminalHandle ? { terminal: source.terminalHandle } : {}) + ...(source.terminalHandle ? { terminal: source.terminalHandle } : {}), + ...(source.nativeChatContext ? { nativeChatContext: source.nativeChatContext } : {}) }) if (!refreshed.ok) { return null @@ -51,7 +55,9 @@ export async function refreshTerminalArtifactSourceAfterGrantFailure( grantId: result.openTarget.grantId, ...(source.terminalHandle ? { terminalHandle: source.terminalHandle } : {}), ...(source.pathText ? { pathText: source.pathText } : {}), - ...(source.cwd ? { cwd: source.cwd } : {}) + ...(source.cwd ? { cwd: source.cwd } : {}), + ...(source.nativeChatContext ? { nativeChatContext: source.nativeChatContext } : {}), + ...(source.readOnly || result.openTarget.readOnly === true ? { readOnly: true as const } : {}) } } @@ -68,7 +74,7 @@ function isTerminalArtifactGrantFailure( function isTerminalArtifactResolution(result: unknown): result is { exists: true isDirectory: false - openTarget: { kind: 'absolute-file'; absolutePath: string; grantId: string } + openTarget: { kind: 'absolute-file'; absolutePath: string; grantId: string; readOnly?: true } } { if (!result || typeof result !== 'object') { return false diff --git a/mobile/src/hooks/use-active-worktree-scroll.ts b/mobile/src/hooks/use-active-worktree-scroll.ts index 7600f3ceafe..ff0441c85a8 100644 --- a/mobile/src/hooks/use-active-worktree-scroll.ts +++ b/mobile/src/hooks/use-active-worktree-scroll.ts @@ -37,7 +37,7 @@ export function useActiveWorktreeScroll( (worktreeId: string): boolean => { for (let sectionIndex = 0; sectionIndex < sections.length; sectionIndex++) { const itemIndex = sections[sectionIndex].data.findIndex((w) => w.worktreeId === worktreeId) - if (itemIndex >= 0) { + if (itemIndex !== -1) { sectionListRef.current?.scrollToLocation({ sectionIndex, itemIndex, diff --git a/mobile/src/session/ai-vault-resume-launch.test.ts b/mobile/src/session/ai-vault-resume-launch.test.ts index 9efc0e50f1a..3e9af99191c 100644 --- a/mobile/src/session/ai-vault-resume-launch.test.ts +++ b/mobile/src/session/ai-vault-resume-launch.test.ts @@ -226,6 +226,13 @@ describe('resumeAiVaultSessionInTerminal', () => { it('creates a fresh terminal and sends the command with Enter', async () => { const sendRequest = vi .fn() + .mockResolvedValueOnce({ + ok: true, + result: { + runtimeId: 'runtime', + capabilities: ['terminal.attribution-removed.v1'] + } + }) .mockResolvedValueOnce({ ok: true, result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'pty-1', title: 'Terminal' } } @@ -249,13 +256,20 @@ describe('resumeAiVaultSessionInTerminal', () => { navigation: 'caller' }) ).resolves.toMatchObject({ id: 'tab-1', terminal: 'pty-1' }) + expect(sendRequest).toHaveBeenNthCalledWith(1, 'status.get', undefined, { + timeoutMs: 30_000, + budgetSpansConnect: true + }) expect(sendRequest).toHaveBeenNthCalledWith( - 1, + 2, 'session.tabs.createTerminal', { worktree: 'id:worktree-1', - env: { ANTHROPIC_BASE_URL: 'http://localhost:3000' }, - envToDelete: ['CODEX_HOME', 'ORCA_CODEX_HOME'], + env: { + ANTHROPIC_BASE_URL: 'http://localhost:3000', + ORCA_ATTRIBUTION_BYPASS: '1' + }, + envToDelete: ['CODEX_HOME', 'ORCA_CODEX_HOME', 'ORCA_ENABLE_GIT_ATTRIBUTION'], launchConfig: { agentCommand: 'claude', agentArgs: '', @@ -269,10 +283,14 @@ describe('resumeAiVaultSessionInTerminal', () => { }, // Why: a socket drop mid-resume must reject within the request timeout // instead of parking on the reconnect waiter with the spinner pinned. - { timeoutMs: RESUME_RPC_TIMEOUT_MS } + { + timeoutMs: RESUME_RPC_TIMEOUT_MS, + budgetSpansConnect: true, + expectedRuntimeId: 'runtime' + } ) expect(sendRequest).toHaveBeenNthCalledWith( - 2, + 3, 'terminal.send', { terminal: 'pty-1', @@ -284,17 +302,35 @@ describe('resumeAiVaultSessionInTerminal', () => { }) it('throws when terminal creation fails', async () => { - const sendRequest = vi.fn().mockResolvedValueOnce({ - ok: false, - error: { message: 'no terminal' } - }) + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { + runtimeId: 'runtime', + capabilities: ['terminal.attribution-removed.v1'] + } + }) + .mockResolvedValueOnce({ + ok: false, + error: { message: 'no terminal' } + }) await expect( resumeAiVaultSessionInTerminal({ sendRequest }, 'worktree-1', { command: 'command' }) ).rejects.toThrow('no terminal') }) it('throws when the created terminal response is malformed', async () => { - const sendRequest = vi.fn().mockResolvedValueOnce({ ok: true, result: { tab: { id: 'x' } } }) + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { + runtimeId: 'runtime', + capabilities: ['terminal.attribution-removed.v1'] + } + }) + .mockResolvedValueOnce({ ok: true, result: { tab: { id: 'x' } } }) await expect( resumeAiVaultSessionInTerminal({ sendRequest }, 'worktree-1', { command: 'command' }) ).rejects.toThrow('Created terminal response was invalid') @@ -303,6 +339,13 @@ describe('resumeAiVaultSessionInTerminal', () => { it('throws when terminal send fails or is locked', async () => { const failedSend = vi .fn() + .mockResolvedValueOnce({ + ok: true, + result: { + runtimeId: 'runtime', + capabilities: ['terminal.attribution-removed.v1'] + } + }) .mockResolvedValueOnce({ ok: true, result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'pty-1' } } @@ -316,6 +359,13 @@ describe('resumeAiVaultSessionInTerminal', () => { const lockedSend = vi .fn() + .mockResolvedValueOnce({ + ok: true, + result: { + runtimeId: 'runtime', + capabilities: ['terminal.attribution-removed.v1'] + } + }) .mockResolvedValueOnce({ ok: true, result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'pty-1' } } @@ -327,6 +377,17 @@ describe('resumeAiVaultSessionInTerminal', () => { }) ).rejects.toThrow('Terminal input is locked') }) + + it('refuses an old host before creating a resume terminal', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ ok: true, result: { appVersion: '1.4.89' } }) + + await expect( + resumeAiVaultSessionInTerminal({ sendRequest }, 'worktree-1', { command: 'command' }) + ).rejects.toThrow('Update the host and try again') + expect(sendRequest).toHaveBeenCalledTimes(1) + }) }) describe('createMobileAiVaultResumeMutationRegistry', () => { diff --git a/mobile/src/session/ai-vault-resume-launch.ts b/mobile/src/session/ai-vault-resume-launch.ts index aa8c1bf98a6..6975b6f355d 100644 --- a/mobile/src/session/ai-vault-resume-launch.ts +++ b/mobile/src/session/ai-vault-resume-launch.ts @@ -16,6 +16,10 @@ import { normalizeAiVaultResumeFilePath } from '../../../src/shared/ai-vault-res import type { TuiAgent } from '../../../src/shared/types' import { parseWslUncPath } from '../../../src/shared/wsl-paths' import { resolveWindowsShellStartupFamily } from '../../../src/shared/windows-terminal-shell' +import { + addLegacyTerminalAttributionDisableRequest, + withLegacyTerminalAttributionDisabledEnv +} from '../../../src/shared/legacy-terminal-attribution-env' import type { RpcClient } from '../transport/rpc-client' import { readMobileReviewCreatedTerminal, @@ -23,6 +27,7 @@ import { type MobileReviewTerminalTab } from './mobile-diff-review-rpc' import type { MobileAiVaultResumeTargetStatus } from '../agent-history/agent-history-resume-target' +import { assertMobileTerminalAttributionDisableSupported } from './mobile-terminal-attribution-compat' const NODE_PLATFORMS = new Set([ 'aix', @@ -169,12 +174,13 @@ export async function resumeAiVaultSessionInTerminal( worktreeId: string, launch: MobileAiVaultResumeLaunch & { clientMutationId?: string } ): Promise { + const authority = await assertMobileTerminalAttributionDisableSupported(client) const created = await client.sendRequest( 'session.tabs.createTerminal', { worktree: `id:${worktreeId}`, - ...(launch.env ? { env: launch.env } : {}), - ...(launch.envToDelete ? { envToDelete: launch.envToDelete } : {}), + env: withLegacyTerminalAttributionDisabledEnv(launch.env), + envToDelete: addLegacyTerminalAttributionDisableRequest(launch.envToDelete), ...(launch.launchConfig ? { launchConfig: launch.launchConfig } : {}), ...(launch.launchAgent ? { launchAgent: launch.launchAgent } : {}), ...(launch.clientMutationId ? { clientMutationId: launch.clientMutationId } : {}), @@ -182,7 +188,11 @@ export async function resumeAiVaultSessionInTerminal( select: true, navigation: 'caller' }, - { timeoutMs: RESUME_RPC_TIMEOUT_MS } + { + timeoutMs: RESUME_RPC_TIMEOUT_MS, + budgetSpansConnect: true, + expectedRuntimeId: authority.runtimeId + } ) if (!created.ok) { throw new Error(created.error?.message || 'Failed to create terminal') diff --git a/mobile/src/session/ai-vault-resume-preparation.test.ts b/mobile/src/session/ai-vault-resume-preparation.test.ts index a0eed5515c6..3e64a06a0f8 100644 --- a/mobile/src/session/ai-vault-resume-preparation.test.ts +++ b/mobile/src/session/ai-vault-resume-preparation.test.ts @@ -53,6 +53,14 @@ describe('prepareMobileAiVaultSessionResume', () => { const sendRequest = vi .fn() .mockResolvedValueOnce({ ok: false, error }) + .mockResolvedValueOnce({ + ok: true, + result: { + runtimeId: 'runtime-1', + appVersion: '1.4.90', + capabilities: ['terminal.attribution-removed.v1'] + } + }) .mockResolvedValueOnce({ ok: true, result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'pty-1', title: 'Terminal' } } @@ -64,9 +72,12 @@ describe('prepareMobileAiVaultSessionResume', () => { await resumeAiVaultSessionInTerminal({ sendRequest }, 'worktree-1', launch) expect(prepared).toBe(legacy) - expect(sendRequest.mock.calls[1]?.[1]).not.toHaveProperty('envToDelete') + expect(sendRequest.mock.calls[2]?.[1]).toMatchObject({ + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'] + }) expect(sendRequest).toHaveBeenNthCalledWith( - 3, + 4, 'terminal.send', { terminal: 'pty-1', diff --git a/mobile/src/session/mobile-diff-review-screen-model.ts b/mobile/src/session/mobile-diff-review-screen-model.ts index 3dcaed35716..f8f1ceedf99 100644 --- a/mobile/src/session/mobile-diff-review-screen-model.ts +++ b/mobile/src/session/mobile-diff-review-screen-model.ts @@ -100,7 +100,7 @@ export function nextReviewIndexAfterMarkReviewed({ const wrappedIndex = filteredQueue.findIndex( (item) => item.key !== currentItemKey && !item.isReviewed ) - const targetIndex = nextIndex >= 0 ? nextIndex : wrappedIndex >= 0 ? wrappedIndex : null + const targetIndex = nextIndex !== -1 ? nextIndex : wrappedIndex !== -1 ? wrappedIndex : null if (targetIndex === null) { return null } diff --git a/mobile/src/session/mobile-file-tap-open.ts b/mobile/src/session/mobile-file-tap-open.ts index 627d9a5ff39..13c306af649 100644 --- a/mobile/src/session/mobile-file-tap-open.ts +++ b/mobile/src/session/mobile-file-tap-open.ts @@ -1,5 +1,6 @@ import type { RuntimeFileOpenResult, + RuntimeNativeChatFileContext, RuntimeTerminalPathResolution } from '../../../src/shared/runtime-types' import { filesystemPathToFileUri } from '../../../src/shared/file-uri-path' @@ -22,6 +23,7 @@ export type OpenMobileFileTapOptions = { terminalHandle?: string | null pathText: string cwd?: string | null + nativeChatContext?: RuntimeNativeChatFileContext | null line: number | null column: number | null pushPreviewRoute: (href: ReturnType) => void @@ -80,7 +82,8 @@ async function openMobileFileTapAsync( ...(options.terminalHandle && options.terminalHandle.trim().length > 0 ? { terminal: options.terminalHandle } : {}), - ...(options.cwd && options.cwd.trim().length > 0 ? { cwd: options.cwd } : {}) + ...(options.cwd && options.cwd.trim().length > 0 ? { cwd: options.cwd } : {}), + ...(options.nativeChatContext ? { nativeChatContext: options.nativeChatContext } : {}) }, { timeoutMs: 10_000 } ) @@ -116,6 +119,12 @@ async function openMobileFileTapAsync( ...(options.terminalHandle && options.terminalHandle.trim().length > 0 ? { terminal: options.terminalHandle } : {}), + ...(options.nativeChatContext + ? { + nativeChatTab: options.nativeChatContext.tabId, + nativeChatSession: options.nativeChatContext.sessionId + } + : {}), name: displayNameFromPath(resolved.openTarget.absolutePath), ...(options.line !== null ? { line: String(options.line) } : {}), ...(options.column !== null ? { column: String(options.column) } : {}), diff --git a/mobile/src/session/mobile-native-chat-draft-reconcile.test.ts b/mobile/src/session/mobile-native-chat-draft-reconcile.test.ts index 4c0cee804c1..b7453e7a67d 100644 --- a/mobile/src/session/mobile-native-chat-draft-reconcile.test.ts +++ b/mobile/src/session/mobile-native-chat-draft-reconcile.test.ts @@ -2,8 +2,10 @@ import { describe, expect, it } from 'vitest' import type { NativeChatMessage } from '../../../src/shared/native-chat-types' import { findLandedImagePreviewEchoes, + findLandedUnconfirmedSends, migrateImagePreviewMessageIds, - type PendingImagePreviewEcho + type PendingImagePreviewEcho, + type UnconfirmedSend } from './mobile-native-chat-draft-reconcile' function userText(id: string, text: string): NativeChatMessage { @@ -21,6 +23,67 @@ function pending(id: string, images: string[], expectedOccurrence = 1): PendingI } describe('mobile native chat image preview reconciliation', () => { + it('reconciles a trailing-marker echo and hands its preview to that echo', () => { + const messages = [ + userText('source', '[Image: source: /tmp/a.png]'), + userText('prompt', 'look at this[Image #1]') + ] + const preview = { + ...pending('pending', ['file:///a.jpg']), + text: 'look at this' + } + const unconfirmed: UnconfirmedSend = { + draftKey: 'draft', + pendingKey: 'pending-key', + text: 'look at this', + normalizedText: 'look at this', + baselineTailMessageId: null, + deadline: null + } + + expect(findLandedUnconfirmedSends(messages, [unconfirmed])).toEqual([unconfirmed]) + expect(findLandedImagePreviewEchoes(messages, [preview])).toEqual([ + { pendingId: 'pending', messageId: 'prompt', images: ['file:///a.jpg'] } + ]) + }) + + it('reconciles a middle-marker echo without changing its rendered whitespace', () => { + const messages = [ + userText('source', '[Image: source: /tmp/a.png]'), + userText('prompt', 'look [Image #1] here') + ] + const preview = { ...pending('pending', ['file:///a.jpg']), text: 'look here' } + const unconfirmed: UnconfirmedSend = { + draftKey: 'draft', + pendingKey: 'pending-key', + text: 'look here', + normalizedText: 'look here', + baselineTailMessageId: null, + deadline: null + } + + expect(findLandedUnconfirmedSends(messages, [unconfirmed])).toEqual([unconfirmed]) + expect(findLandedImagePreviewEchoes(messages, [preview])).toEqual([ + { pendingId: 'pending', messageId: 'prompt', images: ['file:///a.jpg'] } + ]) + }) + + it('reconciles multiple transcript text blocks with desktop separators', () => { + const prompt: NativeChatMessage = { + ...userText('prompt', 'unused'), + blocks: [ + { type: 'text', text: 'look' }, + { type: 'image-ref', path: '/tmp/a.png' }, + { type: 'text', text: '[Image #1] here' } + ] + } + const preview = { ...pending('pending', ['file:///a.jpg']), text: 'look here' } + + expect(findLandedImagePreviewEchoes([prompt], [preview])).toEqual([ + { pendingId: 'pending', messageId: 'prompt', images: ['file:///a.jpg'] } + ]) + }) + it('keeps separate adjacent image-only sends independently reconcilable', () => { const landed = findLandedImagePreviewEchoes( [ @@ -69,4 +132,36 @@ describe('mobile native chat image preview reconciliation', () => { [sessionKey]: { prompt: ['file:///a.jpg'] } }) }) + + it('moves an early standalone preview to a trailing-marker prompt id', () => { + const sessionKey = 'host\0worktree\0tab\0session' + const previous = { [sessionKey]: { source: ['file:///a.jpg'] } } + const messages = [ + userText('source', '[Image: source: /tmp/a.png]'), + userText('prompt', 'look[Image #1]') + ] + + expect(migrateImagePreviewMessageIds(previous, sessionKey, messages)).toEqual({ + [sessionKey]: { prompt: ['file:///a.jpg'] } + }) + }) + + it('moves a preview when the prompt marker is in a later text block', () => { + const sessionKey = 'host\0worktree\0tab\0session' + const previous = { [sessionKey]: { source: ['file:///a.jpg'] } } + const prompt: NativeChatMessage = { + ...userText('prompt', 'unused'), + blocks: [ + { type: 'text', text: 'look' }, + { type: 'text', text: '[Image #1] here' } + ] + } + + expect( + migrateImagePreviewMessageIds(previous, sessionKey, [ + userText('source', '[Image: source: /tmp/a.png]'), + prompt + ]) + ).toEqual({ [sessionKey]: { prompt: ['file:///a.jpg'] } }) + }) }) diff --git a/mobile/src/session/mobile-native-chat-draft-reconcile.ts b/mobile/src/session/mobile-native-chat-draft-reconcile.ts index 360fd22587b..a68fe5bcf32 100644 --- a/mobile/src/session/mobile-native-chat-draft-reconcile.ts +++ b/mobile/src/session/mobile-native-chat-draft-reconcile.ts @@ -1,9 +1,12 @@ import { isImageRefBlock, type NativeChatMessage } from '../../../src/shared/native-chat-types' import { + hasImagePromptMarker, isImageSourceUserTurn, normalizeImageTranscriptMessages, - stripImagePromptMarker + normalizeNativeChatUserText, + normalizedNativeChatUserMessageText } from './mobile-native-chat-image-transcript-markers' +export { normalizeNativeChatUserText as normalizeReconcileText } from './mobile-native-chat-image-transcript-markers' /** An ack-lost ('unknown' outcome) send held until its transcript echo lands or * the deadline surfaces the uncertainty. */ @@ -17,17 +20,7 @@ export type UnconfirmedSend = { } export function normalizedUserText(message: NativeChatMessage): string | null { - if (message.role !== 'user') { - return null - } - const text = message.blocks - .filter((block) => block.type === 'text') - .map((block) => (block.type === 'text' ? block.text : '')) - .join('') - // Claude echoes a captioned image send as `[Image #1] caption` — the sent - // text must still match its echo, so strip the marker before comparing. - const stripped = stripImagePromptMarker(text).trim() - return stripped || null + return normalizedNativeChatUserMessageText(message) } export function countUserTextOccurrences( @@ -87,7 +80,7 @@ export function mergeLandedImagePreviewEchoes( const entries = Object.entries(previous[sessionKey] ?? {}) for (const preview of landed) { const existingIndex = entries.findIndex(([messageId]) => messageId === preview.messageId) - if (existingIndex >= 0) { + if (existingIndex !== -1) { entries.splice(existingIndex, 1) } entries.push([preview.messageId, preview.images]) @@ -117,17 +110,13 @@ function imagePreviewReplacementMessageId( nextIndex++ } const prompt = messages[nextIndex] - const firstText = prompt?.blocks.find((block) => block.type === 'text') - return prompt?.role === 'user' && - prompt.source === source.source && - firstText?.type === 'text' && - stripImagePromptMarker(firstText.text) !== firstText.text + return prompt?.role === 'user' && prompt.source === source.source && hasImagePromptMarker(prompt) ? prompt.id : null } /** Moves previews forward when a progressive source-only transcript frame later - * folds into the marker-prefixed prompt with a different authoritative id. */ + * folds into the marker-bearing prompt with a different authoritative id. */ export function migrateImagePreviewMessageIds( previous: Record>, sessionKey: string, @@ -171,7 +160,7 @@ export function findLandedImagePreviewEchoes( if (!entry.images?.length) { continue } - const targetText = entry.text.trim() + const targetText = normalizeNativeChatUserText(entry.text) const candidates = normalized.filter((message) => { if (message.role !== 'user') { return false diff --git a/mobile/src/session/mobile-native-chat-image-transcript-markers.ts b/mobile/src/session/mobile-native-chat-image-transcript-markers.ts index 2c1ecc291ff..3c3998349ee 100644 --- a/mobile/src/session/mobile-native-chat-image-transcript-markers.ts +++ b/mobile/src/session/mobile-native-chat-image-transcript-markers.ts @@ -1,21 +1,13 @@ // Single-sources the marker logic (pure functions over shared types): // Claude records an attached image as `[Image: source: /path]` (+ `[Image #N]` -// prefix on the caption turn), and both render and echo reconciliation must +// on the caption turn), and both render and echo reconciliation must // agree with desktop on how those marker turns are interpreted. export { imageSourcePathFromText, + hasImagePromptMarker, + isImageSourceUserTurn, normalizeImageTranscriptMessages, + normalizeNativeChatUserText, + normalizedNativeChatUserMessageText, stripImagePromptMarker } from '../../../src/shared/native-chat-image-transcript-markers' -import { imageSourcePathFromText } from '../../../src/shared/native-chat-image-transcript-markers' -import { isTextBlock, type NativeChatMessage } from '../../../src/shared/native-chat-types' - -/** A raw (un-normalized) transcript user turn that is an image-source marker — - * the echo shape of an image riding along on a send. */ -export function isImageSourceUserTurn(message: NativeChatMessage): boolean { - if (message.role !== 'user' || message.blocks.length !== 1) { - return false - } - const block = message.blocks[0] - return block !== undefined && isTextBlock(block) && imageSourcePathFromText(block.text) !== null -} diff --git a/mobile/src/session/mobile-native-chat-open-file.test.ts b/mobile/src/session/mobile-native-chat-open-file.test.ts index d44530e5cd0..bef222721ac 100644 --- a/mobile/src/session/mobile-native-chat-open-file.test.ts +++ b/mobile/src/session/mobile-native-chat-open-file.test.ts @@ -65,6 +65,54 @@ describe('openMobileNativeChatFileTap', () => { ) }) + it('carries the native-chat session identity into resolution and grant refresh', async () => { + const sendRequest = vi.fn(async () => + ok({ + worktree: 'wt-1', + relativePath: null, + absolutePath: '/Users/ada/orca-plans/result.html', + exists: true, + isDirectory: false, + openTarget: { + kind: 'absolute-file', + provider: 'local', + absolutePath: '/Users/ada/orca-plans/result.html', + grantId: 'grant-1', + readOnly: true + } + }) + ) + const options = baseOptions({ sendRequest }) + + openMobileNativeChatFileTap({ + ...options, + pathText: '~/orca-plans/result.html', + nativeChatContext: { tabId: 'tab-1', sessionId: 'session-1' } + }) + await Promise.resolve() + + expect(sendRequest).toHaveBeenCalledWith( + 'files.resolveTerminalPath', + { + worktree: 'id:wt-1', + pathText: '~/orca-plans/result.html', + crossWorkspace: true, + nativeChatContext: { tabId: 'tab-1', sessionId: 'session-1' } + }, + { timeoutMs: 10_000 } + ) + expect(options.pushPreviewRoute).toHaveBeenCalledWith({ + pathname: '/h/[hostId]/files/preview/[worktreeId]', + params: expect.objectContaining({ + source: 'terminalArtifact', + absolutePath: '/Users/ada/orca-plans/result.html', + grantId: 'grant-1', + nativeChatTab: 'tab-1', + nativeChatSession: 'session-1' + }) + }) + }) + it('parses a :line:col citation and opens the mobile preview route', async () => { const sendRequest = vi.fn(async () => worktreeFileResolution('src/app.ts')) const options = baseOptions({ sendRequest }) diff --git a/mobile/src/session/mobile-native-chat-render-data.test.ts b/mobile/src/session/mobile-native-chat-render-data.test.ts index c67257ec24d..1a1811f808d 100644 --- a/mobile/src/session/mobile-native-chat-render-data.test.ts +++ b/mobile/src/session/mobile-native-chat-render-data.test.ts @@ -92,8 +92,8 @@ describe('buildMobileNativeChatTransientData', () => { }) it('folds transcript image marker turns into image-ref blocks (desktop parity)', () => { - // Claude records an attached image as `[Image: source: /path]` + an - // `[Image #1] `-prefixed caption turn; the fold must merge them into one + // Claude records an attached image as `[Image: source: /path]` plus a + // caption turn carrying `[Image #1]`; the fold must merge them into one // user turn with an image-ref block instead of showing raw marker text. const data = build( [ @@ -111,6 +111,20 @@ describe('buildMobileNativeChatTransientData', () => { ]) }) + it('folds a trailing-marker image echo into one user bubble', () => { + const data = build( + [user('u1', '[Image: source: /tmp/a.png]'), user('u2', 'look at this[Image #1]')], + null, + [] + ) + + expect(data).toHaveLength(1) + expect(data[0]?.blocks).toEqual([ + { type: 'image-ref', path: '/tmp/a.png' }, + { type: 'text', text: 'look at this' } + ]) + }) + it('renders a lone image marker turn (no caption) as an image-ref block', () => { const data = build([user('u1', '[Image: source: /tmp/a.png]')], null, []) expect(data[0]?.blocks).toEqual([{ type: 'image-ref', path: '/tmp/a.png' }]) diff --git a/mobile/src/session/mobile-native-chat-terminal-stream.test.ts b/mobile/src/session/mobile-native-chat-terminal-stream.test.ts index df860efc6b1..99c4c47cbcd 100644 --- a/mobile/src/session/mobile-native-chat-terminal-stream.test.ts +++ b/mobile/src/session/mobile-native-chat-terminal-stream.test.ts @@ -12,6 +12,7 @@ const base = { activeTabType: 'terminal', streamActive: true, streamCovered: false, + streamIsLeaseOnly: false, webViewReady: true } @@ -93,8 +94,40 @@ describe('mobile native-chat terminal stream lifecycle', () => { ).toBe('rearm') }) + it('resumes an uncovered handle still holding a lease-only stream', () => { + // Leaving a chat tab for a terminal tab subscribes the incoming handle before the + // route learns chat is gone, so the terminal streams nothing but its input lease. + expect(resolveMobileNativeChatTerminalStreamAction({ ...base, streamIsLeaseOnly: true })).toBe( + 'resume' + ) + // Same wait the other resume paths take — never init a WebView that cannot receive it. + expect( + resolveMobileNativeChatTerminalStreamAction({ + ...base, + streamIsLeaseOnly: true, + webViewReady: false + }) + ).toBe('none') + }) + + it('leaves a lease-only stream alone while chat still covers it (#10681)', () => { + // Lease-only is the correct shape under chat; trading it for output here would + // drop the input floor the composer depends on. + expect( + resolveMobileNativeChatTerminalStreamAction({ + ...base, + showNativeChat: true, + streamCovered: true, + streamIsLeaseOnly: true + }) + ).toBe('none') + }) + it('does nothing for non-terminal tabs, missing handles, or settled states', () => { - expect(resolveMobileNativeChatTerminalStreamAction(base)).toBe('none') + // A full stream on an uncovered handle is the one genuinely settled shape. + expect(resolveMobileNativeChatTerminalStreamAction({ ...base, streamIsLeaseOnly: false })).toBe( + 'none' + ) expect( resolveMobileNativeChatTerminalStreamAction({ ...base, diff --git a/mobile/src/session/mobile-native-chat-terminal-stream.ts b/mobile/src/session/mobile-native-chat-terminal-stream.ts index b9b58448113..9d2727f2c30 100644 --- a/mobile/src/session/mobile-native-chat-terminal-stream.ts +++ b/mobile/src/session/mobile-native-chat-terminal-stream.ts @@ -8,6 +8,10 @@ export function resolveMobileNativeChatTerminalStreamAction(args: { activeTabType: string | null streamActive: boolean streamCovered: boolean + /** The active stream was opened as an input lease, so the host sends `subscribed` + * and nothing else — no scrollback, no data. Distinguishes a stream that renders + * from one that only holds the input floor. */ + streamIsLeaseOnly: boolean webViewReady: boolean }): MobileNativeChatTerminalStreamAction { if (!args.activeHandle || args.activeTabType !== 'terminal') { @@ -22,7 +26,13 @@ export function resolveMobileNativeChatTerminalStreamAction(args: { // the composer locked forever — nothing else re-subscribes a covered handle. return args.streamActive ? 'none' : 'rearm' } - return (args.streamCovered || !args.streamActive) && args.webViewReady ? 'resume' : 'none' + // Why `streamIsLeaseOnly`: switching from a chat tab to a terminal tab subscribes the + // incoming handle before the route learns chat is gone, so it lands a lease-only stream + // on an uncovered handle. Without this input that is indistinguishable from a healthy + // stream and the terminal renders blank until restart. + return (args.streamCovered || args.streamIsLeaseOnly || !args.streamActive) && args.webViewReady + ? 'resume' + : 'none' } export function isTerminalCoveredByNativeChat( diff --git a/mobile/src/session/mobile-terminal-attribution-compat.test.ts b/mobile/src/session/mobile-terminal-attribution-compat.test.ts new file mode 100644 index 00000000000..9f0ebf873bd --- /dev/null +++ b/mobile/src/session/mobile-terminal-attribution-compat.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it, vi } from 'vitest' +import { MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE } from '../../../src/shared/legacy-terminal-attribution-env' +import { assertMobileTerminalAttributionDisableSupported } from './mobile-terminal-attribution-compat' + +function status(result: unknown) { + return { + id: 'status', + ok: true as const, + result: { runtimeId: 'runtime', ...(result as object) }, + _meta: { runtimeId: 'runtime' } + } +} + +describe('mobile terminal attribution compatibility', () => { + it('refuses hosts before terminal creation environment forwarding', async () => { + const sendRequest = vi.fn().mockResolvedValue( + status({ + capabilities: [ + 'runtime.status.compat.v1', + 'runtime.environments.v1', + 'mobile.tasks.v1', + 'workspace-run-context.v1' + ] + }) + ) + + await expect(assertMobileTerminalAttributionDisableSupported({ sendRequest })).rejects.toThrow( + MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE + ) + expect(sendRequest).toHaveBeenCalledWith('status.get', undefined, { + timeoutMs: 30_000, + budgetSpansConnect: true + }) + }) + + it('rejects historical hosts without explicit removal capability', async () => { + const sendRequest = vi.fn().mockResolvedValue(status({ appVersion: '1.4.90' })) + + await expect(assertMobileTerminalAttributionDisableSupported({ sendRequest })).rejects.toThrow( + MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE + ) + }) + + it('accepts capability-proven current development hosts', async () => { + const sendRequest = vi + .fn() + .mockResolvedValue( + status({ appVersion: '0.0.0-dev', capabilities: ['terminal.attribution-removed.v1'] }) + ) + + await expect(assertMobileTerminalAttributionDisableSupported({ sendRequest })).resolves.toEqual( + { runtimeId: 'runtime' } + ) + }) + + it('fails closed when host status cannot be verified', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + id: 'status', + ok: false, + error: { code: 'offline', message: 'Host is offline' }, + _meta: { runtimeId: 'runtime' } + }) + + await expect(assertMobileTerminalAttributionDisableSupported({ sendRequest })).rejects.toThrow( + 'Host is offline' + ) + }) + + it('fails closed with an actionable error for malformed host status', async () => { + const sendRequest = vi.fn().mockResolvedValue( + status({ + appVersion: 1.49, + capabilities: 'terminal.attribution-removed.v1' + }) + ) + + await expect(assertMobileTerminalAttributionDisableSupported({ sendRequest })).rejects.toThrow( + 'Update the host and try again' + ) + }) +}) diff --git a/mobile/src/session/mobile-terminal-attribution-compat.ts b/mobile/src/session/mobile-terminal-attribution-compat.ts new file mode 100644 index 00000000000..ceb2d3f694e --- /dev/null +++ b/mobile/src/session/mobile-terminal-attribution-compat.ts @@ -0,0 +1,34 @@ +import { + hostSupportsSessionTabTerminalCreateAttributionDisable, + MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE +} from '../../../src/shared/legacy-terminal-attribution-env' +import type { RpcClient } from '../transport/rpc-client' + +export const MOBILE_TERMINAL_CREATE_RPC_TIMEOUT_MS = 30_000 +export const MOBILE_TERMINAL_CREATE_RPC_OPTIONS = { + timeoutMs: MOBILE_TERMINAL_CREATE_RPC_TIMEOUT_MS, + budgetSpansConnect: true +} as const + +export type MobileTerminalAttributionAuthority = Readonly<{ runtimeId: string }> + +export async function assertMobileTerminalAttributionDisableSupported( + client: Pick +): Promise { + const response = await client.sendRequest( + 'status.get', + undefined, + MOBILE_TERMINAL_CREATE_RPC_OPTIONS + ) + if (!response.ok) { + throw new Error(response.error?.message || 'Unable to verify the workspace host version.') + } + if (!hostSupportsSessionTabTerminalCreateAttributionDisable(response.result)) { + throw new Error(MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE) + } + const runtimeId = Reflect.get(response.result as object, 'runtimeId') + if (typeof runtimeId !== 'string' || !runtimeId) { + throw new Error(MOBILE_TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE) + } + return Object.freeze({ runtimeId }) +} diff --git a/mobile/src/session/pr-ai-triage-launch.test.ts b/mobile/src/session/pr-ai-triage-launch.test.ts index c2273c9046e..fe9271f5e4d 100644 --- a/mobile/src/session/pr-ai-triage-launch.test.ts +++ b/mobile/src/session/pr-ai-triage-launch.test.ts @@ -12,6 +12,10 @@ function failure(message: string): RpcResponse { const createdTerminal = success({ tab: { type: 'terminal', id: 't1', terminal: 'term-1' } }) const sendAccepted = success({ send: { accepted: true } }) +const safeHost = success({ + runtimeId: 'r', + capabilities: ['terminal.attribution-removed.v1'] +}) function clientReturning(...responses: RpcResponse[]) { const sendRequest = vi.fn(async () => responses[sendRequest.mock.calls.length - 1]) @@ -20,16 +24,27 @@ function clientReturning(...responses: RpcResponse[]) { describe('createTerminalAndSendPrompt', () => { it('creates a terminal then sends the prompt with enter', async () => { - const client = clientReturning(createdTerminal, sendAccepted) + const client = clientReturning(safeHost, createdTerminal, sendAccepted) await createTerminalAndSendPrompt(client, 'wt-1', 'do the thing') - expect(client.sendRequest).toHaveBeenNthCalledWith(1, 'session.tabs.createTerminal', { - worktree: 'id:wt-1', - activate: false, - select: true, - navigation: 'caller' + expect(client.sendRequest).toHaveBeenNthCalledWith(1, 'status.get', undefined, { + timeoutMs: 30_000, + budgetSpansConnect: true }) - expect(client.sendRequest).toHaveBeenNthCalledWith(2, 'terminal.send', { + expect(client.sendRequest).toHaveBeenNthCalledWith( + 2, + 'session.tabs.createTerminal', + { + worktree: 'id:wt-1', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + activate: false, + select: true, + navigation: 'caller' + }, + { timeoutMs: 30_000, budgetSpansConnect: true, expectedRuntimeId: 'r' } + ) + expect(client.sendRequest).toHaveBeenNthCalledWith(3, 'terminal.send', { terminal: 'term-1', text: 'do the thing', enter: true @@ -37,28 +52,41 @@ describe('createTerminalAndSendPrompt', () => { }) it('throws and skips terminal.send when createTerminal fails', async () => { - const client = clientReturning(failure('boom')) + const client = clientReturning(safeHost, failure('boom')) await expect(createTerminalAndSendPrompt(client, 'wt-1', 'p')).rejects.toThrow('boom') - expect(client.sendRequest).toHaveBeenCalledTimes(1) + expect(client.sendRequest).toHaveBeenCalledTimes(2) }) it('throws when the created-terminal response is malformed', async () => { - const client = clientReturning(success({ tab: { type: 'terminal' } })) + const client = clientReturning(safeHost, success({ tab: { type: 'terminal' } })) await expect(createTerminalAndSendPrompt(client, 'wt-1', 'p')).rejects.toThrow( 'Created terminal response was invalid' ) - expect(client.sendRequest).toHaveBeenCalledTimes(1) + expect(client.sendRequest).toHaveBeenCalledTimes(2) }) it('throws when terminal.send returns a failure', async () => { - const client = clientReturning(createdTerminal, failure('send failed')) + const client = clientReturning(safeHost, createdTerminal, failure('send failed')) await expect(createTerminalAndSendPrompt(client, 'wt-1', 'p')).rejects.toThrow('send failed') }) it('throws when terminal input is locked', async () => { - const client = clientReturning(createdTerminal, success({ send: { accepted: false } })) + const client = clientReturning( + safeHost, + createdTerminal, + success({ send: { accepted: false } }) + ) await expect(createTerminalAndSendPrompt(client, 'wt-1', 'p')).rejects.toThrow( 'Terminal input is locked' ) }) + + it('refuses an old host before terminal creation', async () => { + const client = clientReturning(success({ appVersion: '1.4.89' })) + + await expect(createTerminalAndSendPrompt(client, 'wt-1', 'p')).rejects.toThrow( + 'Update the host and try again' + ) + expect(client.sendRequest).toHaveBeenCalledTimes(1) + }) }) diff --git a/mobile/src/session/pr-ai-triage-launch.ts b/mobile/src/session/pr-ai-triage-launch.ts index 6d6c0bbc8b2..1f764be1789 100644 --- a/mobile/src/session/pr-ai-triage-launch.ts +++ b/mobile/src/session/pr-ai-triage-launch.ts @@ -3,6 +3,14 @@ import { readMobileReviewCreatedTerminal, readMobileReviewTerminalSendAccepted } from './mobile-diff-review-rpc' +import { + addLegacyTerminalAttributionDisableRequest, + withLegacyTerminalAttributionDisabledEnv +} from '../../../src/shared/legacy-terminal-attribution-env' +import { + assertMobileTerminalAttributionDisableSupported, + MOBILE_TERMINAL_CREATE_RPC_OPTIONS +} from './mobile-terminal-attribution-compat' // Pure launch path for the PR triage actions ("Fix checks with AI" / "Resolve // conflicts with AI"). Reuses the same two RPCs the diff-review send flow uses — @@ -15,12 +23,19 @@ export async function createTerminalAndSendPrompt( worktreeId: string, prompt: string ): Promise { - const created = await client.sendRequest('session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - activate: false, - select: true, - navigation: 'caller' - }) + const authority = await assertMobileTerminalAttributionDisableSupported(client) + const created = await client.sendRequest( + 'session.tabs.createTerminal', + { + worktree: `id:${worktreeId}`, + env: withLegacyTerminalAttributionDisabledEnv(undefined), + envToDelete: addLegacyTerminalAttributionDisableRequest(undefined), + activate: false, + select: true, + navigation: 'caller' + }, + { ...MOBILE_TERMINAL_CREATE_RPC_OPTIONS, expectedRuntimeId: authority.runtimeId } + ) if (!created.ok) { throw new Error(created.error?.message || 'Failed to create terminal') } diff --git a/mobile/src/session/use-mobile-diff-review-send-actions.test.ts b/mobile/src/session/use-mobile-diff-review-send-actions.test.ts index 1d06190948c..9ae2749412b 100644 --- a/mobile/src/session/use-mobile-diff-review-send-actions.test.ts +++ b/mobile/src/session/use-mobile-diff-review-send-actions.test.ts @@ -163,6 +163,74 @@ describe('useMobileDiffReviewSendActions', () => { expect(setSendSheet).toHaveBeenCalledWith(null) }) + it('creates an unattributed terminal before sending review notes', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ + id: 'status', + ok: true, + result: { + runtimeId: 'runtime', + capabilities: ['terminal.attribution-removed.v1'] + }, + _meta: { runtimeId: 'runtime' } + }) + .mockResolvedValueOnce({ + id: 'create', + ok: true, + result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'terminal-1' } }, + _meta: { runtimeId: 'runtime' } + }) + .mockResolvedValueOnce(sendResponse(true)) + await mount({ sendRequest } as unknown as RpcClient) + + await act(async () => { + await actions?.createTerminalAndSend([COMMENT]) + }) + + expect(sendRequest).toHaveBeenNthCalledWith(1, 'status.get', undefined, { + timeoutMs: 30_000, + budgetSpansConnect: true + }) + expect(sendRequest).toHaveBeenNthCalledWith( + 2, + 'session.tabs.createTerminal', + { + worktree: 'id:wt-1', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + activate: false, + select: true, + navigation: 'caller' + }, + { timeoutMs: 30_000, budgetSpansConnect: true, expectedRuntimeId: 'runtime' } + ) + expect(sendRequest).toHaveBeenNthCalledWith( + 3, + 'terminal.send', + expect.objectContaining({ terminal: 'terminal-1', enter: true }) + ) + }) + + it('refuses to create review terminals on hosts that strip the bypass', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + id: 'status', + ok: true, + result: { appVersion: '1.4.89' }, + _meta: { runtimeId: 'runtime' } + }) + await mount({ sendRequest } as unknown as RpcClient) + + let error: unknown + await act(async () => { + error = await actions?.createTerminalAndSend([COMMENT]).catch((err) => err) + }) + + expect((error as Error).message).toContain('Update the host and try again') + expect(sendRequest).toHaveBeenCalledTimes(1) + expect(sendRequest).not.toHaveBeenCalledWith('terminal.send', expect.anything()) + }) + it('only heals the terminal that was marked', async () => { const sendRequest = vi.fn().mockResolvedValue(sendResponse(true)) await mount({ sendRequest } as unknown as RpcClient) diff --git a/mobile/src/session/use-mobile-diff-review-send-actions.ts b/mobile/src/session/use-mobile-diff-review-send-actions.ts index 0867a3884b3..266caaf6879 100644 --- a/mobile/src/session/use-mobile-diff-review-send-actions.ts +++ b/mobile/src/session/use-mobile-diff-review-send-actions.ts @@ -13,6 +13,14 @@ import { } from './mobile-diff-review-rpc' import { healMobileNativeChatStaleInput } from './mobile-native-chat-stale-input' import type { ReviewScreenState, SendSheetState } from './mobile-diff-review-screen-model' +import { + addLegacyTerminalAttributionDisableRequest, + withLegacyTerminalAttributionDisabledEnv +} from '../../../src/shared/legacy-terminal-attribution-env' +import { + assertMobileTerminalAttributionDisableSupported, + MOBILE_TERMINAL_CREATE_RPC_OPTIONS +} from './mobile-terminal-attribution-compat' type SendActionsInput = { client: RpcClient | null @@ -104,12 +112,19 @@ export function useMobileDiffReviewSendActions(input: SendActionsInput) { if (!client || connState !== 'connected') { throw new Error('Waiting for desktop...') } - const response = await client.sendRequest('session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - activate: false, - select: true, - navigation: 'caller' - }) + const authority = await assertMobileTerminalAttributionDisableSupported(client) + const response = await client.sendRequest( + 'session.tabs.createTerminal', + { + worktree: `id:${worktreeId}`, + env: withLegacyTerminalAttributionDisabledEnv(undefined), + envToDelete: addLegacyTerminalAttributionDisableRequest(undefined), + activate: false, + select: true, + navigation: 'caller' + }, + { ...MOBILE_TERMINAL_CREATE_RPC_OPTIONS, expectedRuntimeId: authority.runtimeId } + ) if (!response.ok) { throw new Error(response.error?.message || 'Failed to create terminal') } diff --git a/mobile/src/session/use-mobile-file-tap-handlers.test.ts b/mobile/src/session/use-mobile-file-tap-handlers.test.ts index 0cfa617f269..21f07562459 100644 --- a/mobile/src/session/use-mobile-file-tap-handlers.test.ts +++ b/mobile/src/session/use-mobile-file-tap-handlers.test.ts @@ -34,12 +34,13 @@ describe('useMobileFileTapHandlers', () => { hostId: 'host-1', worktreeId: 'wt-1', worktreeName: 'Orca', + nativeChatSessionId: 'session-1', activeHandleRef: { current: 'terminal-1' as string | null }, terminalCwdRef: { current: new Map([['terminal-1', '/repo/sub']]) }, openBrowser: vi.fn(), fetchSessionTabs: vi.fn(async () => {}), getSessionTabs: () => [], - getActiveSessionTabId: () => null, + getActiveSessionTabId: () => 'terminal-tab', getActiveSessionTabType: () => 'terminal', switchSessionTab: vi.fn(), scheduleDelayedAction: vi.fn(), @@ -131,7 +132,12 @@ describe('useMobileFileTapHandlers', () => { expect(sendRequest).toHaveBeenCalledWith( 'files.resolveTerminalPath', - { worktree: 'id:wt-1', pathText: 'mobile/src/x.ts', crossWorkspace: true }, + { + worktree: 'id:wt-1', + pathText: 'mobile/src/x.ts', + crossWorkspace: true, + nativeChatContext: { tabId: 'terminal-tab', sessionId: 'session-1' } + }, { timeoutMs: 10_000 } ) expect(options.reportChatTapFailure).toHaveBeenCalledWith("Couldn't open mobile/src/x.ts:12") diff --git a/mobile/src/session/use-mobile-file-tap-handlers.ts b/mobile/src/session/use-mobile-file-tap-handlers.ts index 276be5b566f..67995115f45 100644 --- a/mobile/src/session/use-mobile-file-tap-handlers.ts +++ b/mobile/src/session/use-mobile-file-tap-handlers.ts @@ -10,6 +10,7 @@ type MobileFileTapHandlerOptions = { hostId: string worktreeId: string worktreeName?: string + nativeChatSessionId: string | null activeHandleRef: MutableRefObject terminalCwdRef: MutableRefObject> openBrowser: (url: string) => void @@ -48,6 +49,7 @@ export function useMobileFileTapHandlers( getActiveSessionTabType, getSessionTabs, hostId, + nativeChatSessionId, openBrowser, scheduleDelayedAction, reportChatTapFailure, @@ -71,6 +73,7 @@ export function useMobileFileTapHandlers( getActiveSessionTabType, getSessionTabs, hostId, + nativeChatSessionId, openBrowser, scheduleDelayedAction, reportChatTapFailure, @@ -87,6 +90,7 @@ export function useMobileFileTapHandlers( getActiveSessionTabType, getSessionTabs, hostId, + nativeChatSessionId, openBrowser, router, scheduleDelayedAction, @@ -144,12 +148,18 @@ export function useMobileFileTapHandlers( return } const activationSeq = ++activationSeqRef.current + const nativeChatSessionId = current.nativeChatSessionId + const nativeChatTabId = current.getActiveSessionTabId() openMobileNativeChatFileTap({ client: current.client, hostId: current.hostId, worktreeId: current.worktreeId, worktreeName: current.worktreeName, pathText, + nativeChatContext: + nativeChatSessionId && nativeChatTabId + ? { tabId: nativeChatTabId, sessionId: nativeChatSessionId } + : null, pushPreviewRoute: (href) => routerRef.current.push(href), openBrowser: current.openBrowser, triggerOpenFeedback: triggerSelection, diff --git a/mobile/src/session/use-mobile-native-chat-drafts.test.ts b/mobile/src/session/use-mobile-native-chat-drafts.test.ts index db8e76696d0..daf451e53f9 100644 --- a/mobile/src/session/use-mobile-native-chat-drafts.test.ts +++ b/mobile/src/session/use-mobile-native-chat-drafts.test.ts @@ -316,8 +316,8 @@ describe('useMobileNativeChatDrafts', () => { }) expect(state?.pending).toHaveLength(1) - // Claude echoes a captioned image send as two turns: the source marker and - // the caption prefixed with `[Image #1] ` — the pending must still match. + // Claude echoes a captioned image send as a source turn plus a caption + // carrying `[Image #1]`; the pending must still match. await act(async () => renderer?.update( createElement(Harness, { @@ -334,6 +334,37 @@ describe('useMobileNativeChatDrafts', () => { expect(state?.imagePreviewsByMessageId).toEqual({ u2: ['file:///a.jpg'] }) }) + it('reconciles a captioned image echo with a trailing [Image #N] marker', async () => { + await mount('a') + await act(async () => + renderer?.update( + createElement(Harness, { tabId: 'a', messages: [assistantTextMessage('a1', 'hi')] }) + ) + ) + const origin = state?.captureSendOrigin('look at this') + act(() => { + if (origin) { + state?.acceptSend(origin, 'look at this', ['file:///a.jpg']) + } + }) + expect(state?.pending).toHaveLength(1) + + await act(async () => + renderer?.update( + createElement(Harness, { + tabId: 'a', + messages: [ + assistantTextMessage('a1', 'hi'), + userTextMessage('u1', '[Image: source: /tmp/a.png]'), + userTextMessage('u2', 'look at this[Image #1]') + ] + }) + ) + ) + expect(state?.pending).toEqual([]) + expect(state?.imagePreviewsByMessageId).toEqual({ u2: ['file:///a.jpg'] }) + }) + it('hands a marker-only image preview to the authoritative user bubble', async () => { await mount('a') const origin = state?.captureSendOrigin('') diff --git a/mobile/src/session/use-mobile-native-chat-drafts.ts b/mobile/src/session/use-mobile-native-chat-drafts.ts index 9da4dea6a9b..55fff5b42e3 100644 --- a/mobile/src/session/use-mobile-native-chat-drafts.ts +++ b/mobile/src/session/use-mobile-native-chat-drafts.ts @@ -7,6 +7,7 @@ import { findLandedUnconfirmedSends, mergeLandedImagePreviewEchoes, migrateImagePreviewMessageIds, + normalizeReconcileText, normalizedUserText, type UnconfirmedSend } from './mobile-native-chat-draft-reconcile' @@ -27,8 +28,7 @@ export type { MobileNativeChatPendingMessage, MobileNativeChatSendOrigin } const NO_PENDING_MESSAGES: MobileNativeChatPendingMessage[] = [] const NO_IMAGE_PREVIEWS: Record = {} -// How long an ack-lost send waits for its transcript echo before the UI surfaces -// that delivery remains unconfirmed. +// Ack-lost sends wait for a transcript echo before surfacing as unconfirmed. const UNCONFIRMED_SEND_DEADLINE_MS = 20_000 export function useMobileNativeChatDrafts(args: { @@ -132,14 +132,13 @@ export function useMobileNativeChatDrafts(args: { if (!draftKey) { return null } - const normalizedText = text.trim() - const currentMessages = messagesRef.current + const normalizedText = normalizeReconcileText(text) return { draftKey, pendingKey, normalizedText, - baselineOccurrences: countUserTextOccurrences(currentMessages, normalizedText), - baselineTailMessageId: currentMessages[currentMessages.length - 1]?.id ?? null + baselineOccurrences: countUserTextOccurrences(messagesRef.current, normalizedText), + baselineTailMessageId: messagesRef.current.at(-1)?.id ?? null } }, [draftKey, pendingKey] @@ -299,26 +298,19 @@ export function useMobileNativeChatDrafts(args: { landedCounts.set(text, (landedCounts.get(text) ?? 0) + 1) } } - // Why: compare against the count captured before send; historical equal - // turns cannot clear a new echo, while duplicates land one occurrence each. - // An image-only echo has no text to match, so it reconciles by ORDINAL - // against the count of new `[Image: source: …]` echo turns after its - // baseline tail — text echoes are excluded so an unrelated outstanding - // text send cannot clear it. Ordinal-vs-count stays stable when the effect - // re-runs on the shrunken list, and ignores paginated-in history. + // Image-only source-turn counts stay stable across reruns and ignore paginated history. const next = current.filter((item) => { if (landedImagePendingIds.has(item.id)) { return false } - // Image echoes hand their local URIs to the authoritative message above; - // never drop them through the text-only fallback before that handoff. + // Keep image echoes until their local preview reaches the authoritative message. if (item.images?.length) { return true } return item.text.trim() === '' ? countImageSourceTurnsAfter(messages, item.baselineTailMessageId) < item.expectedOccurrence - : (landedCounts.get(item.text.trim()) ?? 0) < item.expectedOccurrence + : (landedCounts.get(normalizeReconcileText(item.text)) ?? 0) < item.expectedOccurrence }) if (next.length === current.length) { return previous diff --git a/mobile/src/session/use-mobile-native-chat-terminal-stream.test.ts b/mobile/src/session/use-mobile-native-chat-terminal-stream.test.ts index ce282fcd5b1..47b3d982095 100644 --- a/mobile/src/session/use-mobile-native-chat-terminal-stream.test.ts +++ b/mobile/src/session/use-mobile-native-chat-terminal-stream.test.ts @@ -8,10 +8,25 @@ describe('useMobileNativeChatTerminalStream', () => { let harnessRenderCount = 0 const subscriptionsRef = { current: new Map void>() } const subscribingRef = { current: new Set() } + const leaseOnlyRef = { current: new Set() } const webReadyRef = { current: new Set(['terminal-1']) } const initializedRef = { current: new Set(['terminal-1']) } - const subscribe = vi.fn((handle: string) => subscriptionsRef.current.set(handle, () => {})) - const unsubscribe = vi.fn((handle: string) => subscriptionsRef.current.delete(handle)) + /** Mirrors the route's subscribe-time coverage guess, which is what decides whether + * the host opens a lease-only stream or a streaming one. */ + let subscribeOpensLeaseOnly = false + const registerSubscription = (handle: string): void => { + subscriptionsRef.current.set(handle, () => {}) + if (subscribeOpensLeaseOnly) { + leaseOnlyRef.current.add(handle) + } else { + leaseOnlyRef.current.delete(handle) + } + } + const subscribe = vi.fn(registerSubscription) + const unsubscribe = vi.fn((handle: string) => { + subscriptionsRef.current.delete(handle) + leaseOnlyRef.current.delete(handle) + }) const notifyWebReadyRef = { current: (_handle: string, _wasAlreadyReady: boolean): void => {} } const notifyListedHandlesRef = { current: (_liveHandles: ReadonlySet): void => {} } const hasTabsRecoveryNeedRef = { current: (): boolean => false } @@ -19,6 +34,8 @@ describe('useMobileNativeChatTerminalStream', () => { beforeEach(() => { subscriptionsRef.current = new Map([['terminal-1', () => {}]]) subscribingRef.current = new Set() + leaseOnlyRef.current = new Set() + subscribeOpensLeaseOnly = false webReadyRef.current = new Set(['terminal-1']) initializedRef.current = new Set(['terminal-1']) harnessRenderCount = 0 @@ -51,6 +68,7 @@ describe('useMobileNativeChatTerminalStream', () => { streamRevision, subscriptionsRef, subscribingRef, + leaseOnlyRef, webReadyRef, initializedRef, subscribe, @@ -107,6 +125,111 @@ describe('useMobileNativeChatTerminalStream', () => { expect(subscribe).toHaveBeenNthCalledWith(2, 'terminal-1') }) + /** What switchTab does synchronously on the tap, before the route re-renders: the + * coverage it reads still describes the chat tab being left, so the incoming + * terminal gets a lease-only subscribe — the shape that renders nothing. */ + function handOffToTerminalTwo(): void { + subscribeOpensLeaseOnly = true + subscribe('terminal-2') + subscribeOpensLeaseOnly = false + subscribe.mockClear() + unsubscribe.mockClear() + } + + it('trades a lease-only stream for output when a chat tab hands off to a terminal tab', async () => { + webReadyRef.current.add('terminal-2') + initializedRef.current.add('terminal-2') + await act(async () => { + renderer = create(createElement(Harness, { showNativeChat: true })) + }) + handOffToTerminalTwo() + + await act(async () => { + renderer?.update( + createElement(Harness, { showNativeChat: false, activeHandle: 'terminal-2' }) + ) + }) + + expect(unsubscribe).toHaveBeenCalledWith('terminal-2') + expect(subscribe).toHaveBeenCalledWith('terminal-2') + expect(leaseOnlyRef.current.has('terminal-2')).toBe(false) + // The lease-only stream carried no scrollback, so xterm is empty — a stale + // initialized mark would drop the replacement snapshot and keep the tab blank. + expect(initializedRef.current.has('terminal-2')).toBe(false) + }) + + it('settles once a lease-only stream has been replaced by a full one', async () => { + webReadyRef.current.add('terminal-2') + await act(async () => { + renderer = create(createElement(Harness, { showNativeChat: true })) + }) + handOffToTerminalTwo() + await act(async () => { + renderer?.update( + createElement(Harness, { showNativeChat: false, activeHandle: 'terminal-2' }) + ) + }) + subscribe.mockClear() + unsubscribe.mockClear() + + await act(async () => { + renderer?.update( + createElement(Harness, { + showNativeChat: false, + activeHandle: 'terminal-2', + streamRevision: 1 + }) + ) + }) + + // A stream that renders is settled — resubscribing it again would be a loop. + expect(subscribe).not.toHaveBeenCalled() + expect(unsubscribe).not.toHaveBeenCalled() + }) + + it('repairs a lease-only stream once its WebView reports ready', async () => { + await act(async () => { + renderer = create(createElement(Harness, { showNativeChat: true })) + }) + handOffToTerminalTwo() + await act(async () => { + renderer?.update( + createElement(Harness, { showNativeChat: false, activeHandle: 'terminal-2' }) + ) + }) + + // Cold WebView: the resume must wait, and the route's own web-ready path bails + // because the lease-only subscription already counts as live. + expect(subscribe).not.toHaveBeenCalled() + + await act(async () => { + webReadyRef.current.add('terminal-2') + notifyWebReadyRef.current('terminal-2', false) + }) + + expect(unsubscribe).toHaveBeenCalledWith('terminal-2') + expect(subscribe).toHaveBeenCalledWith('terminal-2') + }) + + it('keeps a covered lease-only stream instead of trading it for output (#10681)', async () => { + subscribeOpensLeaseOnly = true + await act(async () => { + renderer = create(createElement(Harness, { showNativeChat: true })) + }) + subscribe.mockClear() + unsubscribe.mockClear() + + await act(async () => { + renderer?.update(createElement(Harness, { showNativeChat: true, streamRevision: 1 })) + }) + + // Lease-only is the correct shape under chat; swapping it for output would drop + // the input floor the composer holds. + expect(subscribe).not.toHaveBeenCalled() + expect(unsubscribe).not.toHaveBeenCalled() + expect(leaseOnlyRef.current.has('terminal-1')).toBe(true) + }) + it('re-subscribes a covered stream torn down under chat (#10681)', async () => { await act(async () => { renderer = create(createElement(Harness, { showNativeChat: true })) @@ -174,9 +297,7 @@ describe('useMobileNativeChatTerminalStream', () => { expect(subscribe).toHaveBeenCalledTimes(5) } finally { - subscribe.mockImplementation((handle: string) => - subscriptionsRef.current.set(handle, () => {}) - ) + subscribe.mockImplementation(registerSubscription) } }) diff --git a/mobile/src/session/use-mobile-native-chat-terminal-stream.ts b/mobile/src/session/use-mobile-native-chat-terminal-stream.ts index 0f0a642a149..b5663b8dc8a 100644 --- a/mobile/src/session/use-mobile-native-chat-terminal-stream.ts +++ b/mobile/src/session/use-mobile-native-chat-terminal-stream.ts @@ -23,6 +23,8 @@ export function useMobileNativeChatTerminalStream(args: { streamRevision: number subscriptionsRef: MutableRefObject void>> subscribingRef: MutableRefObject> + /** Handles whose current subscribe went out as an input lease only. */ + leaseOnlyRef: MutableRefObject> webReadyRef: MutableRefObject> initializedRef: MutableRefObject> subscribe: (handle: string) => void @@ -55,13 +57,21 @@ export function useMobileNativeChatTerminalStream(args: { healthyStreamProofRef.current = null } }, []) - const notifyWebReady = useCallback((handle: string, wasAlreadyReady: boolean) => { - // Why: ordinary WebView startups must not rerender the large session route; - // only readiness that can release a native-chat lease needs reconciliation. - if (!wasAlreadyReady && coveredHandleRef.current === handle) { - setWebReadyRevision((revision) => revision + 1) - } - }, []) + const notifyWebReady = useCallback( + (handle: string, wasAlreadyReady: boolean) => { + // Why: ordinary WebView startups must not rerender the large session route; + // only readiness that can release a native-chat lease needs reconciliation. + // A lease-only stream counts: the route's own web-ready path bails on any live + // subscription, so nothing else would ever trade that lease for output. + if ( + !wasAlreadyReady && + (coveredHandleRef.current === handle || args.leaseOnlyRef.current.has(handle)) + ) { + setWebReadyRevision((revision) => revision + 1) + } + }, + [args.leaseOnlyRef] + ) const notifyListedHandles = useCallback( (liveHandles: ReadonlySet) => { // Why: the rearm budget bounds one teardown, not the handle's lifetime. A covered @@ -106,7 +116,7 @@ export function useMobileNativeChatTerminalStream(args: { (rearmAttemptsRef.current.get(handle) ?? 0) >= MAX_REARM_ATTEMPTS ) }, []) - useEffect(() => { + const reconcileStream = useCallback(() => { const handle = args.activeHandle if (coveredHandleRef.current && coveredHandleRef.current !== handle) { forgetRearmState(coveredHandleRef.current) @@ -115,12 +125,15 @@ export function useMobileNativeChatTerminalStream(args: { const streamActive = handle != null && (args.subscriptionsRef.current.has(handle) || args.subscribingRef.current.has(handle)) + const streamIsLeaseOnly = + streamActive && handle != null && args.leaseOnlyRef.current.has(handle) const action = resolveMobileNativeChatTerminalStreamAction({ showNativeChat: args.showNativeChat, activeHandle: handle, activeTabType: args.activeTabType, streamActive, streamCovered: coveredHandleRef.current === handle, + streamIsLeaseOnly, webViewReady: handle != null && args.webReadyRef.current.has(handle) }) const streamHolding = action === 'none' && streamActive && coveredHandleRef.current === handle @@ -181,7 +194,11 @@ export function useMobileNativeChatTerminalStream(args: { args.subscribe(handle) return } - if (coveredHandleRef.current === handle) { + if (coveredHandleRef.current === handle || streamIsLeaseOnly) { + // Why clear `initialized`: a lease-only stream delivered no scrollback, so xterm + // holds nothing — a stale mark would drop the replacement snapshot and the + // terminal would stay blank through the resubscribe. + args.initializedRef.current.delete(handle) args.unsubscribe(handle) coveredHandleRef.current = null } @@ -190,6 +207,7 @@ export function useMobileNativeChatTerminalStream(args: { args.activeHandle, args.activeTabType, args.initializedRef, + args.leaseOnlyRef, args.leaseReady, args.showNativeChat, args.streamRevision, @@ -203,6 +221,7 @@ export function useMobileNativeChatTerminalStream(args: { rearmBudgetRevision, webReadyRevision ]) + useEffect(() => reconcileStream(), [reconcileStream]) useEffect(() => cancelHealthyStreamProof, [cancelHealthyStreamProof]) // Why memoized: the session route keeps this object in callback dep arrays, and a // fresh literal per render would rebuild them on every keystroke. All three members diff --git a/mobile/src/source-control/mobile-create-pr-action.test.ts b/mobile/src/source-control/mobile-create-pr-action.test.ts index c665b034f7f..ec399b45913 100644 --- a/mobile/src/source-control/mobile-create-pr-action.test.ts +++ b/mobile/src/source-control/mobile-create-pr-action.test.ts @@ -1,8 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import type { HostedReviewCreationBlockedReason, - HostedReviewCreationEligibility, - HostedReviewProvider + HostedReviewCreationEligibility } from '../../../src/shared/hosted-review' import { buildMobileCreatePrAction, @@ -146,7 +145,7 @@ describe('buildMobileCreatePrAction', () => { it('keeps a disabled status row for providers without review creation', () => { const { descriptor } = action({ - eligibility: eligibility({ provider: 'bitbucket' as HostedReviewProvider }) + eligibility: eligibility({ provider: 'unsupported' }) }) expect(descriptor).toMatchObject({ @@ -211,7 +210,7 @@ describe('cold-mount layout stability (issue #8411)', () => { 'unsupported provider', { kind: 'ready', - eligibility: eligibility({ provider: 'bitbucket' as HostedReviewProvider }) + eligibility: eligibility({ provider: 'unsupported' }) } satisfies MobileCreatePrEligibilityState ], ['eligibility error', { kind: 'error' } satisfies MobileCreatePrEligibilityState] diff --git a/mobile/src/source-control/mobile-create-pr-action.ts b/mobile/src/source-control/mobile-create-pr-action.ts index fe75cc60a58..3268a1796c3 100644 --- a/mobile/src/source-control/mobile-create-pr-action.ts +++ b/mobile/src/source-control/mobile-create-pr-action.ts @@ -72,7 +72,7 @@ export function buildMobileCreatePrAction({ } // Why: mirror desktop's structural provider gate (supportsHostedReviewCreation) // instead of relying on the host always emitting a hidden blockedReason for - // non-creatable providers like bitbucket. + // non-creatable providers. if (!supportsHostedReviewCreation(eligibility.provider)) { return { visible: true, diff --git a/mobile/src/terminal/terminal-path-tap.ts b/mobile/src/terminal/terminal-path-tap.ts index ac2a8ea0ff3..8e7545a4cfb 100644 --- a/mobile/src/terminal/terminal-path-tap.ts +++ b/mobile/src/terminal/terminal-path-tap.ts @@ -3,11 +3,12 @@ // one path span containing the tapped column — mobile opens a tapped path, it // does not render hover links over the whole line. -export type TappedFilePath = { - pathText: string - line: number | null - column: number | null -} +import { + parseFileLinkLocation, + type ParsedFileLinkLocation +} from '../../../src/shared/file-link-location' + +export type TappedFilePath = ParsedFileLinkLocation // Separator-anchored path tokens (absolute, relative, ~/, drive-letter, UNC) OR // a bare filename with an extension (README.md, index.ts), optionally suffixed @@ -47,18 +48,13 @@ function trimBoundaryPunctuation( } export function parsePathWithOptionalLineColumn(value: string): TappedFilePath | null { - const match = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(value) - if (!match) { + const parsed = parseFileLinkLocation(value) + if (!parsed) { return null } - const pathText = match[1] + const { pathText, line, column } = parsed // Reject a directory-only token (trailing separator) for either slash style. - if (!pathText || pathText.endsWith('/') || pathText.endsWith('\\')) { - return null - } - const line = match[2] ? Number.parseInt(match[2], 10) : null - const column = match[3] ? Number.parseInt(match[3], 10) : null - if ((line !== null && line < 1) || (column !== null && column < 1)) { + if (pathText.endsWith('/') || pathText.endsWith('\\')) { return null } return { pathText, line, column } diff --git a/mobile/src/transport/host-store.ts b/mobile/src/transport/host-store.ts index 99421ffd192..c32ac44ac77 100644 --- a/mobile/src/transport/host-store.ts +++ b/mobile/src/transport/host-store.ts @@ -182,7 +182,7 @@ async function persistHost(host: HostProfile, requireExisting: boolean): Promise } } let next: StoredHostProfile[] - if (index >= 0) { + if (index !== -1) { updatedExistingHost = true // Why: an authoritative save is the safe point to collapse pre-existing duplicate rows to the preserved host id. next = hosts @@ -195,7 +195,7 @@ async function persistHost(host: HostProfile, requireExisting: boolean): Promise next = [...hosts.filter(({ id }) => !duplicateHostIds.has(id)), stored] } if (duplicateHostIds.size > 0) { - if (index < 0) { + if (index === -1) { // Why: process death between the early token write and metadata publication must leave cleanup discoverable. await recordHostCredentialCleanupIntent(stored.id) cleanupIntentRecordedBeforeMetadata = true @@ -304,7 +304,7 @@ export async function updateHostNameAndEndpoint( ): Promise { await mutateStoredHosts((hosts) => { const index = hosts.findIndex((host) => host.id === hostId) - if (index < 0) { + if (index === -1) { throw new Error('Host not found') } const next = hosts.slice() @@ -321,7 +321,7 @@ export async function updateLastConnected(hostId: string): Promise { try { await mutateStoredHosts((hosts) => { const index = hosts.findIndex((h) => h.id === hostId) - if (index < 0) { + if (index === -1) { return hosts } const next = hosts.slice() diff --git a/mobile/src/transport/mobile-relay-host-overlay-store.ts b/mobile/src/transport/mobile-relay-host-overlay-store.ts index 7f1519eb5c9..4960fbec3f0 100644 --- a/mobile/src/transport/mobile-relay-host-overlay-store.ts +++ b/mobile/src/transport/mobile-relay-host-overlay-store.ts @@ -80,7 +80,7 @@ export async function saveMobileRelayHostOverlay(overlay: MobileRelayHostOverlay const validated = MobileRelayHostOverlaySchema.parse(overlay) return mutateOverlays((overlays) => { const index = overlays.findIndex(({ hostId }) => hostId === validated.hostId) - if (index < 0) { + if (index === -1) { return [...overlays, validated] } const next = overlays.slice() diff --git a/mobile/src/transport/rpc-client.ts b/mobile/src/transport/rpc-client.ts index 9b0afe937f3..f316f8c2b76 100644 --- a/mobile/src/transport/rpc-client.ts +++ b/mobile/src/transport/rpc-client.ts @@ -54,6 +54,7 @@ type ConnectWaiter = { export type SendRequestOptions = { timeoutMs?: number + expectedRuntimeId?: string /** Spend `timeoutMs` across connect-wait AND the request instead of giving each * phase its own. Interactive chat writes need it: they run as sequential loops * under one shared budget, so a per-phase clock lets the composer sit `sending` @@ -1013,7 +1014,15 @@ export function connect( } }) - if (!sendEncrypted({ id, deviceToken, method, params })) { + if ( + !sendEncrypted({ + id, + deviceToken, + method, + params, + ...(options?.expectedRuntimeId ? { expectedRuntimeId: options.expectedRuntimeId } : {}) + }) + ) { pending.delete(id) clearTimeout(timeout) reject(new Error('Connection interrupted')) diff --git a/mobile/src/transport/rpc-response-shape.ts b/mobile/src/transport/rpc-response-shape.ts index 54903f5f3e1..61ecaf57362 100644 --- a/mobile/src/transport/rpc-response-shape.ts +++ b/mobile/src/transport/rpc-response-shape.ts @@ -13,7 +13,7 @@ export function isRpcResponse(value: unknown): value is RpcResponse { return false } if (response.ok === true) { - return Object.prototype.hasOwnProperty.call(response, 'result') + return Object.hasOwn(response, 'result') } return ( response.ok === false && diff --git a/mobile/src/transport/types.ts b/mobile/src/transport/types.ts index 9d96f0561ad..8fe2bdd78f9 100644 --- a/mobile/src/transport/types.ts +++ b/mobile/src/transport/types.ts @@ -18,6 +18,7 @@ export type RpcRequest = { deviceToken: string method: string params?: unknown + expectedRuntimeId?: string } export type RpcSuccess = { diff --git a/package.json b/package.json index a599fb6d3f8..6f7be4e6f4b 100644 --- a/package.json +++ b/package.json @@ -88,6 +88,8 @@ "test:e2e:multi-client-navigation": "node config/scripts/run-multi-client-navigation-e2e.mjs", "test:e2e:floating-mobile-emulator": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/floating-mobile-emulator-tab.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "test:e2e:terminal-rendering-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts tests/e2e/terminal-webgl-atlas-budget.spec.ts --grep @terminal-rendering-golden --config tests/playwright.config.ts --project electron-headless --workers=1", + "test:e2e:posix-profile-index-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-posix-fresh-startup.spec.ts tests/e2e/golden-posix-profile-index-fsync.spec.ts --grep @posix-profile-index-golden --config tests/playwright.config.ts --project electron-headless --workers=1", + "test:e2e:windows-fresh-startup-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-windows-fresh-startup.spec.ts --grep @windows-fresh-startup-golden --config tests/playwright.config.ts --project electron-headless --workers=1", "test:e2e:terminal-rendering-release-evidence": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts tests/e2e/terminal-long-table-scroll-restore.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=2", "test:e2e:terminal-perf": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/terminal-typing-latency.spec.ts tests/e2e/terminal-foreground-redraw-freeze.spec.ts tests/e2e/terminal-output-scheduler.spec.ts tests/e2e/terminal-hidden-tui-visual-restore.spec.ts tests/e2e/artificial-opencode-terminal-load.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=2", "test:e2e:terminal-perf:scale": "pnpm run ensure:electron-runtime && node config/scripts/run-terminal-scale-perf-e2e.mjs", @@ -98,6 +100,9 @@ "test:e2e:ssh-docker-perf": "node config/scripts/run-ssh-docker-perf-e2e.mjs", "test:e2e:ssh-docker-watcher-isolation": "node config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs", "test:e2e:ssh-docker-terminal-parking": "node config/scripts/run-ssh-docker-terminal-parking-e2e.mjs", + "test:e2e:ssh-docker-reconnect-pane-cardinality": "node config/scripts/run-ssh-docker-reconnect-pane-cardinality-e2e.mjs", + "test:e2e:ssh-docker-maxsessions-identity": "node config/scripts/run-ssh-docker-maxsessions-identity-e2e.mjs", + "test:e2e:ssh-docker-two-hosts-isolation": "node config/scripts/run-ssh-docker-two-hosts-isolation-e2e.mjs", "test:e2e:nested-runtime-ssh": "node config/scripts/run-nested-runtime-ssh-e2e.mjs", "test:e2e:source-control-scale": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/source-control-large-file-count.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "win-update-e2e": "node tests/tools/win-update-e2e/run.mjs", @@ -123,6 +128,7 @@ "bench:cold-park-resource": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs", "bench:compare": "node config/scripts/compare-benchmark-artifacts.mjs", "test:e2e:remote-bulk-open-freeze": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/remote-session-bulk-open-freeze-repro.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "test:e2e:daemon-session-liveness": "pnpm run ensure:electron-runtime && pnpm exec playwright test --config tests/playwright.daemon-liveness.local.config.ts", "test:e2e:ssh-docker-bulk-open-freeze": "node config/scripts/run-ssh-docker-bulk-open-freeze-e2e.mjs", "repro:live-remote-bulk-open-freeze": "node config/scripts/live-remote-bulk-open-freeze-repro.mjs", "repro:live-remote-realistic-freeze": "node config/scripts/live-remote-realistic-freeze-repro.mjs" @@ -218,7 +224,7 @@ "mermaid": "^11.16.1", "monaco-editor": "^0.55.1", "oxfmt": "^0.52.0", - "oxlint": "^1.75.0", + "oxlint": "^1.77.0", "oxlint-plugin-react-doctor": "0.9.1", "oxlint-tsgolint": "7.0.2001", "pdfjs-dist": "^6.2.108", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1872f9860e8..57885d16e25 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -294,8 +294,8 @@ importers: specifier: ^0.52.0 version: 0.52.0 oxlint: - specifier: ^1.75.0 - version: 1.75.0(oxlint-tsgolint@7.0.2001) + specifier: ^1.77.0 + version: 1.77.0(oxlint-tsgolint@7.0.2001) oxlint-plugin-react-doctor: specifier: 0.9.1 version: 0.9.1 @@ -1488,124 +1488,124 @@ packages: cpu: [x64] os: [win32] - '@oxlint/binding-android-arm-eabi@1.75.0': - resolution: {integrity: sha512-lutovtFzJqlRaqpZrCqSSGaHZzl9nIxxpjLzhSRLunN6dCLylj0uzlCyQGaQDIys7rrv8kVXiFO+R4Zpn0bX7g==} + '@oxlint/binding-android-arm-eabi@1.77.0': + resolution: {integrity: sha512-E06sKWS6PiI6HRxS1wyQg22HvApt01hI7fV+T3wUk3OSbaaP4a3hYGY/MIQDmASqCiRjBdpRQYkgMkqH82cWmQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] - '@oxlint/binding-android-arm64@1.75.0': - resolution: {integrity: sha512-hXI0hDgHkw4w5nfru72aG7y+2iQJmC4waH/KV6H/hbgA6yAP5jYNx0P9yug15Hs0tWl/+mda3Jjn/2gmDT48tw==} + '@oxlint/binding-android-arm64@1.77.0': + resolution: {integrity: sha512-NvsKz0KZxTp9cYWPLf+FXaSZwB3oO3peAjtukpOMBgse2vhQSoIIVqeO1yR0lEo/UcdZIDL18uq+kL0LzQ0ytA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@oxlint/binding-darwin-arm64@1.75.0': - resolution: {integrity: sha512-D91BWbK/dMYfCcrghspPIuKs2D9LF4Z/OabVSQjw1AO6PWxArD7teDA48bm0ySFqWDaPVqmQRl5GMWNglTXyrQ==} + '@oxlint/binding-darwin-arm64@1.77.0': + resolution: {integrity: sha512-bgjTn6nW4bQCFBvSvuHCpDD+sONvmpo4lGI4PxzMt1quBA+xYxhczk6RiCn3GZ9gY8uhaBbwhj9MdKGfu6T9DA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@oxlint/binding-darwin-x64@1.75.0': - resolution: {integrity: sha512-02mpwzf12BonZ6PT0TuQoomvEh2kVl2WGBIKWezCyToIS+rYkQZ6GXnARBAl9A4Ovm2V+Xe7M4KretyqmmcnJQ==} + '@oxlint/binding-darwin-x64@1.77.0': + resolution: {integrity: sha512-aotaIttH1R6j1Rwhx0M0htgeZyGtVQqYNTVEYMN/UcgHPquGA6kmk9OyuDc3a2GKUQBC+3C3GVQCcrRPMYqAFA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@oxlint/binding-freebsd-x64@1.75.0': - resolution: {integrity: sha512-qZJgLnDaBsiL5YESx2t/TZ8eXkL9fEkKoXEdzegROhlz9A0lgyGnZ0dAzJrh7LJAHQl2K9RdRueN2s/9N7+odg==} + '@oxlint/binding-freebsd-x64@1.77.0': + resolution: {integrity: sha512-nNx/wta7ksRAdYvq+l4AWjXkLxEXHALhENxjj2cYbQAIR4ybaA5L+hCbE63HOmft5czQ6ks+hb8vmEAnn7YGPg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@oxlint/binding-linux-arm-gnueabihf@1.75.0': - resolution: {integrity: sha512-7XlaWA5BJD3XpCfrEqjEe6Zseeb14S7QGa304XfwKignRaKQ+eIj775BQ7nIslggWickl4IsPUFqJ+/gAyNHVg==} + '@oxlint/binding-linux-arm-gnueabihf@1.77.0': + resolution: {integrity: sha512-tMLLjM7xXtzXisVCzkOTXNCy9bZVId2wteNwjohlFDR/jY6WagpEDA1c1wu4xRc20Hojaxj+V6DSR7gbKxijWA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxlint/binding-linux-arm-musleabihf@1.75.0': - resolution: {integrity: sha512-av6Tpv8yrcMMMOadOqENBhlsLRcGFXXwoQ0hzHhsmS9FJ4Wioy8we427GbcMe2XTxmL2e60T67H1Dyr3up+tAA==} + '@oxlint/binding-linux-arm-musleabihf@1.77.0': + resolution: {integrity: sha512-MiAFDFaqR0tmHTAyo0YDcZ5hyLREdYw/RQhc2R3cbT+8O3tB+zqPM2th9TTQ+Uo3jn/embS+DO+HyX9ztCPkOQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxlint/binding-linux-arm64-gnu@1.75.0': - resolution: {integrity: sha512-WcUhd8fHT5plrA14lANevl+hOl815mVI5t2hU21oFWrZKFXIVV/Sr4rWQV0NzSvzBupbMLNc5ErEA6Ehxh5jMg==} + '@oxlint/binding-linux-arm64-gnu@1.77.0': + resolution: {integrity: sha512-/xqQ3B16i1T4cyt/9Mn+4CpzhUXoBXp7kVpIwzOXNFLj5JmK1bIjsbSnX296Gg8A/o7oDtKWikFgBx0SLwztkw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-arm64-musl@1.75.0': - resolution: {integrity: sha512-UWzp5wRHFe/ESO3+eEaxXsTkYTGLYjnTsi/I5neEacXSItQ6WNleapfOAeA4x2b8nyhJ4uQxqvtv9pHv8kWJtQ==} + '@oxlint/binding-linux-arm64-musl@1.77.0': + resolution: {integrity: sha512-LSbwuRKiNCenPDcbARqAZ5RfBy7gmj7vOvfJRLeCDU3gFtSxWbhv/+VTlaUqzUhNj1gFLHB8h7ALnxa/Az6z6g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@oxlint/binding-linux-ppc64-gnu@1.75.0': - resolution: {integrity: sha512-XEVRwGMLKCUKrvhLAz4F6AIh8MJrQVdSZtAmPpRZt9tGPsUnamPOcl3dS/ZQzJnar/Ymgc//+xho0L60Emzuxg==} + '@oxlint/binding-linux-ppc64-gnu@1.77.0': + resolution: {integrity: sha512-QWdcH31mXEUe5Nq1s0CfCpceaKjIo9uZtwDjAuL681g1axf+5x8xrg/eXWaw//4NCxYZ4V4e5Hu5tvdR+pTBlg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-riscv64-gnu@1.75.0': - resolution: {integrity: sha512-mAG4DUXqfLC8cTjMD2kt3jDmVzFREYtDyeLNdLdsCcBc4Zbl2EMuiFektGBilQwkNjYnMvCqJs55U+Hyb+b+jw==} + '@oxlint/binding-linux-riscv64-gnu@1.77.0': + resolution: {integrity: sha512-GnOfYgJxbcElOiPZaDFDl406ONddwvOWk2jvAAAEjwAl4GofNoHF+/HHUIBYa6bFCArlcGPi0XjC4cU1pkgF/Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-riscv64-musl@1.75.0': - resolution: {integrity: sha512-95hrAvriAlI+pekSomTFIn0+bawMDlDwTNVmdjsFusTHyL2JWh7TWvRNG/Lkim72uN8OiCcO9wcaC6omLP5E3w==} + '@oxlint/binding-linux-riscv64-musl@1.77.0': + resolution: {integrity: sha512-AyEMTUCf0xY+hHF+IxqXFQIX0yQOIR8ykpY0lJNOw9xYqOzUX8dyZfRvlG0RfXwuQn2eonf/8NrMmDSZJjdqsA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [musl] - '@oxlint/binding-linux-s390x-gnu@1.75.0': - resolution: {integrity: sha512-4b6f2+FrtruAESrCqIKcrarzfrSx+wk2QNcp+RT91/Prc+pMQMAfyZ1rG1c3tFQNl8Bc616tx40uNXyxNBRPbQ==} + '@oxlint/binding-linux-s390x-gnu@1.77.0': + resolution: {integrity: sha512-sPLzEcNvxd/oyVQ5oZo92CiHkFkpBeRop13E/P3TPY+hZfXHKCOWKI70TE2RYwMKFJDc20EMjH16L7NZICtKTw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@oxlint/binding-linux-x64-gnu@1.75.0': - resolution: {integrity: sha512-nshAhrUvXFUWOvqQ2soIw7HFNWvpvEV4o0cYSqPtzLiPF5gKyYTDOOTJ6Rn8g8K/iGvPIrbDA4v8+5MvnjJrrg==} + '@oxlint/binding-linux-x64-gnu@1.77.0': + resolution: {integrity: sha512-1Oh2ssH2L7lwyvkdSqaMUfsGfwU2Wfvew+obBUYjRVqhpBcUpwnsPSEr1IzVi9XqkuY10geiLsNKecqaZC34Dw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-x64-musl@1.75.0': - resolution: {integrity: sha512-e4jNxLKnxLC6sYBQRxrI2pgIIxnmMtF8U/VwNYcjTT/CLS+spH624cYVnj07bTKwaEWT37/e025isOs6j/0xqA==} + '@oxlint/binding-linux-x64-musl@1.77.0': + resolution: {integrity: sha512-0j/2wRgNGO+Qj/M1uu/p57h/hFTTWWcfie0ufkbabeus2s5+/QqkCflnMOwLLN5m2GsNeWp4xdl4cPa4n7QCOQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@oxlint/binding-openharmony-arm64@1.75.0': - resolution: {integrity: sha512-hZ2lH+1qLf/DiEP9UWuQTK2JWj/BgvMB4jhIV4SmNU1wfEiYYX4TynQyAZXx0j9X4qRYizAL042SKaV+8ynh4w==} + '@oxlint/binding-openharmony-arm64@1.77.0': + resolution: {integrity: sha512-BJ/j54qS0usEnyDkLYURMj2iiD9h5Cyy+ppzeMSXBGRXaGRNWnj1Mw14NqWMR5E/PzdgB30OOCCzLzbRoduafw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@oxlint/binding-win32-arm64-msvc@1.75.0': - resolution: {integrity: sha512-Ilj6PNzGDS3bCU0MSJH7Msh0NhH+T/mRp2shwg+q+GHeVlPwP5LEboW96aW+3kVKFk6zYZy1Xi5pZkqZh6X8KQ==} + '@oxlint/binding-win32-arm64-msvc@1.77.0': + resolution: {integrity: sha512-Yh8w+g2Lpx7StrvtYkoz9JJvXjB9wxgFChFNb85nrXm/wj/XTwGWS1hve9+900HL7llrntYB3YP+y32E3tRqzA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@oxlint/binding-win32-ia32-msvc@1.75.0': - resolution: {integrity: sha512-QVit2nOEOiPhkmsrksPSkoGCdnZRNkspt8fwoYyP09te1VEbnSj4LAxua4rc8FKTmWkySVe05j8iz9GXYfF1AQ==} + '@oxlint/binding-win32-ia32-msvc@1.77.0': + resolution: {integrity: sha512-zja5b7+6a7UsRFgAQSrnax5vrzliEyNPLCjfXONu/vTWswaIVZGFajJZptaeRvPE4LghtFdAzVFlexTm7MVTGA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ia32] os: [win32] - '@oxlint/binding-win32-x64-msvc@1.75.0': - resolution: {integrity: sha512-DSxnNkBUAYARPwJtR12Ig3deWr8w0H997xP6jy33i+e0SyYJw8FKuz4+cZtpmPEhQmvlPJE3X/2vNxDmLkd/rA==} + '@oxlint/binding-win32-x64-msvc@1.77.0': + resolution: {integrity: sha512-+teyvPDZ2RjUvo+SuCqS/UhaJl1QtdW5fWT5NJTV61V5MIuIS90Db9LixmtEGvXixyttiK62P96MSu3UlpviBw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -5541,8 +5541,8 @@ packages: resolution: {integrity: sha512-KjK/XLcXr1DSyonKhsuFqJRiuKqcyG9j3LJ8nkOsrLzGvodBPqzHOKauy10asLMDI0sUpvb+1sxlzff3udZvfg==} hasBin: true - oxlint@1.75.0: - resolution: {integrity: sha512-m9WzjRcRYA/uqIZDa9tclrieoPJ/ln1QYTKdFx6NUOs8uY5DiHlIwRQoCrHT6OM6O3ww3l2skY5gO7G7ZphE7g==} + oxlint@1.77.0: + resolution: {integrity: sha512-qnGh8XJHaQ0dprrDXNQZgS0FgjI6v+V3+X8DwmaV++5Aamy6jGKfDdQ1TUvhUxtmKFAbEf4/WeO5QZX+5WSngg==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: @@ -7809,61 +7809,61 @@ snapshots: '@oxlint-tsgolint/win32-x64@7.0.2001': optional: true - '@oxlint/binding-android-arm-eabi@1.75.0': + '@oxlint/binding-android-arm-eabi@1.77.0': optional: true - '@oxlint/binding-android-arm64@1.75.0': + '@oxlint/binding-android-arm64@1.77.0': optional: true - '@oxlint/binding-darwin-arm64@1.75.0': + '@oxlint/binding-darwin-arm64@1.77.0': optional: true - '@oxlint/binding-darwin-x64@1.75.0': + '@oxlint/binding-darwin-x64@1.77.0': optional: true - '@oxlint/binding-freebsd-x64@1.75.0': + '@oxlint/binding-freebsd-x64@1.77.0': optional: true - '@oxlint/binding-linux-arm-gnueabihf@1.75.0': + '@oxlint/binding-linux-arm-gnueabihf@1.77.0': optional: true - '@oxlint/binding-linux-arm-musleabihf@1.75.0': + '@oxlint/binding-linux-arm-musleabihf@1.77.0': optional: true - '@oxlint/binding-linux-arm64-gnu@1.75.0': + '@oxlint/binding-linux-arm64-gnu@1.77.0': optional: true - '@oxlint/binding-linux-arm64-musl@1.75.0': + '@oxlint/binding-linux-arm64-musl@1.77.0': optional: true - '@oxlint/binding-linux-ppc64-gnu@1.75.0': + '@oxlint/binding-linux-ppc64-gnu@1.77.0': optional: true - '@oxlint/binding-linux-riscv64-gnu@1.75.0': + '@oxlint/binding-linux-riscv64-gnu@1.77.0': optional: true - '@oxlint/binding-linux-riscv64-musl@1.75.0': + '@oxlint/binding-linux-riscv64-musl@1.77.0': optional: true - '@oxlint/binding-linux-s390x-gnu@1.75.0': + '@oxlint/binding-linux-s390x-gnu@1.77.0': optional: true - '@oxlint/binding-linux-x64-gnu@1.75.0': + '@oxlint/binding-linux-x64-gnu@1.77.0': optional: true - '@oxlint/binding-linux-x64-musl@1.75.0': + '@oxlint/binding-linux-x64-musl@1.77.0': optional: true - '@oxlint/binding-openharmony-arm64@1.75.0': + '@oxlint/binding-openharmony-arm64@1.77.0': optional: true - '@oxlint/binding-win32-arm64-msvc@1.75.0': + '@oxlint/binding-win32-arm64-msvc@1.77.0': optional: true - '@oxlint/binding-win32-ia32-msvc@1.75.0': + '@oxlint/binding-win32-ia32-msvc@1.77.0': optional: true - '@oxlint/binding-win32-x64-msvc@1.75.0': + '@oxlint/binding-win32-x64-msvc@1.77.0': optional: true '@parcel/watcher-android-arm64@2.5.6': @@ -12174,27 +12174,27 @@ snapshots: '@oxlint-tsgolint/win32-arm64': 7.0.2001 '@oxlint-tsgolint/win32-x64': 7.0.2001 - oxlint@1.75.0(oxlint-tsgolint@7.0.2001): + oxlint@1.77.0(oxlint-tsgolint@7.0.2001): optionalDependencies: - '@oxlint/binding-android-arm-eabi': 1.75.0 - '@oxlint/binding-android-arm64': 1.75.0 - '@oxlint/binding-darwin-arm64': 1.75.0 - '@oxlint/binding-darwin-x64': 1.75.0 - '@oxlint/binding-freebsd-x64': 1.75.0 - '@oxlint/binding-linux-arm-gnueabihf': 1.75.0 - '@oxlint/binding-linux-arm-musleabihf': 1.75.0 - '@oxlint/binding-linux-arm64-gnu': 1.75.0 - '@oxlint/binding-linux-arm64-musl': 1.75.0 - '@oxlint/binding-linux-ppc64-gnu': 1.75.0 - '@oxlint/binding-linux-riscv64-gnu': 1.75.0 - '@oxlint/binding-linux-riscv64-musl': 1.75.0 - '@oxlint/binding-linux-s390x-gnu': 1.75.0 - '@oxlint/binding-linux-x64-gnu': 1.75.0 - '@oxlint/binding-linux-x64-musl': 1.75.0 - '@oxlint/binding-openharmony-arm64': 1.75.0 - '@oxlint/binding-win32-arm64-msvc': 1.75.0 - '@oxlint/binding-win32-ia32-msvc': 1.75.0 - '@oxlint/binding-win32-x64-msvc': 1.75.0 + '@oxlint/binding-android-arm-eabi': 1.77.0 + '@oxlint/binding-android-arm64': 1.77.0 + '@oxlint/binding-darwin-arm64': 1.77.0 + '@oxlint/binding-darwin-x64': 1.77.0 + '@oxlint/binding-freebsd-x64': 1.77.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.77.0 + '@oxlint/binding-linux-arm-musleabihf': 1.77.0 + '@oxlint/binding-linux-arm64-gnu': 1.77.0 + '@oxlint/binding-linux-arm64-musl': 1.77.0 + '@oxlint/binding-linux-ppc64-gnu': 1.77.0 + '@oxlint/binding-linux-riscv64-gnu': 1.77.0 + '@oxlint/binding-linux-riscv64-musl': 1.77.0 + '@oxlint/binding-linux-s390x-gnu': 1.77.0 + '@oxlint/binding-linux-x64-gnu': 1.77.0 + '@oxlint/binding-linux-x64-musl': 1.77.0 + '@oxlint/binding-openharmony-arm64': 1.77.0 + '@oxlint/binding-win32-arm64-msvc': 1.77.0 + '@oxlint/binding-win32-ia32-msvc': 1.77.0 + '@oxlint/binding-win32-x64-msvc': 1.77.0 oxlint-tsgolint: 7.0.2001 p-cancelable@2.1.1: {} diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index bc7b1cbbe3e..20b70a15b63 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -195,7 +195,7 @@ orca orchestration worker-start --task --worktree current --agent claud For a per-invocation Claude, Codex, or Cursor launch, pass an opaque provider model id with `--model`; add `--effort` only when that agent/model supports the level. These options apply only to fresh agent terminals, override general agent default arguments, and are reported under `launch.requested` and `launch.effective` in the receipt: ```bash -orca orchestration worker-start --task --worktree current --agent claude --model aws-bedrock-opus-5 --effort high --json +orca orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json ``` `--effort` requires `--model`, and neither option can combine with `--terminal`. A connected worker server must advertise launch-preference support before Orca forwards either option. diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 487c9152b89..e0a65fc876f 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -30,7 +30,7 @@ const ORCA_LINEAR_MARKDOWN = "---\nname: orca-linear\ndescription: >-\n Use Orc const ORCA_PER_WORKSPACE_ENV_MARKDOWN = "---\nname: orca-per-workspace-env\ndescription: >-\n Set up, review, debug, or validate Orca per-workspace environment recipes —\n on-demand, disposable runtimes (cloud sandboxes, VMs, or local) created fresh\n for each workspace. Covers first-time setup (provider prerequisites, the\n reusable base snapshot, the coding-agent auth snapshot, credentials, and\n state), not just the per-workspace lifecycle scripts. Use to stand up\n per-workspace environments, fix an `environmentRecipes` entry in `orca.yaml`, scaffold\n provider lifecycle scripts, or resolve an `orca vm recipe doctor` failure.\n---\n\n# Per-Workspace Environments\n\nHelp a user stand up and maintain a repo-owned per-workspace environment recipe end to end. Each\nworkspace gets its own on-demand, disposable runtime (a cloud sandbox, a VM, or a local one),\ncreated fresh and torn down after.\n\nOrca is a **thin wrapper**: you guide, detect, and scaffold; you never own the user's cloud account,\nbilling, images, or credentials.\n\n- **You DO:** sequence the setup, detect what's detectable (provider CLI present/logged-in? recipe\n present? `doctor` passing?), scaffold provider-templated scripts the user fills in, drive the slow\n snapshot/auth phases with the user, and always show the next action.\n- **You DO NOT:** create accounts, choose plans/regions, invent org/project/scope ids, store or print\n secrets, or run anything that spends money without an explicit user OK.\n\nFirst-time setup has **four phases before the per-workspace recipe runs** — easy to miss, so walk\nthem in order:\n\n1. **Prerequisites** — cloud account, provider CLI, scope/project, plan limits, git token (§2).\n2. **Base snapshot** — reusable image: tools + repo + headless build, snapshotted once (§3).\n3. **Agent-auth snapshot** — boot the base, run interactive device-auth, re-snapshot (§4).\n4. **State** — thread snapshot id / scope / project / port between phases via a state file (§6).\n\nThen the **per-workspace contract** (create/suspend/resume/destroy) runs fast (§8).\n\n**The one branch that shapes everything — connection mode:** **Orca-server** (`create` runs `orca serve`\nin the env and emits a `pairingCode`; §7c/§7f) vs **SSH** (`create` runs no server and emits a\n`connection.type:\"ssh\"` block Orca dials into; §7g/§7h). Settle this first — it changes the `create`\noutput shape and half the templates.\n\n**Quick-start (happy path):** interview the user (connection mode Orca-server vs SSH, provider, agent CLI,\ngit auth — §1.2) + read the provider's CLI docs → scaffold `scripts/orca-vm/` from §7 → run the\nbase-snapshot script, then the auth script (you invoke these by hand; not via `orca.yaml`) → wire\n`environmentRecipes` in `orca.yaml` → `orca vm recipe doctor --json` (free) → then the `--provision`\nself-test loop (§9) until it passes.\n\n---\n\n## 1. Setup workflow\n\nDrive these with the user. **[CHECKPOINT]** steps need explicit confirmation — they spend money, take\na long time, or need the user at the keyboard. Never create an Orca workspace or commit unless asked.\n\n1. **Inspect the repo** for an existing `environmentRecipes` entry, `scripts/orca-vm/`, a state file, or setup\n notes. If a working recipe exists, jump to Doctor (§9) instead of rebuilding.\n2. **Interview the user up front** — gather these choices and confirm them back before scaffolding\n anything. Don't pick for them (§11); don't guess.\n - **Connection mode:** how Orca attaches to the environment — an **Orca server** (the VM runs\n `orca serve` and Orca pairs over its pairing URL; worked example §7f) or **SSH** (Orca connects to\n the host over SSH; §7g). This decides the recipe's connection shape, so settle it first.\n - **Provider:** Vercel Sandbox, Fly, Modal, an existing SSH host, … For non-obvious providers, also\n ask scope/project/region and plan limits (§2). Then **read that provider's CLI/SDK docs** (or\n ` --help`) before scaffolding — you need its exact create/exec/snapshot/remove verbs.\n If a provider advertises `ssh`, verify whether it exposes a real dialable SSH target\n (host/port/user/key or proxy command) or only a provider-mediated interactive shell; Orca SSH mode\n needs the former.\n - **Coding-agent CLI + account:** which agent runs in the VM (`codex`, `claude`, …) and that the user\n has an account for it — it gets logged in during the Phase-3 auth snapshot (§4).\n - **Git auth:** the token source for cloning a private repo (`GH_TOKEN`/`GITHUB_TOKEN` or `gh auth\n token`; §5).\n3. **Check prerequisites (§2)** — detect the provider CLI + auth and confirm the items above are in\n place before any paid step.\n4. **Scaffold scripts + state file** from §7 (worked Vercel example: §7f; SSH host: §7g; Docker SSH:\n §7h; Windows: §7i), filling in the provider's real commands. Make them executable.\n5. **[CHECKPOINT] Build the base snapshot (§3)** — paid, slow.\n6. **[CHECKPOINT] Authenticate the agent (§4)** — interactive; the user follows a URL/code. **You cannot\n drive this step** — you run commands non-interactively, so there's no TTY for `docker exec -it` /\n `ssh -t` to prompt against. The **user** runs the Phase-3 login in their own terminal (or via the\n Claude Code harness bang-prefix — `! `, with the required space after `!`); you scaffold and drive\n the non-interactive phases around it. After kicking it off, **ask the user to report back once the login\n finishes** — you can't observe it completing, and you need that confirmation before resuming the\n non-interactive steps (base/auth commit, doctor, provision).\n7. **Wire the recipe** so `orca.yaml` points create/suspend/resume/destroy at the scripts (§8). The\n workspace composer reads `environmentRecipes` from the project's primary checkout of `orca.yaml`, **not** from\n a feature branch or worktree. So a recipe added only on a branch won't appear as a \"Run on\" option\n until that `orca.yaml` change is committed and merged to the project's primary branch. Tell the user\n this up front: `doctor`/`--provision` validate the scripts from the working copy on any branch, but\n creating a workspace from the recipe in the picker needs it on primary.\n8. **Dry-run doctor** — `orca vm recipe doctor --repo-path --json` (free, static; §9).\n Fix every failure before going live.\n9. **[CHECKPOINT] Live self-test** — get the user's OK once, then run\n `orca vm recipe doctor --provision --json` as a loop: it runs create → validates →\n destroys, and on failure returns a full transcript. Read it, fix the scripts, and re-run yourself until\n it passes (§9). Spends cloud money; the one approval covers the loop.\n10. **[CHECKPOINT] Optional workspace test** — only if asked: create a workspace via the picker, then\n verify sleep/wake/delete.\n\n---\n\n## 2. Phase 1 — Prerequisites\n\nThe user's responsibility; verify what's verifiable, ask for the rest, invent nothing. State which\nitems you verified vs. which the user asserted.\n\n- **Connection mode** (Orca server vs SSH) confirmed with the user — see §1 step 2; it shapes the recipe.\n- **Cloud account + plan** that allows sandboxes/VMs. Ask.\n- **Provider CLI installed + authenticated** — detect (`command -v `), check auth (e.g.\n `vercel whoami`). If missing, point at the provider's docs; don't log them in.\n- **Scope / project / region** the sandboxes live under. Ask; flows into every script via state.\n- **Plan / timeout / RAM caps.** Record them — e.g. Vercel Hobby caps sandbox timeout at **45m**,\n which limits both the base build and per-workspace runtime (see §10).\n- **Git token for private repos** (`GH_TOKEN`/`GITHUB_TOKEN`, or the provider's git auth; can fall back\n to `gh auth token`). See §5.\n- **Coding-agent CLI choice** (`codex`, `claude`…) and that the user has an account — it gets\n authenticated into the VM in Phase 3.\n\n---\n\n## 3. Phase 2 — Base snapshot (the reusable image)\n\nBuild **once**, snapshot, and every workspace boots from it in seconds instead of rebuilding.\nProvisioning + building takes a while (often ~20–30 min), so it runs behind a checkpoint. The script\nshape is §7a; key points:\n\n- Build the **headless Electron main only** (not the renderer) so it fits in plan RAM.\n- Use the VM image's package manager (`apt`/`dnf`/`apk`, per the base distro — not the provider brand).\n- Clone with the git token via `GIT_ASKPASS` (§5).\n- **Trap errors and remove the half-built sandbox** so a crash doesn't leave a paid resource running.\n- Snapshot the stopped sandbox, parse the snapshot id, and write it + scope/project/port/repo to state.\n\n---\n\n## 4. Phase 3 — Agent-auth snapshot (interactive)\n\nThe base snapshot has the agent CLI installed but **not logged in**, and per-workspace VMs are\nephemeral — so authenticate once and bake it into a second snapshot layer. Script shape is §7b:\n\n1. Boot a sandbox from the base `snapshotId` (from state).\n2. Run the agent's login **interactively** (`--interactive --tty`); the user completes the URL/code in\n their browser. On a **headless VM this must be the device-auth flow** (e.g. `codex login --device-auth`),\n **not** plain `codex login`: the default OAuth login starts a loopback callback server on a container\n port the host browser can't reach, so it hangs. Device-auth instead prints a URL + code the user opens\n on the **host**.\n3. Verify login; **refuse to snapshot an unauthenticated VM.** Prefer the status command's **exit code**\n (most agent CLIs exit non-zero when unauthenticated). If you grep instead, agent status often goes to\n **stderr** (e.g. `codex login status` prints \"Logged in using ChatGPT\" there), so **fold stderr first**\n (`... 2>&1 | grep …`) and match the agent's **exact success line** — never `grep -qi 'logged in'`, which\n also matches \"**not** logged in\" and would commit an unauthenticated image.\n4. Re-snapshot, parse the new id, and overwrite `snapshotId` in state to the authenticated image\n (recording `authSourceSnapshotId`). Remove the auth sandbox.\n\n**You can't drive step 2 yourself** (you run commands non-interactively — no TTY). The **user** runs it in\ntheir own terminal, or via the Claude Code harness bang-prefix (`! `, with the required space after\n`!`). You scaffold/boot the sandbox and run steps 3–4, but **you cannot observe the interactive login\nfinishing** — so **ask the user to tell you when it's done** before you verify and re-snapshot.\n\nIf the agent's credentials are short-lived, warn that the snapshot may need periodic re-auth (§10).\n\nFor disposable runtimes, do **not** treat a host agent config directory (for example `~/.codex`) as the\nauth snapshot by bind-mounting or copying it wholesale. Agent homes often contain sqlite state, hook\napproval state, caches, logs, and host-specific env/config. Instead, authenticate/configure the agent\ninside the disposable runtime and snapshot/commit that runtime layer.\n\n---\n\n## 5. Credentials\n\n- **Never** commit secrets or put them in `userData`, recipe JSON, comments, docs, or the state file.\n- **Git token:** read from env (`GH_TOKEN`/`GITHUB_TOKEN`), falling back to `gh auth token`. Pass to the\n VM only via the provider's ephemeral `--env`. Inside the VM, use a `GIT_ASKPASS` helper with\n `x-access-token` (not the token in the clone URL) and `GIT_TERMINAL_PROMPT=0` so a missing token fails\n fast instead of hanging. When you write the helper from inside `bash -lc` under `set -u`, escape the\n positional arg and the token (`\\$1`, `\\$GH_TOKEN`) so they land **literally** and resolve at git-runtime\n — an unescaped `$1` aborts with \"unbound variable\", and a literal `$GH_TOKEN` keeps the real token out of\n the written file. `rm -f` the helper after the clone/fetch.\n- **Provider auth:** rely on the provider CLI's logged-in session, not checked-in keys.\n- **Agent auth:** lives in the authenticated snapshot (Phase 3) — never a file you write or commit.\n- State holds only **non-secret** wiring (snapshot ids, scope, project, port, repo url/ref).\n\n---\n\n## 6. State file\n\nA repo-local JSON file (e.g. `scripts/orca-vm/-state.json`) threads non-secret values between\nphases. Each script resolves values as **env var → state → built-in fallback**, and merges its outputs\nback. Phase 2 writes the base `snapshotId`; Phase 3 overwrites it with the authenticated snapshot;\nper-workspace `create` boots from `snapshotId`.\n\n```json\n{\n \"baseName\": \"orca-base\",\n \"snapshotId\": \"snap_authenticated_image_id\",\n \"authSourceSnapshotId\": \"snap_base_image_id\",\n \"scope\": \"\",\n \"project\": \"\",\n \"port\": 7331,\n \"repoUrl\": \"https://host/org/repo.git\",\n \"repoRef\": \"main\",\n \"projectRoot\": \"/abs/path/on/remote/repo\"\n}\n```\n\n---\n\n## 7. Script templates (provider-agnostic shapes)\n\nScaffold under `scripts/orca-vm/`. These are **shapes** — fill in the provider's real commands. All\nreserve stdout for the final JSON and log progress to stderr. Include a shared `json_value ` /\n`env_value ` reader (env → state → fallback) in each.\n\n**Where each script runs:**\n\n- **Local-side** (`create`/`suspend`/`resume`/`destroy` + the base-snapshot/auth scripts the user\n invokes) runs **on the user's desktop**, so it must run on their OS. macOS/Linux: `#!/usr/bin/env\n bash`, `set -euo pipefail`, quoted paths. **Windows:** a bare `.sh` won't run — scaffold `.ps1`/`.cmd`\n or require WSL/Git-Bash and point `orca.yaml` at the right launcher.\n- **Remote-side** (commands you `exec` *inside* the Linux VM) always runs in the VM's Linux shell, so\n bash is fine there regardless of the user's OS.\n\n### 7a. Base-snapshot (`-base-snapshot.sh`) — Phase 2\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# resolve base_name/repo_url/repo_ref/project_root/port/scope/project/timeout (env→state→fallback)\n# resolve gh token: GH_TOKEN | GITHUB_TOKEN | `gh auth token`\n# 1. provision a sandbox (timeout/vcpus/published port/snapshot retention); trap: remove on error\n# 2. remote exec (long timeout): install pkgs + gh + corepack/pnpm + agent CLI;\n# clone with GIT_ASKPASS(token); write headless main-only build config;\n# dev setup; pnpm install; build CLI; build headless electron main; smoke-check tools\n# 3. snapshot stopped sandbox; parse snapshot id (fail if unparseable)\n# 4. merge { baseName, snapshotId, projectRoot, repoUrl, repoRef, port, scope, project } into state\n# print only the state JSON to stdout\n```\n\nWorked Vercel commands for this phase are in §7f. You run this script by hand (not via `orca.yaml`),\nafter exporting the first-run inputs the state file doesn't have yet — e.g. provider scope/project, the\nrepo URL/ref, and a git token (`GH_TOKEN`); later runs read them back from state.\n\n### 7b. Auth (`-base-auth.sh`) — Phase 3\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# read source snapshot from state.snapshotId (fail if absent); auth_name=\"${base_name}-auth\"\n# 1. boot sandbox from source snapshot; trap: remove on error\n# 2. INTERACTIVE/TTY remote exec: agent login — user completes URL/code. Headless VM: MUST use the\n# device-auth flow (e.g. `codex login --device-auth`) — plain OAuth login binds a loopback callback\n# port the host can't reach and hangs. User runs this themselves (you have no interactive TTY); ask\n# them to report back when it's done before continuing.\n# 3. verify login, then refuse to snapshot if not logged in. Prefer the status command's EXIT CODE (most\n# agent CLIs exit non-zero when unauthenticated) over string-matching. If you must grep, fold stderr\n# first (`status 2>&1 | grep …` — many agents print the success line there) and match the agent's exact\n# success line; never `grep -qi 'logged in'`, which also matches \"not logged in\". Codex example: §7f.\n# 4. snapshot; parse new id\n# 5. merge { snapshotId:, authSourceSnapshotId: } into state; remove auth sandbox\n# print only the state JSON to stdout\n```\n\n### 7c. Create (`-create.sh`) — per workspace\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# read authenticated snapshotId/scope/project/port/repo*/project_root (env→state→fallback)\n# fail clearly if snapshotId is missing (point back to Phases 2–3)\n# name = orca-${ORCA_VM_RECIPE_ID}-${ORCA_VM_INSTANCE_ID} (sanitized, length-capped)\n# 1. boot sandbox from snapshotId with a published port; capture the public URL → pairing address\n# (an externally reachable wss:// URL); trap: remove sandbox on error\n# 2. remote exec: ensure repo at desired commit; rebuild only if commit changed (cache marker)\n# 3. remote exec: start orca serve in the background and read the recipe JSON it writes (see below)\n# 4. print serve's JSON to stdout, optionally enriched with userData:\n# { schemaVersion:1, pairingCode, projectRoot, userData:{ provider, resourceId:name, snapshotId } }\n```\n\n**The exact `orca serve` invocation and its output (verified — do not improvise the flags).** Inside the\nVM, run:\n\n```bash\norca serve \\\n --port \"$PORT\" \\\n --project-root \"$ABS_REPO_PATH_ON_REMOTE\" \\\n --pairing-address \"$EXTERNAL_WSS_URL\" \\\n --recipe-json\n```\n\n**Binary name:** in a VM built from source (the Phase-2 flow), run it as `pnpm exec orca-dev serve …`\nfrom the repo root — `orca-dev` is the in-repo entrypoint and is what the §7f example uses. Plain\n`orca serve …` is the same command when the built CLI is installed on the VM's PATH. The flags/output\nare identical either way.\n\nThere is **no `--host` flag**. `--project-root` must be an absolute directory on the remote. With\n`--recipe-json` the server **stays running** and prints exactly this single object to **stdout**, then\nkeeps serving:\n\n```json\n{ \"schemaVersion\": 1, \"pairingCode\": \"\", \"projectRoot\": \"\" }\n```\n\n`pairingCode` is the pairing URL, already pointing at whatever you passed as `--pairing-address` — so set\n`--pairing-address` to the externally reachable address and **pass `pairingCode` through unchanged; never\nhand-rewrite it**. Because serve runs in the foreground and doesn't exit, redirect its stdout to a file\nand poll until that file parses as JSON (and bail if the process dies — dump its stderr log). Your\n`create` script then prints that JSON (optionally merging `userData`). Concrete pattern: §7f.\n\n### 7d. Suspend / resume / destroy — per workspace\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\npayload=\"$(cat)\" # Orca passes lifecycle JSON on stdin\nresource_id=\"$(node -e 'const d=JSON.parse(process.argv[1]); process.stdout.write(d.recipeResult?.userData?.resourceId ?? \"\")' \"$payload\")\"\n[ -n \"$resource_id\" ] || { echo \"No resource id in lifecycle payload\" >&2; exit 1; }\n# suspend: provider suspend \"$resource_id\"\n# resume: provider resume \"$resource_id\"; then RE-EMIT fresh recipe JSON (pairing may change)\n# destroy: provider remove \"$resource_id\" (or set destroy: none in orca.yaml)\n```\n\n### 7e. State file — scaffold with scope/project/repo filled in and snapshot ids empty (§6).\n\n### 7f. Worked example — Vercel Sandbox (all three phases)\n\nA real, working shape (the Vercel surface is a CLI: `vercel sandbox create|exec|snapshot|remove`). Adapt\nnames; verify flags against `vercel sandbox --help` for the user's CLI version before relying on them.\nThese ground §7a (base snapshot) and §7b (auth), which are otherwise generic skeletons.\n\n**Phase 2 — base snapshot (§7a):** provision → install tools + clone + headless build → snapshot.\n\n```bash\n# provision a fresh build sandbox (retain a couple of snapshots); trap-remove on error\nvercel sandbox create --name \"$base\" --runtime node24 --timeout 30m --vcpus 4 --publish-port \"$port\" \\\n --snapshot-expiration 30d --keep-last-snapshots 2 \"${vercel_args[@]}\" >&2\n# remote build (long timeout): install pkgs+gh+pnpm+agent CLI, clone with GIT_ASKPASS (write the helper\n# with LITERAL \\$1/\\$GH_TOKEN so they resolve at git-runtime, not write-time — see §5/§7f create — then\n# `rm -f /tmp/askpass.sh`), write the headless main-only build config (drop the renderer), dev setup,\n# build CLI + headless main, smoke-check\nvercel sandbox exec \"$base\" \"${vercel_args[@]}\" --timeout 25m --env \"GH_TOKEN=$gh_token\" … -- bash -lc '…build…' >&2\n# snapshot the STOPPED sandbox and parse the id from CLI output (fail if unparseable)\nout=\"$(vercel sandbox snapshot \"$base\" --stop --expiration 30d \"${vercel_args[@]}\" 2>&1)\"; printf '%s\\n' \"$out\" >&2\nsnapshot_id=\"$(printf '%s\\n' \"$out\" | sed -nE 's/.*(snap_[A-Za-z0-9]+).*/\\1/p' | tail -1)\"\n# merge { baseName, snapshotId, scope, project, port, repoUrl, repoRef, projectRoot } into state; print state JSON\n```\n\n**Phase 3 — agent-auth snapshot (§7b):** boot the base, log the agent in interactively, re-snapshot.\n(`codex` below is an example — substitute the user's chosen agent's login/status verbs, e.g. `claude`.)\n\n```bash\nvercel sandbox create --name \"$auth\" --snapshot \"$snapshot_id\" --timeout 30m --publish-port \"$port\" \"${vercel_args[@]}\" >&2\n# INTERACTIVE — the USER runs this in their own terminal (you have no interactive TTY) and completes the\n# URL/code on the HOST. --device-auth is MANDATORY on a headless VM: plain `codex login` binds a loopback\n# callback port the host browser can't reach and hangs. Ask the user to report back when login finishes.\nvercel sandbox exec --interactive --tty \"$auth\" \"${vercel_args[@]}\" -- bash -lc 'codex login --device-auth'\n# refuse to snapshot an unauthenticated VM — fold stderr, match codex's exact success line (§4)\nvercel sandbox exec \"$auth\" \"${vercel_args[@]}\" --timeout 30s -- bash -lc 'codex login status 2>&1' | grep -Eqi 'Logged in using ChatGPT|Logged in via device' \\\n || { echo \"agent not logged in; not snapshotting\" >&2; exit 1; }\nout=\"$(vercel sandbox snapshot \"$auth\" --stop --expiration 30d \"${vercel_args[@]}\" 2>&1)\"; printf '%s\\n' \"$out\" >&2\nnew_id=\"$(printf '%s\\n' \"$out\" | sed -nE 's/.*(snap_[A-Za-z0-9]+).*/\\1/p' | tail -1)\"\n# overwrite state.snapshotId = new_id, record authSourceSnapshotId = snapshot_id; remove the auth sandbox\n```\n\n**Per-workspace `create`** (the fast path):\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# resolve from env→state→fallback: snapshot_id, scope, project, port, repo_url, repo_ref, project_root\nvercel_args=(); [ -n \"$scope\" ] && vercel_args+=(--scope \"$scope\"); [ -n \"$project\" ] && vercel_args+=(--project \"$project\")\n[ -n \"$snapshot_id\" ] || { echo \"snapshotId missing — run Phases 2–3 first\" >&2; exit 1; }\ngh_token=\"${GH_TOKEN:-${GITHUB_TOKEN:-$(command -v gh >/dev/null 2>&1 && gh auth token 2>/dev/null || true)}}\"\nname=\"orca-${ORCA_VM_RECIPE_ID:-vercel-sandbox}-${ORCA_VM_INSTANCE_ID:-$(date +%s)}\" # sanitize+cap to 63 chars\n\n# Arm cleanup BEFORE create so a failing create can't leak a half-built paid sandbox.\ncleanup_on_error() { [ \"$?\" -ne 0 ] && vercel sandbox remove \"$name\" \"${vercel_args[@]}\" >/dev/null 2>&1 || true; }\ntrap cleanup_on_error EXIT\n\n# 1. boot from the authenticated snapshot, publish the serve port\ncreate_output=\"$(vercel sandbox create --name \"$name\" --snapshot \"$snapshot_id\" \\\n --timeout 30m --publish-port \"$port\" \"${vercel_args[@]}\" 2>&1)\"; printf '%s\\n' \"$create_output\" >&2\n# Vercel prints the published https URL; derive the external wss:// pairing address from it\npublic_url=\"$(printf '%s\\n' \"$create_output\" | sed -nE 's#.*(https://[^[:space:]]+\\.vercel\\.run).*#\\1#p' | head -1)\"\n[ -n \"$public_url\" ] || { echo \"no published URL in create output\" >&2; exit 1; }\npairing_ws=\"${public_url/https:\\/\\//wss://}\"\n\n# 2. (remote) ensure the repo is at the right commit; rebuild only if the commit changed (cache marker)\nvercel sandbox exec \"$name\" \"${vercel_args[@]}\" --timeout 20m \\\n --env \"GH_TOKEN=$gh_token\" --env \"ORCA_PROJECT_ROOT=$project_root\" \\\n --env \"ORCA_REPO_URL=$repo_url\" --env \"ORCA_REPO_REF=$repo_ref\" \\\n -- bash -lc 'set -euo pipefail; cd \"$ORCA_PROJECT_ROOT\"; \\\n # Re-establish git auth for the private-repo fetch (why + full rationale: §5); else it hangs on a prompt.\n # Load-bearing escaping: \\$1 and \\$GH_TOKEN must land LITERALLY and resolve at git-runtime. Test after\n # any edit here — reformatting the nested printf/node quoting silently breaks the fetch or leaks the token.\n if [ -n \"${GH_TOKEN:-}\" ]; then \\\n printf \"%s\\n\" \"#!/usr/bin/env bash\" \"case \\\"\\$1\\\" in *Username*) echo x-access-token;; *Password*) echo \\\"\\$GH_TOKEN\\\";; esac\" > /tmp/askpass.sh; \\\n chmod 700 /tmp/askpass.sh; export GIT_ASKPASS=/tmp/askpass.sh GIT_TERMINAL_PROMPT=0; fi; \\\n git fetch origin \"$ORCA_REPO_REF\"; \\\n git checkout -B \"$ORCA_REPO_REF\" FETCH_HEAD; \\\n rm -f /tmp/askpass.sh; \\\n c=\"$(git rev-parse HEAD)\"; [ -f .orca-built ] && [ \"$(cat .orca-built)\" = \"$c\" ] || { \\\n pnpm install --prefer-offline && pnpm run build:cli && \\\n node config/scripts/run-electron-vite-build.mjs --config config/electron-vite.vm-serve.config.ts && \\\n printf \"%s\" \"$c\" > .orca-built; }' >&2\n\n# 3. (remote) start orca serve in the background, writing recipe JSON to a file; poll until it parses\nrecipe_json=\"$(vercel sandbox exec \"$name\" \"${vercel_args[@]}\" --timeout 60s \\\n --env \"ORCA_PORT=$port\" --env \"ORCA_PROJECT_ROOT=$project_root\" --env \"ORCA_PAIRING_ADDRESS=$pairing_ws\" \\\n -- bash -lc 'set -euo pipefail; cd \"$ORCA_PROJECT_ROOT\"; rm -f /tmp/orca-recipe.json /tmp/orca-serve.log; \\\n nohup pnpm exec orca-dev serve --port \"$ORCA_PORT\" --project-root \"$ORCA_PROJECT_ROOT\" \\\n --pairing-address \"$ORCA_PAIRING_ADDRESS\" --recipe-json >/tmp/orca-recipe.json 2>/tmp/orca-serve.log /dev/null 2>&1 && { cat /tmp/orca-recipe.json; exit 0; }; \\\n kill -0 \"$pid\" 2>/dev/null || { cat /tmp/orca-serve.log >&2; exit 1; }; sleep 0.25; \\\n done; cat /tmp/orca-serve.log >&2; echo \"serve recipe JSON timed out\" >&2; exit 1')\"\n\n# 4. print serve's JSON enriched with userData (single object on stdout)\nnode -e 'const p=JSON.parse(process.argv[1]); console.log(JSON.stringify({...p, schemaVersion:1,\n userData:{...p.userData, provider:\"vercel-sandbox\", resourceId:process.argv[2], snapshotId:process.argv[3]}}))' \\\n \"$recipe_json\" \"$name\" \"$snapshot_id\"\ntrap - EXIT\n```\n\n`suspend`/`resume`/`destroy` use `vercel sandbox stop|...|remove \"$resource_id\"` reading\n`userData.resourceId` from stdin (§7d). This is the **Orca-server** connection mode (the recipe emits a\npairing URL). If the user chose **SSH** in the §1 interview, use §7g instead.\n\n### 7g. Worked example — existing SSH host (SSH connection mode)\n\nSSH mode is **fundamentally different from §7c/§7f**, not a relabeling of them:\n\n- **`create` does NOT run `orca serve` and does NOT emit a `pairingCode`.** Orca itself connects to the\n host over its SSH relay, brings up the git + filesystem providers, and imports the repo. The script's\n only job is to make the host ready and **print SSH connection details** Orca will dial.\n- The result uses a `connection` block with `type: \"ssh\"` and a `target`, **not** the flat\n `pairingCode`/`projectRoot` shape. Exact shape (Orca rejects anything else):\n\n```json\n{\n \"schemaVersion\": 1,\n \"connection\": {\n \"type\": \"ssh\",\n \"projectRoot\": \"/abs/path/to/repo/on/host\",\n \"target\": {\n \"label\": \"my-box\",\n \"host\": \"192.0.2.10\",\n \"port\": 22,\n \"username\": \"ubuntu\",\n \"identityFile\": \"~/.ssh/id_ed25519\",\n \"jumpHost\": \"bastion.example.com\",\n \"proxyCommand\": \"cloudflared access ssh --hostname %h\",\n \"relayGracePeriodSeconds\": 0,\n \"portForwards\": []\n }\n }\n}\n```\n\n`label`, `host`, `port`, `username` are required; the rest are optional — omit any you don't need.\n\n**Networking → which `target` fields to set** (how *your desktop* reaches the box — there is no\n`orca serve` URL in SSH mode):\n\n- Public IP / DNS, or a Tailscale/VPN address → `host`; SSH port → `port` (usually 22).\n- Key auth → `identityFile` (add `identitiesOnly: true` if the agent has many keys).\n- Through a bastion → `jumpHost` (a `user@host` ProxyJump) **or** a full `proxyCommand` (e.g. an access\n proxy). Use one, not both.\n- A service port the workspace needs → add entries to `portForwards`.\n- `relayGracePeriodSeconds` (optional): how long Orca keeps the SSH relay alive after the workspace\n detaches before tearing it down; `0` = tear down immediately. Leave it off unless the user wants a\n reconnect grace window.\n\n**Toolchain & agent auth on a persistent (no-snapshot) host — do this ONCE, by hand, before wiring the\nrecipe** (there's no base image to bake; the host *is* the base). Run the §7f Phase-2 install steps and\nthe §7f Phase-3 ` login --device-auth` **directly over SSH on the host** (interactive, e.g.\n`ssh -t user@host ' login --device-auth'`). After that the host stays ready across workspaces.\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# resolve from env→state→fallback (default unset optionals to \"\"): ssh_username, host,\n# ssh_port (default 22), identity_file, jump_host, proxy_command, project_root, repo_url, repo_ref\n: \"${identity_file:=}\"; : \"${jump_host:=}\"; : \"${proxy_command:=}\" # avoid set -u aborts on optionals\ngh_token=\"${GH_TOKEN:-${GITHUB_TOKEN:-$(command -v gh >/dev/null 2>&1 && gh auth token 2>/dev/null || true)}}\"\nssh_target=\"${ssh_username}@${host}\"\nssh_opts=(-p \"$ssh_port\"); [ -n \"$identity_file\" ] && ssh_opts+=(-i \"$identity_file\")\n# Why: a fresh host's key isn't in known_hosts; a StrictHostKeyChecking prompt would HANG a\n# non-interactive create. Pre-add the key (or set the option) so it can't block.\nssh-keyscan -p \"$ssh_port\" \"$host\" >> \"$HOME/.ssh/known_hosts\" 2>/dev/null || true\n\n# 1. ensure the repo is present and at the right commit on the host (NO orca serve here)\nssh \"${ssh_opts[@]}\" \"$ssh_target\" \\\n \"GH_TOKEN='$gh_token' GIT_TERMINAL_PROMPT=0 bash -lc '\n set -euo pipefail\n [ -d \\\"$project_root/.git\\\" ] || git clone \\\"$repo_url\\\" \\\"$project_root\\\"\n cd \\\"$project_root\\\" && git fetch origin \\\"$repo_ref\\\" && git checkout -B \\\"$repo_ref\\\" FETCH_HEAD\n '\" >&2\n\n# 2. print the SSH connection block (NO pairingCode, NO orca serve). host/port/username tell Orca's\n# relay how to dial in; identityFile/jumpHost/proxyCommand/portForwards are emitted when set.\nnode -e 'const [host,port,user,idf,jh,pc,root]=process.argv.slice(1);\n const target={ label:\"per-workspace-host\", host, port:Number(port), username:user };\n if(idf) target.identityFile=idf; if(jh) target.jumpHost=jh; if(pc) target.proxyCommand=pc;\n // add target.portForwards=[...] here if the workspace needs forwarded service ports\n console.log(JSON.stringify({ schemaVersion:1, connection:{ type:\"ssh\", projectRoot:root, target } }))' \\\n \"$host\" \"$ssh_port\" \"$ssh_username\" \"$identity_file\" \"$jump_host\" \"$proxy_command\" \"$project_root\"\n```\n\n`suspend`/`resume`/`destroy`: on a persistent host there's usually nothing to tear down — set\n`destroy: none` and omit suspend/resume. (Orca still disconnects/reconnects its own SSH relay on\nsleep/wake/delete — that's separate from these scripts.)\n\nIf the SSH host is instead an **ephemeral/snapshot-capable VM** (your hypervisor, or a cloud VM with\nimage support), keep the §7f Phase-2/3 base-image model for provisioning, but still emit the\n`connection.type:\"ssh\"` block above instead of starting `orca serve`.\n\n### 7h. Worked example — local Docker SSH (SSH connection mode)\n\nLocal Docker can model an ephemeral SSH VM without cloud cost: build a base image with `sshd`, tools,\nrepo prerequisites, and the agent CLI; run an **interactive auth container** once; then `docker commit`\nthat container as the authenticated image used by per-workspace `create`.\n\nKey points:\n\n- Publish container SSH to a random localhost port (`-p 127.0.0.1::22`) and emit\n `connection.type:\"ssh\"` with `host:\"127.0.0.1\"`, that port, `username`, `identityFile`, and\n `identitiesOnly:true`.\n- Generate a repo-local SSH key if needed, but gitignore the private/public key files.\n- **Bake SSH host keys into the base image** (`ssh-keygen -A` at **build** time; at runtime only generate\n if absent). Ephemeral containers all present the **same** host key, so `known_hosts` on `127.0.0.1`\n doesn't churn as the published port rotates across workspaces (otherwise every container's freshly\n generated key collides on `localhost` and trips host-key-changed warnings).\n- The auth image is the Docker equivalent of Phase 3: the **user** runs the agent login **inside** the\n container (you can't drive it — you have no interactive TTY), configures proxy env/config, approves\n hooks, and you commit once they report it's done. On a headless container use the **device-auth** flow\n (§4). Verify login before committing — exit code, or fold stderr and match the exact success line (§4).\n- Do not bind-mount or copy the host's full agent home into the image. Let each container have writable\n agent state; only the committed auth image should carry reusable authenticated state.\n- If committing from an interactive shell, force the runtime entrypoint back to `sshd`:\n `docker commit --change='ENTRYPOINT [\"/usr/local/bin/orca-docker-ssh-entrypoint\"]' …`.\n- `destroy` should read `recipeResult.userData.resourceId` and run `docker rm -f \"$resource_id\"`.\n\nValidation before wiring/live use:\n\n```bash\ndocker image inspect \"$auth_image\" --format '{{json .Config.Entrypoint}}'\ndocker run -d --name \"$name\" -p 127.0.0.1::22 -e \"ORCA_SSH_PUBLIC_KEY=$pubkey\" \"$auth_image\"\ndocker ps -a --filter \"name=$name\"\ndocker logs \"$name\"\nssh -i \"$key\" -p \"$port\" -o IdentitiesOnly=yes user@127.0.0.1 'codex --version'\n```\n\nIf the container exits immediately, inspect logs before the cleanup trap removes it; a committed\ninteractive image with `ENTRYPOINT [\"bash\"]` is a common cause.\n\nAlso confirm the **host key is stable** across containers: the SSH `ssh -i … 127.0.0.1` dial should not\ntrigger a host-key-changed warning when a second container reuses the port. If it does, the host keys\nweren't baked into the base image (see the `ssh-keygen -A` point above).\n\n### 7i. Windows local-side scripts\n\nThe local-side scripts run on the user's desktop. On **Windows**, a bare `.sh` won't execute. Either\nrequire WSL/Git-Bash (and point `orca.yaml` at e.g. `bash ./scripts/orca-vm/.sh` via a `.cmd`\nlauncher), or scaffold PowerShell equivalents. Minimal PowerShell shape:\n\n```powershell\n#requires -Version 5\n$ErrorActionPreference = 'Stop'\n# resolve env→state→fallback; run the provider CLI / ssh the same way;\n# capture provider output; build the result object for the chosen mode and write ONE line of JSON to stdout.\n# Orca-server mode: @{ schemaVersion=1; pairingCode=$pairingCode; projectRoot=$projectRoot; userData=@{...} }\n# SSH mode: @{ schemaVersion=1; connection=@{ type=\"ssh\"; projectRoot=$projectRoot;\n# target=@{ label=$label; host=$host; port=$port; username=$user } } } (see §7g/§7h)\n($result | ConvertTo-Json -Compress -Depth 6)\n# progress/errors → Write-Error / the error stream, never stdout.\n```\n\nThe remote-side commands you run *inside* the Linux VM stay bash regardless of the desktop OS.\n\n---\n\n## 8. Per-workspace recipe contract (the fast path)\n\nOnce the authenticated snapshot exists, this runs on every workspace create. Define recipes in\n`orca.yaml`:\n\n```yaml\nenvironmentRecipes:\n - id: cloud-sandbox\n name: Cloud Sandbox\n create: ./scripts/orca-vm/cloud-sandbox-create.sh\n suspend: ./scripts/orca-vm/cloud-sandbox-suspend.sh\n resume: ./scripts/orca-vm/cloud-sandbox-resume.sh\n destroy: ./scripts/orca-vm/cloud-sandbox-destroy.sh\n```\n\n`create` runs **locally from the repo root** and prints **one** JSON object to stdout. Its shape depends\non the connection mode chosen in §1:\n\n**Orca-server mode** — boot the env, start `orca serve` in it, and print serve's result:\n\n```json\n{\n \"schemaVersion\": 1,\n \"pairingCode\": \"orca-pairing-code-or-url\",\n \"projectRoot\": \"/absolute/path/to/repo/on/remote\",\n \"userData\": { \"provider\": \"example\", \"resourceId\": \"provider-resource-id\" }\n}\n```\n\nHere `pairingCode` (from `orca serve --recipe-json`) and `projectRoot` are required; `schemaVersion` (`1`)\nand `userData` are optional.\n\n**SSH mode** — do **not** run `orca serve`; print the `connection.type:\"ssh\"` block instead (full shape +\nworked script in §7g). `pairingCode` is **not** used in SSH mode.\n\nLifecycle hooks (all run locally):\n\n- `create`: required. Prints recipe result JSON.\n- `suspend`: optional. Sleep; reads lifecycle payload on stdin.\n- `resume`: optional. Wake; reads payload on stdin and **prints fresh recipe JSON** (pairing may change).\n- `destroy`: optional unless `destroy: none`. Delete/cleanup; reads payload on stdin.\n\nStart Orca remotely with `orca serve --port \"$PORT\" --project-root \"$ABS_ROOT\" --pairing-address\n\"$EXTERNAL_WSS_URL\" --recipe-json` (exact flags + output in §7c). Set `--pairing-address` to the\nexternally reachable address so the emitted `pairingCode` is reachable; tunneling/port mapping is the\nscript's job.\n\nBackward compatibility: `command`→`create`, `cleanup`→`destroy`, `cleanup: none`→`destroy: none`.\nPrefer the lifecycle names.\n\n---\n\n## 9. Doctor and validation\n\nValidate in two stages — the cheap dry run first, then the live self-test.\n\n### Dry run (free, non-destructive) — always do this first\n\n`orca vm recipe doctor --repo-path --json` validates **static wiring only** — it does\n**not** boot anything. It checks: local-host execution (v1), repo path, recipe id exists,\ncreate/destroy/suspend/resume command paths resolve, suspend/resume are paired, and each script is\nexecutable (POSIX exec bit; skipped on Windows). Fix every failure here before spending any cloud money.\n\n### Live self-test (`--provision`) — diagnose and iterate yourself\n\n`orca vm recipe doctor --repo-path --provision --json` actually runs the recipe end\nto end: it executes `create`, validates the returned recipe JSON, then runs `destroy` to **tear the\nenvironment back down** (so the test leaves nothing running, as long as `destroy` works). It spends real\ncloud money, so get the user's OK **once** before starting — that one approval covers the whole loop\nbelow; do not re-ask before each run.\n\nOn failure, the JSON result includes a `provisionTranscript` with the **complete** captured output of\neach stage so you can self-diagnose without asking the user to relay logs:\n\n```json\n{\n \"ok\": false,\n \"checks\": [ { \"id\": \"recipe.provision\", \"status\": \"fail\", \"message\": \"…\" } ],\n \"provisionTranscript\": {\n \"provision\": { \"exitCode\": 0, \"signal\": null, \"stdout\": \"…\", \"stderr\": \"…\", \"parseError\": \"…\" },\n \"destroy\": { \"exitCode\": 0, \"signal\": null, \"stdout\": \"…\", \"stderr\": \"…\" }\n }\n}\n```\n\n**Run it as a loop:** read `provisionTranscript.provision.stderr` / `.stdout` / `.parseError` (and\n`destroy.*`), fix the script, and re-run `--provision` until `ok` is `true` — iterating on your own\nrather than waiting for the user to paste errors. Common reads: a non-empty `stderr` with `exitCode 0`\nplus a `parseError` means `create` ran but printed something other than the single recipe-result JSON on\nstdout (often a stray `echo` — route it to stderr, see §10); a non-zero `exitCode` is a provider/script\nfailure described in `stderr`. Each stream is redacted and capped (head+tail) — large logs keep both the\nsetup context and the failure.\n\nThe self-test cannot see provider-side truth beyond what the scripts print, so still confirm: state has a\npopulated **authenticated** `snapshotId` (Phases 2–3 done), and `destroy` is implemented/tested (or\nexplicitly `none` — in which case the self-test won't tear down, so clean up manually).\n\nFor SSH recipes, also smoke-test the exact emitted target before declaring success: dial the host/port\nwith the identity/proxy settings, run `pwd`, verify the repo path, check the agent binary, and confirm\n`destroy` removes the provider resource/container. For Docker, inspect the auth image entrypoint and do a\nstartup-only `docker run` before the full clone/install path.\n\n---\n\n## 10. Failure modes\n\n- **Build exceeds plan timeout (e.g. Hobby 45m).** Use enough vCPUs and a timeout covering the build;\n else split work or use a higher plan. The cap also limits per-workspace runtime — surface it.\n- **Build exceeds plan RAM.** Build the **headless main only** (drop the renderer) — the biggest fitter.\n- **Private-repo clone hangs/fails.** Wrong/missing token. Use `GIT_ASKPASS` + `GIT_TERMINAL_PROMPT=0`\n so it fails fast instead of prompting.\n- **`GIT_ASKPASS` helper aborts the clone with \"`$1: unbound variable`\".** The `printf`/heredoc that writes\n the helper inside `bash -lc` under `set -u` expanded `$1`/`$GH_TOKEN` at **write** time. Escape them\n (`\\$1`, `\\$GH_TOKEN`) so they land literally and resolve at git-runtime; this also keeps the real token\n out of the file. `rm -f` the helper afterward (§5, §7f).\n- **Agent verified as \"not logged in\" despite a good login.** `codex login status` (and similar) print\n \"Logged in …\" to **stderr**; an stdout-only `grep` misses it. Prefer the status **exit code**; if you\n grep, fold stderr first (`status 2>&1 | grep …`) and match the exact success line — not `grep -qi\n 'logged in'`, which also matches \"not logged in\".\n- **Headless agent login hangs.** Plain OAuth `login` starts a loopback callback server on a VM/container\n port the host browser can't reach. Use the **device-auth** flow (`login --device-auth`) — it prints a\n URL + code the user opens on the host.\n- **`known_hosts` host-key churn on local Docker.** Each ephemeral container regenerating its SSH host key\n collides on `127.0.0.1` as the published port rotates. Bake host keys into the base image at build time\n (`ssh-keygen -A`; runtime generates only if absent) so all containers share one stable key (§7h).\n- **Snapshot expired/evicted.** If `create` hits an unknown snapshot id, rerun Phases 2–3 and update\n `snapshotId`.\n- **Agent auth didn't persist.** Confirm `snapshotId` points at the **authenticated** snapshot; re-run\n Phase 3. Warn that short-lived tokens may need periodic re-auth.\n- **Agent auth copied from the host breaks.** Do not bind-mount/copy a full host agent home; sqlite\n files can be unwritable or host-specific, hooks may need approval again, and config may reference\n local-only env vars. Authenticate inside the runtime and snapshot/commit that layer.\n- **Docker auth image exits immediately.** Inspect `docker image inspect … .Config.Entrypoint` and\n `docker logs`. If the image was committed from an interactive shell, reset the entrypoint to the SSH\n entrypoint during `docker commit`.\n- **Leaked paid resource.** Every long script must trap errors and remove the sandbox it created.\n- **`create` emits non-JSON on stdout.** A stray `echo` corrupts the result — stdout is for the final\n JSON only; everything else to stderr. The `--provision` self-test surfaces this as `exitCode 0` + a\n `parseError` with the offending stdout in `provisionTranscript` (§9).\n\n---\n\n## 11. Boundaries\n\n- Don't create accounts, choose plans/regions, or invent scope/project/org/image/billing ids.\n- Don't invent or store credentials; no secrets in `userData`, state, comments, docs, or commits.\n- Don't run paid/long phases (base snapshot, auth, live test) without an explicit OK.\n- Don't hide provider errors behind generic messages — preserve actionable stderr.\n- Don't make Orca own provider lifecycle beyond invoking the configured scripts.\n- Don't commit or create an Orca workspace unless asked.\n" // oxfmt-ignore -const ORCHESTRATION_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Use Orca orchestration for structured multi-agent coordination: threaded\n messages, blocking ask/reply flows, task dispatch, worker_done/escalation\n waits, task DAGs, decision gates, coordinator loops, or decomposing work\n across agents. Use `orca-cli` instead for full ownership handoffs, including\n requests phrased as \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", or \"another worktree\" when the user did not explicitly ask to\n supervise, monitor, wait for results, or coordinate a DAG. Use `orca-cli` for\n ordinary terminal control, lightweight terminal prompts, shell commands, Orca\n worktree management, reading or waiting on terminals, and automation of the\n browser embedded inside Orca. Use Computer Use for browser windows, webviews,\n Orca app UI, or desktop UI outside Orca's embedded browser.\n---\n\n# Orca Inter-Agent Orchestration\n\nOrchestration is Orca's structured coordination layer for agent messages, task ownership, dispatch state, and worker completion tracking.\n\nUse this skill when coordination state matters. For lightweight terminal prompts or basic worktree/terminal/built-in-browser control, use `orca-cli`.\n\n## Tool Boundary\n\nIf a task says to use Orca orchestration, the coordinator must create or bind a Run, create the Task with `orca orchestration task-create`, then attach the worker with either the preferred `orca orchestration worker-start` composition or the low-level `orca orchestration dispatch --inject` path.\n\nDo not substitute non-Orca subagent tools, generic agent-spawn APIs, or chat-only parallel worker features. Those may create useful workers, but they do not create Orca task/dispatch provenance, injected lifecycle preambles, `worker_done` authority, or decision gates.\n\nBefore claiming a worker was orchestrated, verify the task/dispatch exists:\n\n```bash\norca orchestration task-list --json\norca orchestration dispatch-show --task --json\n```\n\nIf the work was accidentally run outside Orca orchestration, say so plainly. To repair provenance, rerun or revalidate the needed work through a fresh Orca terminal plus injected dispatch; do not retroactively describe the external worker as orchestrated.\n\n## When To Use\n\n- Send/reply/ask between agent terminals with persistent messages.\n- Dispatch structured tasks to workers and wait for `worker_done` or `escalation`.\n- Track task DAGs with dependencies.\n- Run coordinator loops or decision gates.\n\nDo not use orchestration merely because the user says \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", or asks for another worktree/agent/model/effort. Those are full ownership transfers unless the user explicitly asks to supervise, monitor, wait for worker completion/results, coordinate a DAG, use decision gates, or keep a blocking ask/reply loop.\n\n## Preconditions\n\n- `orca status --json` should show a running runtime.\n- `orca` must be on PATH (`orca-ide` on Linux).\n- The orchestration experimental feature must be enabled in Settings > Experimental.\n- `orca orchestration` commands are RPC calls to the running Orca runtime.\n\n## Contract Migration\n\nOrca adopts a live pre-update orchestration assignment into an ordinary Run. Adoption preserves the existing agent process, PTY/session, terminal handle, tab/leaf/pane, worktree or folder workspace, Task, and Dispatch; it never restarts or replaces the worker. The retired scheduler is not revived, and a newly created attempt uses the current grammar.\n\nTreat the authority label on injected or formatted messages as definitive:\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported command printed with the message, using the same CLI executable and arguments that the original prompt supplied.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded, at-least-once cutover replay. Process it idempotently and acknowledge it only through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or lifecycle action.\n- An unlabeled current message uses the current guide and current grammar.\n\nAn explicitly selected current Run, attested current Run binding, current Dispatch, or federated attachment takes precedence over legacy fallback. A retained adoption record alone never turns a current command into a legacy call.\n\nDatabase provenance, an old-looking terminal, or a legacy Run ID does not prove mutation authority. If the runtime cannot prove liveness, principal ownership, capability, or the exact legacy contract, it degrades to read-only inspection and must not fall back to local execution. Exact recovery may restore the already-live PTY once in its original inactive background tab. It must not spawn, write, signal, stop, switch, focus, split, or inject a terminal. Loss of lifecycle authority does not invalidate the existing assignment, process, or filesystem work.\n\nCompatibility retries have narrow guarantees. A pending ask, a reply, a final Dispatch settlement, and a consuming check have durable recovery identities. A-era heartbeat and escalation calls remain at-least-once across a manual A-to-B retry because identical later signals may be intentional. If an A-era ask may already have been answered, run the exact non-consuming recovery check printed by the runtime first; after its answer is printed and acknowledged, a new invocation with the same question creates a new question. Never guess among multiple identical question threads.\n\nWhen a compatibility or recovery command returns structured next-step arguments, run those exact arguments with the same CLI executable. The arguments intentionally omit the executable name so the guidance works with `orca`, `orca-ide`, `orca-dev`, or another configured Orca CLI command. Do not translate the command from memory, broaden its recipient, or retry it as a current mutation unless the returned guidance explicitly says to.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The initial command durably commits the question, prints its exact `ask --resume ` command, and exits with launcher status `75`; it does not wait for the answer. Run that exact resume command after the launcher or update boundary. Resume is idempotent and read-oriented: it waits for the already-committed question and does not create another one. For a WSL process that received compatibility proof at launch, use the printed executable `orca-ide` WSL resume command so the same distro and packaged launcher authority are preserved; do not substitute a PATH-resolved local CLI. Older WSL processes that never received the hidden launch token remain lifecycle read-only after the update, even while their terminal and filesystem work continue.\n\nLegacy inspection remains available without consuming mail:\n\n```bash\norca orchestration run-list --json\n# run_legacy_local is an empty audit tombstone after adoption.\norca orchestration run-show --id run_legacy_local --json\n# In run-list, find the ordinary Run whose objective is:\n# \"Recovered orchestration work from a contract update\"\norca orchestration run-show --id --json\norca orchestration task-list --run --json\norca orchestration inbox --full --json\norca orchestration check --terminal --peek --format --json\norca terminal read --terminal --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\nIf the original coordinator is unavailable or cannot prove its retained authority, a current coordinator may explicitly take over the adopted Run from its own live agent terminal:\n\n```bash\norca orchestration run-use --id --takeover-legacy --json\norca orchestration check --run --json\n```\n\nTakeover fences only the old coordinator, binds the current one, and moves pending worker mail into current Run Delivery. It is bound to the authenticated invoking terminal; `--from` cannot name another coordinator. Live legacy workers keep their original Tasks, Dispatches, processes, filesystems, and old prompt commands; their later questions, escalations, and completion reports route to the current coordinator. Do not use takeover while the original coordinator is still actively coordinating, because its later lifecycle mutations are rejected.\n\nDo not launch a replacement editor merely because the desktop app or runtime was updated. If adoption cannot prove continuing authority, keep the original worker as the only editor until it reaches a stable handoff point, then use a new current Dispatch in a conflict-free placement for any remaining work.\n\n## Ownership\n\nNew orchestration messages and tasks belong to one explicitly bound Run. A Run is only a durable namespace and coordinator inbox; it never schedules or places workers. Lifecycle authority comes from the active Dispatch, and terminal handles remain routing metadata rather than durable identity. Send `worker_done` and `heartbeat` from the worker's own terminal; Orca routes them to that Dispatch's Run.\n\nClassify inherited context before sending lifecycle messages:\n\n- Coordinated subtask: a live coordinator owns the DAG and waits on this dispatch. Follow the preamble exactly, including `worker_done`, heartbeat/status, `ask`, and `escalation`.\n- Full handoff means ownership transfer, not supervised dispatch. The original actor is not monitoring a DAG, so do not create lifecycle obligations unless the user explicitly asks you to supervise.\n- Classify requests containing \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"another agent\", or \"another worktree\" as full handoffs by default, even when the user names a custom model or reasoning effort.\n- Use supervised orchestration only when the user explicitly asks you to \"supervise\", \"monitor\", \"wait\", \"track completion\", \"wait for worker_done\", return results, coordinate a DAG, use a decision gate, or manage ask/reply flow.\n- Do not use `orca orchestration dispatch --inject` for full handoffs. It injects a coordinator preamble that tells the worker to send `worker_done`, heartbeat, and `ask` messages, then end its turn under the original terminal's dispatch lifecycle.\n- Do not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. Do not peek at terminal output after prompt delivery to monitor progress.\n- A review-only `worker_done` reports findings; it does not authorize coordinator file edits. After a review-only completion, synthesize findings, ask a decision gate if ownership is unclear, and dispatch or hand off fixes unless the user explicitly asked the coordinator to own fixes.\n- If the user's plan names a next owner agent (for example, \"then use opencode to create a PR\"), post-review corrections and PR prep belong to that named owner. The coordinator routes, synthesizes, asks decision gates when needed, and supervises; the named owner edits files and creates the PR.\n\nIf unclear, inspect orchestration state before sending lifecycle messages:\n\n```bash\norca orchestration task-list --json\norca terminal list --json\n# If inherited context includes a task id:\norca orchestration dispatch-show --task --json\n```\n\n## Messaging\n\n```bash\norca orchestration send --subject [--to ] [--from ] [--body ] [--type ] [--priority ] [--thread-id ] [--payload ] [--json]\norca orchestration check [--terminal ] [--ack ] [--peek|--all] [--types ] [--format] [--wait] [--timeout-ms ] [--json]\norca orchestration reply --id --body [--from ] [--json]\norca orchestration ask (--question |--resume ) [--options ] [--timeout-ms ] [--from ] [--json]\norca orchestration inbox [--limit ] [--json]\n```\n\nRules:\n\n- Omit `--from` unless impersonating another terminal; Orca auto-resolves it from the current terminal.\n- A coordinator `check` returns the bound Run's oldest FIFO Delivery (up to 50 messages) and replays that exact batch until `--ack `. Process every message before acknowledging; `check --ack --wait` acknowledges, checks, and waits in one operation.\n- Use `--peek` and `--all` only for read-only history/debugging. Type filters decide when a waiter wakes; the returned actionable Delivery is still the oldest full batch.\n- Use `dispatch:` for coordinator guidance to one supervised worker. Orca routes that stable address locally or through the connected-server relay; do not substitute a remote terminal handle.\n- Terminal handles remain appropriate for low-level pre-Dispatch messaging. Prefer `agentTerminalHandle` from the create response, fall back to `startupTerminal.handle` for older runtimes, then re-resolve with `orca terminal list --worktree ... --json` if missing or stale. Continue with the replacement handle only; never dual-send to old and new handles.\n- `terminal list --json` omits `visualLayouts` because handle recovery does not need topology. Add `--include-visual-layouts` only for explicit tab and pane inspection.\n- `orca orchestration check --peek --format --json` returns locally formatted unread mail without consuming it; it never writes to terminal input or remotely wakes another terminal. Use `orchestration dispatch --inject` to deliver a tracked task, or `terminal send` when an existing agent needs a free-form prompt.\n- While supervising workers manually, use `check --wait --types worker_done,escalation,question --timeout-ms ` instead of sleep/poll loops. Process the whole Delivery, reply to `question` messages with `orca orchestration reply --id --body --json`, then acknowledge and keep waiting.\n- Treat a `check --wait` timeout or `{count:0}` as a checkpoint, not a worker failure. Long coding tasks routinely run 15-60 minutes; keep using rolling waits unless you receive `worker_done`/`escalation`, the terminal exits or disappears, or the user explicitly asks you to stop.\n- Heartbeats and visible terminal activity mean the worker is alive, not done. Do not stop, close, kill, or restart a worker just because it has not produced a completion message yet.\n- Use `ask` when a worker needs a blocking answer from the coordinator; it defaults to the active Dispatch's Run. Timeout or disconnect leaves the question pending, so resume by its original message ID instead of asking again.\n- `check --wait` returns one bounded Delivery, not every future completion. Process every message, acknowledge it, then keep waiting until every expected Dispatch settles.\n- Group addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`.\n- Message types include `status`, `dispatch`, `worker_done`, `merge_ready`, `escalation`, `handoff`, `question`, `decision_gate` (legacy/gates), and `heartbeat`.\n- Use group addresses only for messages that are genuinely useful to many terminals, such as `status` broadcasts or intentional fan-out questions. Do not send dispatch lifecycle messages to groups.\n- `worker_done` belongs to the active Dispatch and defaults to its Run mailbox; never target a group.\n- A valid `worker_done` for the active `taskId` + `dispatchId` marks the task and dispatch completed automatically. Do not follow it with `task-update --status completed`; reserve manual updates for explicit recovery or overrides.\n- `heartbeat` is also Dispatch-scoped. Include both IDs and omit `--to` so Orca uses the owning Run; use `status` for broad progress updates.\n\n## Tasks And Dispatch\n\nA Run is the namespace/inbox, a Task is the work item, and a Dispatch assigns one Task attempt to a terminal. Create or bind a Run once before the common loop.\n\n```bash\norca orchestration run-create --objective --json\norca orchestration task-create --spec [--deps ] [--parent ] [--json]\norca orchestration task-list [--status ] [--ready] [--brief] [--json]\norca orchestration task-update --id --status [--result ] [--json]\norca orchestration dispatch --task --to [--from ] [--inject] [--json]\norca orchestration dispatch-show --task [--json]\n```\n\nTask statuses: `pending`, `ready`, `dispatched`, `completed`, `failed`, `blocked`.\n\nDispatch rules:\n\n- `--inject` sends the task spec plus preamble into a recognized agent CLI so it can report `worker_done`.\n- If the target is a bare shell, omit `--inject`, dispatch for tracking if needed, then send the prompt manually with `orca terminal send --terminal --text --enter --json`.\n- After 3 consecutive failures on one task, the dispatch context circuit-breaks and the task is marked failed.\n- Use `task-list --brief --json` for coordinator sweeps; it collapses whitespace and caps each echoed spec at 160 characters (`spec_truncated` marks shortened rows). Omit `--brief` when the full spec is required, or when an older CLI rejects it as an unknown flag.\n\n## Preferred Supervised Worker Loop\n\nUse `worker-start` for the normal supervised path. It composes the existing worktree, terminal, readiness, and dispatch primitives while returning exact created/reused effects. Agents still choose placement and concurrency; Orca does not schedule workers or infer conflicts.\n\nCreate the Run and every independent Task first, then start all independent workers before waiting:\n\n```bash\norca orchestration run-create --objective \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration worker-start --task --worktree current --agent codex --json\norca orchestration worker-start --task --worktree current --agent claude --json\n```\n\n`current` and exact existing worktrees create a fresh agent terminal and do not rerun setup. Reuse an existing agent only with `--terminal `.\n\nFor a per-invocation Claude, Codex, or Cursor launch, pass an opaque provider model id with `--model`; add `--effort` only when that agent/model supports the level. These options apply only to fresh agent terminals, override general agent default arguments, and are reported under `launch.requested` and `launch.effective` in the receipt:\n\n```bash\norca orchestration worker-start --task --worktree current --agent claude --model aws-bedrock-opus-5 --effort high --json\n```\n\n`--effort` requires `--model`, and neither option can combine with `--terminal`. A connected worker server must advertise launch-preference support before Orca forwards either option.\n\nFor a new worktree, setup runs by default and agent-first creation reuses the returned startup agent terminal:\n\n```bash\norca orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n# Independent/top-level:\norca orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nSetup normally starts alongside the agent. Only a repository explicitly configured with `wait-for-setup` delays agent launch until setup succeeds. Use `--setup skip` or `--setup inherit` only for a concrete reason.\n\nRead the returned receipt before continuing: `ready` plus setup `running` is normal for start-immediately, while wait-for-setup returns setup `succeeded` before accepting task input. A failed or unknown start exits nonzero; inspect its `stage`, `effects`, and `residualResources` instead of guessing or automatically retrying. A wait-for-setup timeout can honestly leave setup `running`, which is not proof of failure.\n\nTo run the worker on another connected Orca server, add `--on `. The Run and Tasks remain authoritative on the current server; later commands route by Dispatch ID, so never repeat `--on`:\n\n```bash\n# Mac Run home -> Windows worker (the reverse is identical from a Windows Run home)\norca orchestration worker-start --task --on windows --worktree new-top-level --repo --name --agent codex --setup run --json\norca orchestration worker-show --dispatch --json\norca orchestration worker-read --dispatch --limit 50 --json\norca orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nRemote `current` and `new-child` are intentionally invalid because those words are ambiguous across servers. Use an exact discovered remote worktree selector or `new-top-level` with an explicit remote repo selector.\n\nThe follow-up is structured inbox mail, not prompt injection. The worker's next\n`orchestration check` receives it even when the Dispatch is on another connected Orca server.\n\n`worker-read` defaults to `--source auto`: Orca returns the exact hook-reported Codex, Claude, OpenClaude, or Grok transcript when it can prove the worker session, otherwise it returns bounded terminal output with `source: \"terminal\"` and a typed `fallbackReason`. Continue with the returned top-level `cursor`; it stays pinned to that exact source. If Orca reports `source_changed`, start a fresh read without the old cursor. Never supply or guess a provider session ID or transcript path.\n\nWait until every expected Dispatch settles, not for a fixed number of batches:\n\n```bash\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n# Process every message. For each accepted worker_done that is not immediately reused:\norca orchestration worker-release --dispatch --json\n# Acknowledge only after every message and required release decision is handled:\norca orchestration check --ack --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\nAfter processing each accepted `worker_done`, choose the terminal's next owner before you acknowledge the Delivery or wait again. If the same exact agent has an immediate follow-up Task, read the `worker.agent_terminal_handle` field of `worker-show --dispatch --json`, then run `orca orchestration worker-start --task --terminal --json` so Orca transfers cleanup ownership to the new Dispatch. Otherwise run `orca orchestration worker-release --dispatch --json`.\n\nRun `worker-release` after both succeeded and failed `worker_done` reports unless the user explicitly asked to keep that worker live. Release is post-completion cleanup, not cancellation: Orca first preserves inspectable output, then closes only the exact agent terminal owned by that settled Dispatch. Reused or pre-existing terminals, setup terminals, coordinators, active workers, user-taken-over terminals, and identities Orca cannot prove are retained. If the user explicitly asks to keep the live terminal for debugging, record that exception with `orca orchestration worker-retain --dispatch --json` instead of silently skipping cleanup. When the user is finished, the same Dispatch can be passed to `worker-release`, which clears the requested retention and releases the terminal.\n\nDo not release a worker because of a timeout, TUI idle state, heartbeat, status, question, escalation, or rejected/stale `worker_done`. If release returns `release_pending` or `release_unknown`, do not substitute `terminal close`; follow the exact recovery action in the receipt. A replayed Delivery may repeat `worker-release` safely.\n\nWorkers report exactly once using the IDs and capability injected by Orca; they do not supply Run/server/terminal identity:\n\n```bash\norca orchestration send --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a,path/b\" --json\n# On failure, use --outcome failed; never encode failure only in prose.\n```\n\nA worker question defaults to its owning Run. Timeout leaves it pending:\n\n```bash\norca orchestration ask --question \"\" --options \"yes,no\" --timeout-ms 600000 --json\norca orchestration ask --resume --timeout-ms 600000 --json\n# Coordinator:\norca orchestration reply --id --body \"\" --json\n```\n\nRecovery is conditional, never a fixed destructive sequence:\n\n- `worker-show --dispatch ` says `ready`: keep waiting or read bounded output.\n- It proves `failed` or `stopped`: start a replacement with `worker-start --task --retry-of ` plus an explicit `--on`/`--worktree` and `--agent`/`--terminal` choice. Retry does not silently inherit placement.\n- It remains `outcome_unknown`: either `worker-stop --dispatch ` and inspect again, or explicitly `worker-abandon --dispatch ` while accepting that resources may still be live. Abandon performs no remote, process, or filesystem action.\n- `worker-stop` closes only the exact supervised agent terminal. It never deletes the worktree, setup terminal, configured tabs, or unrelated processes.\n\nLow-level `worktree create`, `terminal create`, and `dispatch --inject` remain valid recipes for custom argv or topology that `worker-start` does not express.\n\n## Gates And Legacy Inspection\n\n```bash\norca orchestration gate-create --task --question [--options ] [--json]\norca orchestration gate-resolve --id --resolution [--json]\norca orchestration gate-list [--task ] [--status ] [--json]\n```\n\nUse `ask` for worker-to-coordinator questions; it creates a `question` message that the coordinator answers with `reply`. Use `gate-create` only for coordinator-managed task DAG decisions, not for answering a worker's `ask`.\n\n`coordinator-start`, `coordinator-stop`, `run`, and `run-stop` are retired scheduler commands. They perform no effects and return the current-skill recovery action. They are not aliases for lightweight Run creation or binding.\n\nRecovery only: `orca orchestration reset --tasks|--messages|--all --json` clears the selected local orchestration database state. Do not run it during active coordination unless explicitly abandoning that state.\n\n## Full Handoffs\n\nFor full ownership transfer, use non-lifecycle terminal/worktree commands and then stop monitoring unless the user asks for supervision.\n\nTreat these as full handoff requests by default: \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"send this to another agent\", \"another agent\", \"another worktree\", or \"launch another agent to own this.\" Custom model or reasoning effort words such as `gpt-5.5`, `high`, or `xhigh` do not make the handoff supervised.\n\nSupervised orchestration remains available only when the user explicitly asks for supervision or coordination: \"supervise\", \"monitor\", \"wait for worker_done\", \"wait for results\", \"track completion\", \"DAG\", \"decision gate\", \"ask/reply\", or \"coordinate workers.\"\n\nDo not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Do not create a `taskId`/`dispatchId`, inject a lifecycle preamble, wait for completion, or read the worker terminal after prompt delivery except to avoid losing the initial prompt.\n\nNew top-level worktree handoff:\n\n```bash\norca worktree create --name --no-parent --agent codex --prompt \"\" --setup run --json\n```\n\nBefore creating a new worktree from an active feature branch, decide and state whether the desired Orca lineage is child or top-level. Use child worktree lineage only when the new work is conceptually stacked under or dependent on the active worktree. For independent repo-wide fixes, standalone feature work, or unrelated follow-up tasks, create a top-level worktree with `--no-parent`.\n\nExisting terminal handoff:\n\n```bash\norca terminal send --terminal --text \"\" --enter --json\n```\n\nCustom Codex model/effort handoff:\n\n`orca worktree create --agent codex --prompt ...` launches the known Codex agent but does not accept Codex-specific `--model` or `-c model_reasoning_effort=...` arguments. When the user asks for a specific Codex model or effort, create the independent worktree first, launch Codex with the requested command in that worktree, wait only for TUI readiness if prompt delivery would otherwise race startup, send the prompt, and stop.\n\nThe two-step custom-argv path cannot enforce a repository's explicit `wait-for-setup` startup policy because the later `terminal create` is not the startup owned by `worktree create`. Use it only when the repository starts agents immediately. If the repository requires `wait-for-setup`, use an agent-first configured launcher that can preserve sequencing, or stop and ask rather than silently bypassing the policy.\n\nNote: when no repo default-terminal configuration supplies a primary terminal, bare create opens a fallback shell before `terminal create` adds the agent. Configured default tabs are materialized instead and may run real commands. Prefer `--agent` whenever custom argv is not required. With the two-step path, target only the agent handle; close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell.\n\nUse the exact full `::` worktree id returned by `orca worktree create --json`; a bare repo id cannot target the new worktree.\n\n```bash\norca worktree create --name --no-parent --setup run --json\norca terminal create --worktree id: --title --command 'codex --model gpt-5.5 -c model_reasoning_effort=\"xhigh\"' --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca terminal send --terminal --text \"\" --enter --json\n```\n\nWait only for `tui-idle` when needed to avoid losing the prompt. Do not monitor task completion.\n\n`--no-parent` only controls Orca lineage; it does not choose the Git base. If the work should start from the repo default base, omit `--base-branch` so Orca uses that default, or explicitly pass the repo default base (`origin/main`, `origin/master`, or the `orca repo show --repo --json` value); never base it on the current feature branch unless the user explicitly asks for stacked work or \"branch from current\". Put current-branch context in the prompt instead.\n\n## Worker Terminals\n\nChoose the worker location before creating a terminal. `Fresh worker` means a fresh agent session, not a new git worktree. For parallel work, create one fresh agent terminal per worker in the same required worktree, falling back to the active worktree when none is named. If the task says current worktree only, depends on uncommitted files/artifacts, or must validate/PR the current branch, keep every worker in the active worktree:\n\n```bash\norca terminal create --worktree active --title --command \"codex\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nReuse an idle agent in the required worktree only if the prompt allows reuse; otherwise create a fresh terminal there. Create a new worktree only when the user explicitly requests one or a concrete checkout or filesystem conflict makes sharing unsafe or impossible; if the user did not request it, state that conflict before running `worktree create`. Independent tasks, parallel execution, convenience, or a preference for separate checkouts are not isolation requirements.\n\nWhen a new worktree is allowed, use child lineage for isolated work that is stacked under or dependent on the active worktree, and use `--no-parent` when it is not stacked. Decide the Git base separately: `--no-parent` makes the worktree top-level in Orca, while omitted `--base-branch` uses the repo default base.\n\nFor every new worktree, pass `--setup run` so any configured repository setup hook runs. This does not mean waiting for setup before agent launch: preserve the repository's startup policy, whose default starts setup and the agent side by side. Use `--setup skip` or `--setup inherit` only when there is a concrete task-specific reason, and state that reason before creating the worktree. This rule does not rerun setup for current or existing worktrees.\n\n```bash\norca worktree create --name --agent codex --setup run --json\n# or: --agent claude | omp | pi | grok | ...\n# Read from agentTerminalHandle, falling back to startupTerminal.handle.\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nFor new-worktree workers, read the id and `agentTerminalHandle` from `worktree create`, falling back to `startupTerminal.handle` for older runtimes. Use that as the sole worker handle when present; otherwise use `terminal list` to resolve the agent handle. Omit `--repo` only inside an Orca-managed worktree; otherwise pass `--repo `.\n\n**For an allowed new worktree, use agent-first:** `--agent` reveals the new worktree and launches the selected agent **in its first terminal**, without adding a separate fallback shell for that worker. Pass `--setup run`; repo setup and default-terminal settings may add intentional tabs or splits. Do **not** run bare `worktree create` and then `terminal create --command ` for the same worker when agent-first create is available: without configured default tabs, that two-step path leaves a fallback shell + agent pair. Only use it when custom agent argv is required (for example Codex model/effort flags) or when an older CLI rejects `--agent`; if you must, message only the agent handle. Configured default tabs are intentional surfaces, so close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell. Do not run `worktree create` when the task must stay in the current worktree.\n\nUse `orca worktree create --prompt ...` or `orca terminal send ...` for full handoffs or untracked/lightweight prompts. Those paths do not attach `taskId`/`dispatchId`; the worker should not send lifecycle messages unless the prompt supplies a live orchestration preamble.\n\nSidebar lineage and orchestration lifecycle are related but not identical. A same-worktree worker may appear as a peer under that worktree in the sidebar while remaining a child dispatch in orchestration state; only an actual child worktree creates visible parent/child worktree lineage.\n\nOther terminal commands coordinators often need:\n\n```bash\norca terminal list [--worktree ] [--include-visual-layouts] [--json]\norca terminal create [--worktree ] [--title ] [--command ] [--json]\norca terminal split --terminal [--direction horizontal|vertical] [--command ] [--json]\norca terminal wait --terminal --for tui-idle --timeout-ms --json\norca terminal read --terminal --json\norca terminal send --terminal --text --enter --json\n```\n\nIf an older CLI rejects `worktree create --agent`, create the worktree normally, then run `orca terminal create --worktree --command \"codex\" --json` or `--command \"claude\"`.\n\nWait for `tui-idle` before dispatching. Always pass `--timeout-ms`; real coding tasks can take 15-60 minutes. During supervision, use rolling `check --wait` windows. If a window returns no matching message, inspect `task-list`, `terminal read`, or `terminal wait --for tui-idle` as a liveness checkpoint; if the terminal is still working or producing activity, keep waiting instead of retrying the task.\n\n## Agent Guidance\n\n- Workers with a valid live preamble must send `worker_done` exactly once from their own terminal with an explicit `--outcome succeeded` or `--outcome failed`:\n `orca orchestration send --type worker_done --subject \"\" --body \"<3-sentence summary: what you did, what you found, what's left>\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a\" --report-path \"\" --json`\n- A failed outcome is still a terminal report, but Orca records both the Dispatch and Task as failed. Never encode failure only in the subject/body.\n- After sending `worker_done`, end your turn and idle at the agent prompt. The coordinator may reuse or release this terminal after it processes your report; do not start more work, poll, or attempt to close the terminal yourself. If it reuses you, it re-engages you with a fresh preamble + TASK block delivered as new terminal input.\n- For long tasks, send heartbeat/status only when the preamble asks for it, including both IDs:\n `orca orchestration send --type heartbeat --subject \"alive\" --payload '{\"taskId\":\"\",\"dispatchId\":\"\",\"phase\":\"implementing\"}' --json`\n- If blocked before completion, use `ask`; use `escalation` only when ownership is valid and the coordinator must intervene.\n- Treat preambles inherited through terminal history or full handoffs as stale unless the current prompt explicitly keeps that coordinator in the loop.\n- Coordinators must account for every settled worker terminal before waiting again or ending the turn: immediately reuse the exact worker for a new Dispatch, explicitly retain it at the user's request with `worker-retain`, or run `worker-release`. Do not leave a completed worker live merely to inspect output; released workers remain readable through `worker-read`.\n- Coordinators should use `task-list --ready` as external memory, dispatch parallel waves, and avoid dependency chains deeper than 3-4 steps.\n\n## Example\n\n```bash\norca terminal create --worktree active --title login-css-worker --command \"claude\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration task-create --spec \"Fix the login button CSS\" --json\norca orchestration dispatch --task --to --inject --json\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\n## Next Action\n\nCoordinator: confirm `orca status --json`, create or bind a Run, inspect `task-list`/`dispatch-show` if inheriting state, then use the explicit supervised loop (`task-create` -> `worker-start` -> `check --wait`). Use low-level terminal creation plus `dispatch --inject` only when the composed start does not express the needed topology. After every accepted `worker_done`, either transfer the exact terminal to an immediate follow-up Dispatch or run `worker-release` before the next wait.\n\nWorker: if the current prompt contains a live dispatch preamble, do the task, use `ask` for blocking questions, and send `worker_done` once with the required payload. If the preamble is stale or absent, do not send lifecycle messages; inspect state or treat the prompt as an ordinary handoff.\n" +const ORCHESTRATION_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Use Orca orchestration for structured multi-agent coordination: threaded\n messages, blocking ask/reply flows, task dispatch, worker_done/escalation\n waits, task DAGs, decision gates, coordinator loops, or decomposing work\n across agents. Use `orca-cli` instead for full ownership handoffs, including\n requests phrased as \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", or \"another worktree\" when the user did not explicitly ask to\n supervise, monitor, wait for results, or coordinate a DAG. Use `orca-cli` for\n ordinary terminal control, lightweight terminal prompts, shell commands, Orca\n worktree management, reading or waiting on terminals, and automation of the\n browser embedded inside Orca. Use Computer Use for browser windows, webviews,\n Orca app UI, or desktop UI outside Orca's embedded browser.\n---\n\n# Orca Inter-Agent Orchestration\n\nOrchestration is Orca's structured coordination layer for agent messages, task ownership, dispatch state, and worker completion tracking.\n\nUse this skill when coordination state matters. For lightweight terminal prompts or basic worktree/terminal/built-in-browser control, use `orca-cli`.\n\n## Tool Boundary\n\nIf a task says to use Orca orchestration, the coordinator must create or bind a Run, create the Task with `orca orchestration task-create`, then attach the worker with either the preferred `orca orchestration worker-start` composition or the low-level `orca orchestration dispatch --inject` path.\n\nDo not substitute non-Orca subagent tools, generic agent-spawn APIs, or chat-only parallel worker features. Those may create useful workers, but they do not create Orca task/dispatch provenance, injected lifecycle preambles, `worker_done` authority, or decision gates.\n\nBefore claiming a worker was orchestrated, verify the task/dispatch exists:\n\n```bash\norca orchestration task-list --json\norca orchestration dispatch-show --task --json\n```\n\nIf the work was accidentally run outside Orca orchestration, say so plainly. To repair provenance, rerun or revalidate the needed work through a fresh Orca terminal plus injected dispatch; do not retroactively describe the external worker as orchestrated.\n\n## When To Use\n\n- Send/reply/ask between agent terminals with persistent messages.\n- Dispatch structured tasks to workers and wait for `worker_done` or `escalation`.\n- Track task DAGs with dependencies.\n- Run coordinator loops or decision gates.\n\nDo not use orchestration merely because the user says \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", or asks for another worktree/agent/model/effort. Those are full ownership transfers unless the user explicitly asks to supervise, monitor, wait for worker completion/results, coordinate a DAG, use decision gates, or keep a blocking ask/reply loop.\n\n## Preconditions\n\n- `orca status --json` should show a running runtime.\n- `orca` must be on PATH (`orca-ide` on Linux).\n- The orchestration experimental feature must be enabled in Settings > Experimental.\n- `orca orchestration` commands are RPC calls to the running Orca runtime.\n\n## Contract Migration\n\nOrca adopts a live pre-update orchestration assignment into an ordinary Run. Adoption preserves the existing agent process, PTY/session, terminal handle, tab/leaf/pane, worktree or folder workspace, Task, and Dispatch; it never restarts or replaces the worker. The retired scheduler is not revived, and a newly created attempt uses the current grammar.\n\nTreat the authority label on injected or formatted messages as definitive:\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported command printed with the message, using the same CLI executable and arguments that the original prompt supplied.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded, at-least-once cutover replay. Process it idempotently and acknowledge it only through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or lifecycle action.\n- An unlabeled current message uses the current guide and current grammar.\n\nAn explicitly selected current Run, attested current Run binding, current Dispatch, or federated attachment takes precedence over legacy fallback. A retained adoption record alone never turns a current command into a legacy call.\n\nDatabase provenance, an old-looking terminal, or a legacy Run ID does not prove mutation authority. If the runtime cannot prove liveness, principal ownership, capability, or the exact legacy contract, it degrades to read-only inspection and must not fall back to local execution. Exact recovery may restore the already-live PTY once in its original inactive background tab. It must not spawn, write, signal, stop, switch, focus, split, or inject a terminal. Loss of lifecycle authority does not invalidate the existing assignment, process, or filesystem work.\n\nCompatibility retries have narrow guarantees. A pending ask, a reply, a final Dispatch settlement, and a consuming check have durable recovery identities. A-era heartbeat and escalation calls remain at-least-once across a manual A-to-B retry because identical later signals may be intentional. If an A-era ask may already have been answered, run the exact non-consuming recovery check printed by the runtime first; after its answer is printed and acknowledged, a new invocation with the same question creates a new question. Never guess among multiple identical question threads.\n\nWhen a compatibility or recovery command returns structured next-step arguments, run those exact arguments with the same CLI executable. The arguments intentionally omit the executable name so the guidance works with `orca`, `orca-ide`, `orca-dev`, or another configured Orca CLI command. Do not translate the command from memory, broaden its recipient, or retry it as a current mutation unless the returned guidance explicitly says to.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The initial command durably commits the question, prints its exact `ask --resume ` command, and exits with launcher status `75`; it does not wait for the answer. Run that exact resume command after the launcher or update boundary. Resume is idempotent and read-oriented: it waits for the already-committed question and does not create another one. For a WSL process that received compatibility proof at launch, use the printed executable `orca-ide` WSL resume command so the same distro and packaged launcher authority are preserved; do not substitute a PATH-resolved local CLI. Older WSL processes that never received the hidden launch token remain lifecycle read-only after the update, even while their terminal and filesystem work continue.\n\nLegacy inspection remains available without consuming mail:\n\n```bash\norca orchestration run-list --json\n# run_legacy_local is an empty audit tombstone after adoption.\norca orchestration run-show --id run_legacy_local --json\n# In run-list, find the ordinary Run whose objective is:\n# \"Recovered orchestration work from a contract update\"\norca orchestration run-show --id --json\norca orchestration task-list --run --json\norca orchestration inbox --full --json\norca orchestration check --terminal --peek --format --json\norca terminal read --terminal --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\nIf the original coordinator is unavailable or cannot prove its retained authority, a current coordinator may explicitly take over the adopted Run from its own live agent terminal:\n\n```bash\norca orchestration run-use --id --takeover-legacy --json\norca orchestration check --run --json\n```\n\nTakeover fences only the old coordinator, binds the current one, and moves pending worker mail into current Run Delivery. It is bound to the authenticated invoking terminal; `--from` cannot name another coordinator. Live legacy workers keep their original Tasks, Dispatches, processes, filesystems, and old prompt commands; their later questions, escalations, and completion reports route to the current coordinator. Do not use takeover while the original coordinator is still actively coordinating, because its later lifecycle mutations are rejected.\n\nDo not launch a replacement editor merely because the desktop app or runtime was updated. If adoption cannot prove continuing authority, keep the original worker as the only editor until it reaches a stable handoff point, then use a new current Dispatch in a conflict-free placement for any remaining work.\n\n## Ownership\n\nNew orchestration messages and tasks belong to one explicitly bound Run. A Run is only a durable namespace and coordinator inbox; it never schedules or places workers. Lifecycle authority comes from the active Dispatch, and terminal handles remain routing metadata rather than durable identity. Send `worker_done` and `heartbeat` from the worker's own terminal; Orca routes them to that Dispatch's Run.\n\nClassify inherited context before sending lifecycle messages:\n\n- Coordinated subtask: a live coordinator owns the DAG and waits on this dispatch. Follow the preamble exactly, including `worker_done`, heartbeat/status, `ask`, and `escalation`.\n- Full handoff means ownership transfer, not supervised dispatch. The original actor is not monitoring a DAG, so do not create lifecycle obligations unless the user explicitly asks you to supervise.\n- Classify requests containing \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"another agent\", or \"another worktree\" as full handoffs by default, even when the user names a custom model or reasoning effort.\n- Use supervised orchestration only when the user explicitly asks you to \"supervise\", \"monitor\", \"wait\", \"track completion\", \"wait for worker_done\", return results, coordinate a DAG, use a decision gate, or manage ask/reply flow.\n- Do not use `orca orchestration dispatch --inject` for full handoffs. It injects a coordinator preamble that tells the worker to send `worker_done`, heartbeat, and `ask` messages, then end its turn under the original terminal's dispatch lifecycle.\n- Do not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. Do not peek at terminal output after prompt delivery to monitor progress.\n- A review-only `worker_done` reports findings; it does not authorize coordinator file edits. After a review-only completion, synthesize findings, ask a decision gate if ownership is unclear, and dispatch or hand off fixes unless the user explicitly asked the coordinator to own fixes.\n- If the user's plan names a next owner agent (for example, \"then use opencode to create a PR\"), post-review corrections and PR prep belong to that named owner. The coordinator routes, synthesizes, asks decision gates when needed, and supervises; the named owner edits files and creates the PR.\n\nIf unclear, inspect orchestration state before sending lifecycle messages:\n\n```bash\norca orchestration task-list --json\norca terminal list --json\n# If inherited context includes a task id:\norca orchestration dispatch-show --task --json\n```\n\n## Messaging\n\n```bash\norca orchestration send --subject [--to ] [--from ] [--body ] [--type ] [--priority ] [--thread-id ] [--payload ] [--json]\norca orchestration check [--terminal ] [--ack ] [--peek|--all] [--types ] [--format] [--wait] [--timeout-ms ] [--json]\norca orchestration reply --id --body [--from ] [--json]\norca orchestration ask (--question |--resume ) [--options ] [--timeout-ms ] [--from ] [--json]\norca orchestration inbox [--limit ] [--json]\n```\n\nRules:\n\n- Omit `--from` unless impersonating another terminal; Orca auto-resolves it from the current terminal.\n- A coordinator `check` returns the bound Run's oldest FIFO Delivery (up to 50 messages) and replays that exact batch until `--ack `. Process every message before acknowledging; `check --ack --wait` acknowledges, checks, and waits in one operation.\n- Use `--peek` and `--all` only for read-only history/debugging. Type filters decide when a waiter wakes; the returned actionable Delivery is still the oldest full batch.\n- Use `dispatch:` for coordinator guidance to one supervised worker. Orca routes that stable address locally or through the connected-server relay; do not substitute a remote terminal handle.\n- Terminal handles remain appropriate for low-level pre-Dispatch messaging. Prefer `agentTerminalHandle` from the create response, fall back to `startupTerminal.handle` for older runtimes, then re-resolve with `orca terminal list --worktree ... --json` if missing or stale. Continue with the replacement handle only; never dual-send to old and new handles.\n- `terminal list --json` omits `visualLayouts` because handle recovery does not need topology. Add `--include-visual-layouts` only for explicit tab and pane inspection.\n- `orca orchestration check --peek --format --json` returns locally formatted unread mail without consuming it; it never writes to terminal input or remotely wakes another terminal. Use `orchestration dispatch --inject` to deliver a tracked task, or `terminal send` when an existing agent needs a free-form prompt.\n- While supervising workers manually, use `check --wait --types worker_done,escalation,question --timeout-ms ` instead of sleep/poll loops. Process the whole Delivery, reply to `question` messages with `orca orchestration reply --id --body --json`, then acknowledge and keep waiting.\n- Treat a `check --wait` timeout or `{count:0}` as a checkpoint, not a worker failure. Long coding tasks routinely run 15-60 minutes; keep using rolling waits unless you receive `worker_done`/`escalation`, the terminal exits or disappears, or the user explicitly asks you to stop.\n- Heartbeats and visible terminal activity mean the worker is alive, not done. Do not stop, close, kill, or restart a worker just because it has not produced a completion message yet.\n- Use `ask` when a worker needs a blocking answer from the coordinator; it defaults to the active Dispatch's Run. Timeout or disconnect leaves the question pending, so resume by its original message ID instead of asking again.\n- `check --wait` returns one bounded Delivery, not every future completion. Process every message, acknowledge it, then keep waiting until every expected Dispatch settles.\n- Group addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`.\n- Message types include `status`, `dispatch`, `worker_done`, `merge_ready`, `escalation`, `handoff`, `question`, `decision_gate` (legacy/gates), and `heartbeat`.\n- Use group addresses only for messages that are genuinely useful to many terminals, such as `status` broadcasts or intentional fan-out questions. Do not send dispatch lifecycle messages to groups.\n- `worker_done` belongs to the active Dispatch and defaults to its Run mailbox; never target a group.\n- A valid `worker_done` for the active `taskId` + `dispatchId` marks the task and dispatch completed automatically. Do not follow it with `task-update --status completed`; reserve manual updates for explicit recovery or overrides.\n- `heartbeat` is also Dispatch-scoped. Include both IDs and omit `--to` so Orca uses the owning Run; use `status` for broad progress updates.\n\n## Tasks And Dispatch\n\nA Run is the namespace/inbox, a Task is the work item, and a Dispatch assigns one Task attempt to a terminal. Create or bind a Run once before the common loop.\n\n```bash\norca orchestration run-create --objective --json\norca orchestration task-create --spec [--deps ] [--parent ] [--json]\norca orchestration task-list [--status ] [--ready] [--brief] [--json]\norca orchestration task-update --id --status [--result ] [--json]\norca orchestration dispatch --task --to [--from ] [--inject] [--json]\norca orchestration dispatch-show --task [--json]\n```\n\nTask statuses: `pending`, `ready`, `dispatched`, `completed`, `failed`, `blocked`.\n\nDispatch rules:\n\n- `--inject` sends the task spec plus preamble into a recognized agent CLI so it can report `worker_done`.\n- If the target is a bare shell, omit `--inject`, dispatch for tracking if needed, then send the prompt manually with `orca terminal send --terminal --text --enter --json`.\n- After 3 consecutive failures on one task, the dispatch context circuit-breaks and the task is marked failed.\n- Use `task-list --brief --json` for coordinator sweeps; it collapses whitespace and caps each echoed spec at 160 characters (`spec_truncated` marks shortened rows). Omit `--brief` when the full spec is required, or when an older CLI rejects it as an unknown flag.\n\n## Preferred Supervised Worker Loop\n\nUse `worker-start` for the normal supervised path. It composes the existing worktree, terminal, readiness, and dispatch primitives while returning exact created/reused effects. Agents still choose placement and concurrency; Orca does not schedule workers or infer conflicts.\n\nCreate the Run and every independent Task first, then start all independent workers before waiting:\n\n```bash\norca orchestration run-create --objective \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration task-create --spec \"\" --json\norca orchestration worker-start --task --worktree current --agent codex --json\norca orchestration worker-start --task --worktree current --agent claude --json\n```\n\n`current` and exact existing worktrees create a fresh agent terminal and do not rerun setup. Reuse an existing agent only with `--terminal `.\n\nFor a per-invocation Claude, Codex, or Cursor launch, pass an opaque provider model id with `--model`; add `--effort` only when that agent/model supports the level. These options apply only to fresh agent terminals, override general agent default arguments, and are reported under `launch.requested` and `launch.effective` in the receipt:\n\n```bash\norca orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\n```\n\n`--effort` requires `--model`, and neither option can combine with `--terminal`. A connected worker server must advertise launch-preference support before Orca forwards either option.\n\nFor a new worktree, setup runs by default and agent-first creation reuses the returned startup agent terminal:\n\n```bash\norca orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n# Independent/top-level:\norca orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nSetup normally starts alongside the agent. Only a repository explicitly configured with `wait-for-setup` delays agent launch until setup succeeds. Use `--setup skip` or `--setup inherit` only for a concrete reason.\n\nRead the returned receipt before continuing: `ready` plus setup `running` is normal for start-immediately, while wait-for-setup returns setup `succeeded` before accepting task input. A failed or unknown start exits nonzero; inspect its `stage`, `effects`, and `residualResources` instead of guessing or automatically retrying. A wait-for-setup timeout can honestly leave setup `running`, which is not proof of failure.\n\nTo run the worker on another connected Orca server, add `--on `. The Run and Tasks remain authoritative on the current server; later commands route by Dispatch ID, so never repeat `--on`:\n\n```bash\n# Mac Run home -> Windows worker (the reverse is identical from a Windows Run home)\norca orchestration worker-start --task --on windows --worktree new-top-level --repo --name --agent codex --setup run --json\norca orchestration worker-show --dispatch --json\norca orchestration worker-read --dispatch --limit 50 --json\norca orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nRemote `current` and `new-child` are intentionally invalid because those words are ambiguous across servers. Use an exact discovered remote worktree selector or `new-top-level` with an explicit remote repo selector.\n\nThe follow-up is structured inbox mail, not prompt injection. The worker's next\n`orchestration check` receives it even when the Dispatch is on another connected Orca server.\n\n`worker-read` defaults to `--source auto`: Orca returns the exact hook-reported Codex, Claude, OpenClaude, or Grok transcript when it can prove the worker session, otherwise it returns bounded terminal output with `source: \"terminal\"` and a typed `fallbackReason`. Continue with the returned top-level `cursor`; it stays pinned to that exact source. If Orca reports `source_changed`, start a fresh read without the old cursor. Never supply or guess a provider session ID or transcript path.\n\nWait until every expected Dispatch settles, not for a fixed number of batches:\n\n```bash\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n# Process every message. For each accepted worker_done that is not immediately reused:\norca orchestration worker-release --dispatch --json\n# Acknowledge only after every message and required release decision is handled:\norca orchestration check --ack --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\nAfter processing each accepted `worker_done`, choose the terminal's next owner before you acknowledge the Delivery or wait again. If the same exact agent has an immediate follow-up Task, read the `worker.agent_terminal_handle` field of `worker-show --dispatch --json`, then run `orca orchestration worker-start --task --terminal --json` so Orca transfers cleanup ownership to the new Dispatch. Otherwise run `orca orchestration worker-release --dispatch --json`.\n\nRun `worker-release` after both succeeded and failed `worker_done` reports unless the user explicitly asked to keep that worker live. Release is post-completion cleanup, not cancellation: Orca first preserves inspectable output, then closes only the exact agent terminal owned by that settled Dispatch. Reused or pre-existing terminals, setup terminals, coordinators, active workers, user-taken-over terminals, and identities Orca cannot prove are retained. If the user explicitly asks to keep the live terminal for debugging, record that exception with `orca orchestration worker-retain --dispatch --json` instead of silently skipping cleanup. When the user is finished, the same Dispatch can be passed to `worker-release`, which clears the requested retention and releases the terminal.\n\nDo not release a worker because of a timeout, TUI idle state, heartbeat, status, question, escalation, or rejected/stale `worker_done`. If release returns `release_pending` or `release_unknown`, do not substitute `terminal close`; follow the exact recovery action in the receipt. A replayed Delivery may repeat `worker-release` safely.\n\nWorkers report exactly once using the IDs and capability injected by Orca; they do not supply Run/server/terminal identity:\n\n```bash\norca orchestration send --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a,path/b\" --json\n# On failure, use --outcome failed; never encode failure only in prose.\n```\n\nA worker question defaults to its owning Run. Timeout leaves it pending:\n\n```bash\norca orchestration ask --question \"\" --options \"yes,no\" --timeout-ms 600000 --json\norca orchestration ask --resume --timeout-ms 600000 --json\n# Coordinator:\norca orchestration reply --id --body \"\" --json\n```\n\nRecovery is conditional, never a fixed destructive sequence:\n\n- `worker-show --dispatch ` says `ready`: keep waiting or read bounded output.\n- It proves `failed` or `stopped`: start a replacement with `worker-start --task --retry-of ` plus an explicit `--on`/`--worktree` and `--agent`/`--terminal` choice. Retry does not silently inherit placement.\n- It remains `outcome_unknown`: either `worker-stop --dispatch ` and inspect again, or explicitly `worker-abandon --dispatch ` while accepting that resources may still be live. Abandon performs no remote, process, or filesystem action.\n- `worker-stop` closes only the exact supervised agent terminal. It never deletes the worktree, setup terminal, configured tabs, or unrelated processes.\n\nLow-level `worktree create`, `terminal create`, and `dispatch --inject` remain valid recipes for custom argv or topology that `worker-start` does not express.\n\n## Gates And Legacy Inspection\n\n```bash\norca orchestration gate-create --task --question [--options ] [--json]\norca orchestration gate-resolve --id --resolution [--json]\norca orchestration gate-list [--task ] [--status ] [--json]\n```\n\nUse `ask` for worker-to-coordinator questions; it creates a `question` message that the coordinator answers with `reply`. Use `gate-create` only for coordinator-managed task DAG decisions, not for answering a worker's `ask`.\n\n`coordinator-start`, `coordinator-stop`, `run`, and `run-stop` are retired scheduler commands. They perform no effects and return the current-skill recovery action. They are not aliases for lightweight Run creation or binding.\n\nRecovery only: `orca orchestration reset --tasks|--messages|--all --json` clears the selected local orchestration database state. Do not run it during active coordination unless explicitly abandoning that state.\n\n## Full Handoffs\n\nFor full ownership transfer, use non-lifecycle terminal/worktree commands and then stop monitoring unless the user asks for supervision.\n\nTreat these as full handoff requests by default: \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"send this to another agent\", \"another agent\", \"another worktree\", or \"launch another agent to own this.\" Custom model or reasoning effort words such as `gpt-5.5`, `high`, or `xhigh` do not make the handoff supervised.\n\nSupervised orchestration remains available only when the user explicitly asks for supervision or coordination: \"supervise\", \"monitor\", \"wait for worker_done\", \"wait for results\", \"track completion\", \"DAG\", \"decision gate\", \"ask/reply\", or \"coordinate workers.\"\n\nDo not run `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Do not create a `taskId`/`dispatchId`, inject a lifecycle preamble, wait for completion, or read the worker terminal after prompt delivery except to avoid losing the initial prompt.\n\nNew top-level worktree handoff:\n\n```bash\norca worktree create --name --no-parent --agent codex --prompt \"\" --setup run --json\n```\n\nBefore creating a new worktree from an active feature branch, decide and state whether the desired Orca lineage is child or top-level. Use child worktree lineage only when the new work is conceptually stacked under or dependent on the active worktree. For independent repo-wide fixes, standalone feature work, or unrelated follow-up tasks, create a top-level worktree with `--no-parent`.\n\nExisting terminal handoff:\n\n```bash\norca terminal send --terminal --text \"\" --enter --json\n```\n\nCustom Codex model/effort handoff:\n\n`orca worktree create --agent codex --prompt ...` launches the known Codex agent but does not accept Codex-specific `--model` or `-c model_reasoning_effort=...` arguments. When the user asks for a specific Codex model or effort, create the independent worktree first, launch Codex with the requested command in that worktree, wait only for TUI readiness if prompt delivery would otherwise race startup, send the prompt, and stop.\n\nThe two-step custom-argv path cannot enforce a repository's explicit `wait-for-setup` startup policy because the later `terminal create` is not the startup owned by `worktree create`. Use it only when the repository starts agents immediately. If the repository requires `wait-for-setup`, use an agent-first configured launcher that can preserve sequencing, or stop and ask rather than silently bypassing the policy.\n\nNote: when no repo default-terminal configuration supplies a primary terminal, bare create opens a fallback shell before `terminal create` adds the agent. Configured default tabs are materialized instead and may run real commands. Prefer `--agent` whenever custom argv is not required. With the two-step path, target only the agent handle; close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell.\n\nUse the exact full `::` worktree id returned by `orca worktree create --json`; a bare repo id cannot target the new worktree.\n\n```bash\norca worktree create --name --no-parent --setup run --json\norca terminal create --worktree id: --title --command 'codex --model gpt-5.5 -c model_reasoning_effort=\"xhigh\"' --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca terminal send --terminal --text \"\" --enter --json\n```\n\nWait only for `tui-idle` when needed to avoid losing the prompt. Do not monitor task completion.\n\n`--no-parent` only controls Orca lineage; it does not choose the Git base. If the work should start from the repo default base, omit `--base-branch` so Orca uses that default, or explicitly pass the repo default base (`origin/main`, `origin/master`, or the `orca repo show --repo --json` value); never base it on the current feature branch unless the user explicitly asks for stacked work or \"branch from current\". Put current-branch context in the prompt instead.\n\n## Worker Terminals\n\nChoose the worker location before creating a terminal. `Fresh worker` means a fresh agent session, not a new git worktree. For parallel work, create one fresh agent terminal per worker in the same required worktree, falling back to the active worktree when none is named. If the task says current worktree only, depends on uncommitted files/artifacts, or must validate/PR the current branch, keep every worker in the active worktree:\n\n```bash\norca terminal create --worktree active --title --command \"codex\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nReuse an idle agent in the required worktree only if the prompt allows reuse; otherwise create a fresh terminal there. Create a new worktree only when the user explicitly requests one or a concrete checkout or filesystem conflict makes sharing unsafe or impossible; if the user did not request it, state that conflict before running `worktree create`. Independent tasks, parallel execution, convenience, or a preference for separate checkouts are not isolation requirements.\n\nWhen a new worktree is allowed, use child lineage for isolated work that is stacked under or dependent on the active worktree, and use `--no-parent` when it is not stacked. Decide the Git base separately: `--no-parent` makes the worktree top-level in Orca, while omitted `--base-branch` uses the repo default base.\n\nFor every new worktree, pass `--setup run` so any configured repository setup hook runs. This does not mean waiting for setup before agent launch: preserve the repository's startup policy, whose default starts setup and the agent side by side. Use `--setup skip` or `--setup inherit` only when there is a concrete task-specific reason, and state that reason before creating the worktree. This rule does not rerun setup for current or existing worktrees.\n\n```bash\norca worktree create --name --agent codex --setup run --json\n# or: --agent claude | omp | pi | grok | ...\n# Read from agentTerminalHandle, falling back to startupTerminal.handle.\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration dispatch --task --to --inject --json\n```\n\nFor new-worktree workers, read the id and `agentTerminalHandle` from `worktree create`, falling back to `startupTerminal.handle` for older runtimes. Use that as the sole worker handle when present; otherwise use `terminal list` to resolve the agent handle. Omit `--repo` only inside an Orca-managed worktree; otherwise pass `--repo `.\n\n**For an allowed new worktree, use agent-first:** `--agent` reveals the new worktree and launches the selected agent **in its first terminal**, without adding a separate fallback shell for that worker. Pass `--setup run`; repo setup and default-terminal settings may add intentional tabs or splits. Do **not** run bare `worktree create` and then `terminal create --command ` for the same worker when agent-first create is available: without configured default tabs, that two-step path leaves a fallback shell + agent pair. Only use it when custom agent argv is required (for example Codex model/effort flags) or when an older CLI rejects `--agent`; if you must, message only the agent handle. Configured default tabs are intentional surfaces, so close a prior terminal only after `terminal list` or `terminal show` confirms it is an unused shell. Do not run `worktree create` when the task must stay in the current worktree.\n\nUse `orca worktree create --prompt ...` or `orca terminal send ...` for full handoffs or untracked/lightweight prompts. Those paths do not attach `taskId`/`dispatchId`; the worker should not send lifecycle messages unless the prompt supplies a live orchestration preamble.\n\nSidebar lineage and orchestration lifecycle are related but not identical. A same-worktree worker may appear as a peer under that worktree in the sidebar while remaining a child dispatch in orchestration state; only an actual child worktree creates visible parent/child worktree lineage.\n\nOther terminal commands coordinators often need:\n\n```bash\norca terminal list [--worktree ] [--include-visual-layouts] [--json]\norca terminal create [--worktree ] [--title ] [--command ] [--json]\norca terminal split --terminal [--direction horizontal|vertical] [--command ] [--json]\norca terminal wait --terminal --for tui-idle --timeout-ms --json\norca terminal read --terminal --json\norca terminal send --terminal --text --enter --json\n```\n\nIf an older CLI rejects `worktree create --agent`, create the worktree normally, then run `orca terminal create --worktree --command \"codex\" --json` or `--command \"claude\"`.\n\nWait for `tui-idle` before dispatching. Always pass `--timeout-ms`; real coding tasks can take 15-60 minutes. During supervision, use rolling `check --wait` windows. If a window returns no matching message, inspect `task-list`, `terminal read`, or `terminal wait --for tui-idle` as a liveness checkpoint; if the terminal is still working or producing activity, keep waiting instead of retrying the task.\n\n## Agent Guidance\n\n- Workers with a valid live preamble must send `worker_done` exactly once from their own terminal with an explicit `--outcome succeeded` or `--outcome failed`:\n `orca orchestration send --type worker_done --subject \"\" --body \"<3-sentence summary: what you did, what you found, what's left>\" --task-id --dispatch-id --outcome succeeded --files-modified \"path/a\" --report-path \"\" --json`\n- A failed outcome is still a terminal report, but Orca records both the Dispatch and Task as failed. Never encode failure only in the subject/body.\n- After sending `worker_done`, end your turn and idle at the agent prompt. The coordinator may reuse or release this terminal after it processes your report; do not start more work, poll, or attempt to close the terminal yourself. If it reuses you, it re-engages you with a fresh preamble + TASK block delivered as new terminal input.\n- For long tasks, send heartbeat/status only when the preamble asks for it, including both IDs:\n `orca orchestration send --type heartbeat --subject \"alive\" --payload '{\"taskId\":\"\",\"dispatchId\":\"\",\"phase\":\"implementing\"}' --json`\n- If blocked before completion, use `ask`; use `escalation` only when ownership is valid and the coordinator must intervene.\n- Treat preambles inherited through terminal history or full handoffs as stale unless the current prompt explicitly keeps that coordinator in the loop.\n- Coordinators must account for every settled worker terminal before waiting again or ending the turn: immediately reuse the exact worker for a new Dispatch, explicitly retain it at the user's request with `worker-retain`, or run `worker-release`. Do not leave a completed worker live merely to inspect output; released workers remain readable through `worker-read`.\n- Coordinators should use `task-list --ready` as external memory, dispatch parallel waves, and avoid dependency chains deeper than 3-4 steps.\n\n## Example\n\n```bash\norca terminal create --worktree active --title login-css-worker --command \"claude\" --json\norca terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\norca orchestration task-create --spec \"Fix the login button CSS\" --json\norca orchestration dispatch --task --to --inject --json\norca orchestration check --wait --types worker_done,escalation,question --timeout-ms 900000 --json\n```\n\n## Next Action\n\nCoordinator: confirm `orca status --json`, create or bind a Run, inspect `task-list`/`dispatch-show` if inheriting state, then use the explicit supervised loop (`task-create` -> `worker-start` -> `check --wait`). Use low-level terminal creation plus `dispatch --inject` only when the composed start does not express the needed topology. After every accepted `worker_done`, either transfer the exact terminal to an immediate follow-up Dispatch or run `worker-release` before the next wait.\n\nWorker: if the current prompt contains a live dispatch preamble, do the task, use `ask` for blocking questions, and send `worker_done` once with the required payload. If the preamble is stale or absent, do not send lifecycle messages; inspect state or treat the prompt as an ordinary handoff.\n" // Why: no current guide has bundled reference documents, so --full is byte-identical for now. // oxfmt-ignore diff --git a/src/cli/handlers/emulator.test.ts b/src/cli/handlers/emulator.test.ts index 07bdd51e2f5..ff0dc5f141a 100644 --- a/src/cli/handlers/emulator.test.ts +++ b/src/cli/handlers/emulator.test.ts @@ -1,5 +1,5 @@ import path from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { callMock, remoteMock } = vi.hoisted(() => ({ callMock: vi.fn(), @@ -29,6 +29,9 @@ import { main } from '../index' import { okFixture, queueFixtures } from '../test-fixtures' describe('orca emulator CLI handlers', () => { + const originalWorkspaceId = process.env.ORCA_WORKSPACE_ID + const originalWorktreeId = process.env.ORCA_WORKTREE_ID + beforeEach(() => { vi.restoreAllMocks() callMock.mockReset() @@ -38,6 +41,19 @@ describe('orca emulator CLI handlers', () => { process.exitCode = undefined }) + afterEach(() => { + if (originalWorkspaceId === undefined) { + delete process.env.ORCA_WORKSPACE_ID + } else { + process.env.ORCA_WORKSPACE_ID = originalWorkspaceId + } + if (originalWorktreeId === undefined) { + delete process.env.ORCA_WORKTREE_ID + } else { + process.env.ORCA_WORKTREE_ID = originalWorktreeId + } + }) + it('resolves relative APK paths before calling the runtime', async () => { queueFixtures(callMock, okFixture('req_install', { ok: true })) @@ -73,6 +89,46 @@ describe('orca emulator CLI handlers', () => { ) }) + it('uses the folder workspace exported by the current Orca terminal', async () => { + process.env.ORCA_WORKSPACE_ID = 'folder:folder-1' + delete process.env.ORCA_WORKTREE_ID + callMock.mockResolvedValue( + okFixture('req_attach', { + attached: true, + info: { deviceUdid: 'device-1', streamUrl: 'scrcpy://device-1' } + }) + ) + + await main(['emulator', 'attach', 'device-1'], '/folder/project') + + expect(callMock).toHaveBeenCalledOnce() + expect(callMock).toHaveBeenCalledWith( + 'emulator.attach', + { device: 'device-1', worktree: 'folder:folder-1', focus: false }, + { timeoutMs: 180_000 } + ) + }) + + it('uses the current git worktree exported by the Orca terminal', async () => { + process.env.ORCA_WORKSPACE_ID = 'folder:stale-parent' + process.env.ORCA_WORKTREE_ID = 'repo-1::/repo/project ' + callMock.mockResolvedValue( + okFixture('req_attach', { + attached: true, + info: { deviceUdid: 'device-1', streamUrl: 'scrcpy://device-1' } + }) + ) + + await main(['emulator', 'attach', 'device-1'], '/repo/project') + + expect(callMock).toHaveBeenCalledOnce() + expect(callMock).toHaveBeenCalledWith( + 'emulator.attach', + { device: 'device-1', worktree: 'repo-1::/repo/project ', focus: false }, + { timeoutMs: 180_000 } + ) + }) + it('rejects relative APK paths for remote runtimes', async () => { remoteMock.mockReturnValue(true) diff --git a/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts b/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts new file mode 100644 index 00000000000..a7b1766437e --- /dev/null +++ b/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts @@ -0,0 +1,51 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { reportCliError } from '../format' +import { ORCHESTRATION_HANDLERS } from './orchestration' + +afterEach(() => { + vi.restoreAllMocks() +}) + +it('prints a rejected lifecycle verdict as a JSON failure envelope', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const client = { + call: vi.fn().mockResolvedValue({ + result: { + message: { id: 'msg_rejected' }, + lifecycle: { + action: 'rejected', + code: 'sender_not_assignee', + reason: 'dispatch ctx_1 expected the assigned pane' + } + } + }) + } + let rejection: unknown + try { + await ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_foreign'], + ['to', 'term_coord'], + ['subject', 'done'], + ['type', 'worker_done'], + ['outcome', 'succeeded'] + ]), + client, + cwd: '/tmp/repo', + json: true + } as never) + } catch (error) { + rejection = error + } + + expect(rejection).toBeDefined() + reportCliError(rejection, true, { commandPath: ['orchestration', 'send'] }) + + expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({ + ok: false, + error: { + code: 'sender_not_assignee', + message: 'dispatch ctx_1 expected the assigned pane' + } + }) +}) diff --git a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts b/src/cli/handlers/orchestration-lifecycle-rejection.test.ts index c55eed4391d..369edf9c4f6 100644 --- a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts +++ b/src/cli/handlers/orchestration-lifecycle-rejection.test.ts @@ -10,9 +10,11 @@ import { ORCHESTRATION_HANDLERS } from './orchestration' afterEach(() => { process.exitCode = originalExitCode + vi.clearAllMocks() + callMock.mockReset() }) -it('prints a lifecycle rejection and exits unsuccessfully', async () => { +it('raises a lifecycle rejection for the CLI error boundary', async () => { const response = { result: { message: { id: 'msg_rejected' }, @@ -25,22 +27,328 @@ it('prints a lifecycle rejection and exits unsuccessfully', async () => { } callMock.mockResolvedValueOnce(response) + await expect( + ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_foreign'], + ['to', 'term_coord'], + ['subject', 'done'], + ['type', 'worker_done'], + ['outcome', 'succeeded'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: false + } as never) + ).rejects.toMatchObject({ + code: 'sender_not_assignee', + message: 'dispatch ctx_1 expected the assigned pane' + }) + expect(printResult).not.toHaveBeenCalled() +}) + +it('raises a Run-home relay rejection for the CLI error boundary', async () => { + callMock.mockResolvedValueOnce({ + result: { + relay: { + messageId: 'relay_rejected', + sequence: 1, + dispatchId: 'ctx_1', + destination: 'run_home', + accepted: true + }, + lifecycle: { + action: 'rejected', + code: 'task_dispatch_mismatch', + reason: 'wrong task', + authority: 'run_home' + } + } + }) + + await expect( + ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'done'], + ['type', 'worker_done'], + ['task-id', 'task_wrong'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'succeeded'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + ).rejects.toMatchObject({ code: 'task_dispatch_mismatch', message: 'wrong task' }) + expect(printResult).not.toHaveBeenCalled() +}) + +it('accepts an explicit current settlement without a compatibility read', async () => { + callMock.mockResolvedValueOnce({ + result: { message: { id: 'msg_done' }, lifecycle: { action: 'completed' } } + }) + await ORCHESTRATION_HANDLERS['orchestration send']({ flags: new Map([ - ['from', 'term_foreign'], - ['to', 'term_coord'], + ['from', 'term_worker'], ['subject', 'done'], ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], ['outcome', 'succeeded'] ]), client: { call: callMock }, cwd: '/tmp/repo', - json: false + json: true } as never) - expect(process.exitCode).toBe(1) - const formatter = vi.mocked(printResult).mock.calls[0]?.[2] - expect(formatter?.(response.result)).toBe( - 'Rejected msg_rejected: dispatch ctx_1 expected the assigned pane' - ) + expect(callMock).toHaveBeenCalledOnce() +}) + +it('fails closed when an older runtime leaves worker_done dispatched without a verdict', async () => { + callMock + .mockResolvedValueOnce({ + result: { message: { id: 'msg_unconfirmed', run_id: 'run_1' } } + }) + .mockResolvedValueOnce({ + result: { dispatch: { id: 'ctx_1', status: 'dispatched' } } + }) + .mockResolvedValueOnce({ result: { tasks: [] } }) + + await expect( + ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_foreign'], + ['subject', 'done'], + ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'succeeded'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + ).rejects.toMatchObject({ code: 'operation_unknown' }) + + expect(callMock).toHaveBeenNthCalledWith(2, 'orchestration.dispatchShow', { task: 'task_1' }) + expect(callMock).toHaveBeenNthCalledWith(3, 'orchestration.taskList', { + status: 'completed', + run: 'run_1' + }) +}) + +it('normalizes compatibility-read failures to operation_unknown', async () => { + callMock + .mockResolvedValueOnce({ + result: { message: { id: 'msg_unconfirmed', run_id: 'run_1' } } + }) + .mockRejectedValueOnce(new Error('runtime disconnected')) + .mockResolvedValueOnce({ result: { tasks: [] } }) + + await expect( + ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'done'], + ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'succeeded'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + ).rejects.toMatchObject({ code: 'operation_unknown' }) +}) + +it('accepts a legacy response only after the authoritative dispatch is terminal', async () => { + callMock + .mockResolvedValueOnce({ + result: { message: { id: 'msg_legacy_completed', run_id: 'run_1' } } + }) + .mockResolvedValueOnce({ + result: { dispatch: { id: 'ctx_1', status: 'completed' } } + }) + .mockResolvedValueOnce({ + result: { + tasks: [ + { + id: 'task_1', + status: 'completed', + result: JSON.stringify({ + provenance: 'worker_report', + messageId: 'msg_legacy_completed', + outcome: 'succeeded' + }) + } + ] + } + }) + + await ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'done'], + ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'succeeded'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + + expect(callMock).toHaveBeenCalledTimes(3) + expect(callMock).toHaveBeenNthCalledWith(2, 'orchestration.dispatchShow', { task: 'task_1' }) +}) + +it('accepts a legacy failed report only after the authoritative dispatch failed', async () => { + callMock + .mockResolvedValueOnce({ + result: { message: { id: 'msg_legacy_failed', run_id: 'run_1' } } + }) + .mockResolvedValueOnce({ result: { dispatch: { id: 'ctx_1', status: 'failed' } } }) + .mockResolvedValueOnce({ + result: { + tasks: [ + { + id: 'task_1', + status: 'failed', + result: JSON.stringify({ + provenance: 'worker_report', + messageId: 'msg_legacy_failed', + outcome: 'failed' + }) + } + ] + } + }) + + await ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'failed'], + ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'failed'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + + expect(callMock).toHaveBeenCalledTimes(3) +}) + +it('accepts an idempotent retry whose first report already settled', async () => { + callMock + .mockResolvedValueOnce({ + result: { + message: { id: 'msg_retry', run_id: 'run_1', from_handle: 'term_worker' } + } + }) + .mockResolvedValueOnce({ result: { dispatch: { id: 'ctx_1', status: 'completed' } } }) + .mockResolvedValueOnce({ + result: { + tasks: [ + { + id: 'task_1', + status: 'completed', + result: JSON.stringify({ + provenance: 'worker_report', + messageId: 'msg_first', + reportedBy: 'term_worker', + outcome: 'succeeded' + }) + } + ] + } + }) + + await ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'done'], + ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'succeeded'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + + expect(callMock).toHaveBeenCalledTimes(3) +}) + +it('rejects an unrelated failed Dispatch that left its Task blocked', async () => { + callMock + .mockResolvedValueOnce({ + result: { message: { id: 'msg_after_stop', run_id: 'run_1' } } + }) + .mockResolvedValueOnce({ result: { dispatch: { id: 'ctx_1', status: 'failed' } } }) + .mockResolvedValueOnce({ result: { tasks: [] } }) + + await expect( + ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'failed'], + ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'failed'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + ).rejects.toMatchObject({ code: 'operation_unknown' }) +}) + +it('rejects a terminal Dispatch with the wrong identity', async () => { + callMock + .mockResolvedValueOnce({ + result: { message: { id: 'msg_stale', run_id: 'run_1' } } + }) + .mockResolvedValueOnce({ + result: { dispatch: { id: 'ctx_replacement', status: 'completed' } } + }) + .mockResolvedValueOnce({ + result: { + tasks: [ + { + id: 'task_1', + status: 'completed', + result: JSON.stringify({ + provenance: 'worker_report', + messageId: 'msg_stale', + outcome: 'succeeded' + }) + } + ] + } + }) + + await expect( + ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'done'], + ['type', 'worker_done'], + ['task-id', 'task_1'], + ['dispatch-id', 'ctx_1'], + ['outcome', 'succeeded'] + ]), + client: { call: callMock }, + cwd: '/tmp/repo', + json: true + } as never) + ).rejects.toMatchObject({ code: 'operation_unknown' }) }) diff --git a/src/cli/handlers/orchestration-migration.test.ts b/src/cli/handlers/orchestration-migration.test.ts index a1a117b90b3..863720eaab1 100644 --- a/src/cli/handlers/orchestration-migration.test.ts +++ b/src/cli/handlers/orchestration-migration.test.ts @@ -12,33 +12,43 @@ afterEach(() => { }) describe('orchestration CLI migration recovery', () => { - it('forwards legacy worker_done without inventing a completion outcome', async () => { - process.env.ORCA_PANE_KEY = 'tab-worker:leaf-worker' - const call = vi.fn().mockResolvedValue({ result: { message: { id: 'msg_done' } } }) + it.each([false, true])( + 'accepts an attested legacy worker_done settlement (replayed: %s)', + async (replayed) => { + process.env.ORCA_PANE_KEY = 'tab-worker:leaf-worker' + const call = vi.fn().mockResolvedValue({ + result: { + message: { id: 'msg_done' }, + lifecycle: { action: 'settled', outcome: 'succeeded', duplicate: replayed } + } + }) - await ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_worker'], - ['subject', 'Done'], - ['type', 'worker_done'] - ]), - client: { call }, - cwd: '/tmp/repo', - json: true - } as never) + await ORCHESTRATION_HANDLERS['orchestration send']({ + flags: new Map([ + ['from', 'term_worker'], + ['subject', 'Done'], + ['type', 'worker_done'] + ]), + client: { call }, + cwd: '/tmp/repo', + json: true + } as never) - expect(call).toHaveBeenCalledWith('orchestration.send', { - from: 'term_worker', - to: undefined, - run: undefined, - subject: 'Done', - body: undefined, - type: 'worker_done', - priority: undefined, - threadId: undefined, - payload: undefined, - senderPaneKey: 'tab-worker:leaf-worker', - devMode: false - }) - }) + expect(call).toHaveBeenCalledWith('orchestration.send', { + from: 'term_worker', + to: undefined, + run: undefined, + subject: 'Done', + body: undefined, + type: 'worker_done', + priority: undefined, + threadId: undefined, + payload: undefined, + senderPaneKey: 'tab-worker:leaf-worker', + waitForLifecycleSettlement: true, + devMode: false + }) + expect(call).toHaveBeenCalledOnce() + } + ) }) diff --git a/src/cli/handlers/orchestration-worker-settlement.ts b/src/cli/handlers/orchestration-worker-settlement.ts new file mode 100644 index 00000000000..8b9425391ee --- /dev/null +++ b/src/cli/handlers/orchestration-worker-settlement.ts @@ -0,0 +1,147 @@ +import type { RuntimeClient } from '../runtime-client' +import { RuntimeClientError } from '../runtime-client' + +export async function requireWorkerDoneSettlement( + client: RuntimeClient, + type: string | undefined, + payload: string | undefined, + result: unknown +): Promise { + if (type !== 'worker_done' || hasLifecycleVerdict(result)) { + return + } + const target = parseWorkerDoneTarget(payload) + const receipt = parseWorkerDoneReceipt(result) + if (target && receipt) { + const [dispatchVerification, taskVerification] = await Promise.all([ + client.call<{ dispatch: { id: string; status: string } | null }>( + 'orchestration.dispatchShow', + { task: target.taskId } + ), + client.call<{ + tasks: { id: string; status: string; result: string | null }[] + }>('orchestration.taskList', { status: target.expectedStatus, run: receipt.runId }) + ]).catch(() => { + throw workerDoneSettlementUnknown() + }) + const task = taskVerification.result.tasks.find((candidate) => candidate.id === target.taskId) + if ( + dispatchVerification.result.dispatch?.id === target.dispatchId && + dispatchVerification.result.dispatch.status === target.expectedStatus && + task?.status === target.expectedStatus && + isExactWorkerReport(task.result, receipt, target.outcome) + ) { + return + } + } + throw workerDoneSettlementUnknown() +} + +function workerDoneSettlementUnknown(): RuntimeClientError { + return new RuntimeClientError( + 'operation_unknown', + 'The runtime accepted worker_done but did not confirm that the exact report settled its Task and Dispatch. Retry from the assigned worker after verifying its active Dispatch.' + ) +} + +function parseWorkerDoneReceipt( + result: unknown +): { messageId: string; runId: string; fromHandle?: string } | undefined { + if (!result || typeof result !== 'object' || !('message' in result)) { + return undefined + } + const message = (result as { message?: unknown }).message + if (!message || typeof message !== 'object') { + return undefined + } + const { + id, + run_id: runId, + from_handle: fromHandle + } = message as { + id?: unknown + run_id?: unknown + from_handle?: unknown + } + return typeof id === 'string' && typeof runId === 'string' + ? { + messageId: id, + runId, + ...(typeof fromHandle === 'string' ? { fromHandle } : {}) + } + : undefined +} + +function isExactWorkerReport( + result: string | null | undefined, + receipt: { messageId: string; fromHandle?: string }, + outcome: 'succeeded' | 'failed' +): boolean { + if (!result) { + return false + } + try { + const parsed = JSON.parse(result) as Record + return ( + parsed.provenance === 'worker_report' && + parsed.outcome === outcome && + (parsed.messageId === receipt.messageId || + (receipt.fromHandle !== undefined && parsed.reportedBy === receipt.fromHandle)) + ) + } catch { + return false + } +} + +function hasLifecycleVerdict(result: unknown): boolean { + if (!result || typeof result !== 'object' || !('lifecycle' in result)) { + return false + } + const lifecycle = (result as { lifecycle?: unknown }).lifecycle + if (!lifecycle || typeof lifecycle !== 'object') { + return false + } + const action = (lifecycle as { action?: unknown }).action + if ('relay' in result) { + return ( + (lifecycle as { authority?: unknown }).authority === 'run_home' && + (action === 'completed' || action === 'failed' || action === 'rejected') + ) + } + if (action === 'settled') { + const outcome = (lifecycle as { outcome?: unknown }).outcome + return outcome === 'succeeded' || outcome === 'failed' + } + return action === 'completed' || action === 'failed' || action === 'rejected' +} + +function parseWorkerDoneTarget(payload: string | undefined): + | { + taskId: string + dispatchId: string + outcome: 'succeeded' | 'failed' + expectedStatus: 'completed' | 'failed' + } + | undefined { + if (!payload) { + return undefined + } + try { + const parsed = JSON.parse(payload) as Record + if ( + typeof parsed.taskId !== 'string' || + typeof parsed.dispatchId !== 'string' || + (parsed.outcome !== 'succeeded' && parsed.outcome !== 'failed') + ) { + return undefined + } + return { + taskId: parsed.taskId, + dispatchId: parsed.dispatchId, + outcome: parsed.outcome, + expectedStatus: parsed.outcome === 'succeeded' ? 'completed' : 'failed' + } + } catch { + return undefined + } +} diff --git a/src/cli/handlers/orchestration.test.ts b/src/cli/handlers/orchestration.test.ts index ef7299efb43..c43f7b45b62 100644 --- a/src/cli/handlers/orchestration.test.ts +++ b/src/cli/handlers/orchestration.test.ts @@ -50,7 +50,7 @@ afterEach(() => { describe('orchestration send structured payload flags', () => { beforeEach(() => { - callMock.mockReset().mockResolvedValue({ result: { message: { id: 'msg_1' } } }) + callMock.mockReset().mockResolvedValue({ result: { lifecycle: { action: 'completed' } } }) getTerminalHandleMock.mockReset() delete process.env.ORCA_TERMINAL_HANDLE delete process.env.ORCA_PANE_KEY @@ -94,6 +94,7 @@ describe('orchestration send structured payload flags', () => { filesModified: ['src/a.ts', 'src/b.ts'], reportPath: 'reports/done.md' }), + waitForLifecycleSettlement: true, devMode: false }) }) @@ -207,6 +208,7 @@ describe('orchestration send structured payload flags', () => { priority: undefined, threadId: undefined, payload: JSON.stringify({ outcome: 'succeeded' }), + waitForLifecycleSettlement: true, devMode: false }) }) @@ -233,6 +235,7 @@ describe('orchestration send structured payload flags', () => { priority: undefined, threadId: undefined, payload: JSON.stringify({ outcome: 'succeeded' }), + waitForLifecycleSettlement: true, devMode: false }) }) diff --git a/src/cli/handlers/orchestration.ts b/src/cli/handlers/orchestration.ts index 5be6e62394d..771b8367b88 100644 --- a/src/cli/handlers/orchestration.ts +++ b/src/cli/handlers/orchestration.ts @@ -8,6 +8,7 @@ import { getRequiredStringFlag } from '../flags' import { RuntimeClientError } from '../runtime-client' +import { requireWorkerDoneSettlement } from './orchestration-worker-settlement' import { getTerminalHandle } from '../selectors' import { clampOrchestrationAskTimeoutMs, @@ -90,14 +91,13 @@ const WORKER_TERMINAL_LIST_STATES = [ 'released' ] as const -type LifecycleSendRejection = { - action: 'rejected' - code: string - reason: string -} +type LifecycleSendResult = + | { action: 'completed' | 'failed'; authority?: 'run_home' } + | { action: 'settled'; outcome: 'succeeded' | 'failed'; duplicate?: boolean } + | { action: 'rejected'; code: string; reason: string } type OrchestrationSendResult = - | { message: { id: string }; lifecycle?: LifecycleSendRejection } + | { message: { id: string; run_id?: string }; lifecycle?: LifecycleSendResult } | { messages: { id: string }[]; recipients: number } | { relay: { @@ -107,7 +107,7 @@ type OrchestrationSendResult = destination?: 'run_home' | 'worker' accepted: true } - lifecycle?: { action: 'completed' | 'failed' } + lifecycle?: LifecycleSendResult } function resolveCompatibilityCliCommand(): 'orca' | 'orca-ide' | 'orca-dev' { @@ -579,6 +579,7 @@ export const ORCHESTRATION_HANDLERS: Record = { payload: getOptionalStructuredMessagePayload(flags), // Why: pane key is the remint-stable sender identity the runtime verifies lifecycle ownership against; older runtimes strip it. senderPaneKey: process.env.ORCA_PANE_KEY || undefined, + waitForLifecycleSettlement: type === 'worker_done' ? true : undefined, devMode: isDevCliInvocation() } const dispatchCapability = getOptionalStringFlag(flags, 'dispatch-capability') @@ -589,15 +590,12 @@ export const ORCHESTRATION_HANDLERS: Record = { sendParams, dispatchCapability ? { orchestrationCapability: dispatchCapability } : undefined ) - if ('message' in result.result && result.result.lifecycle?.action === 'rejected') { - // Why: a rejected lifecycle signal isn't completion; non-zero exit stops workers from treating it as such. - process.exitCode = 1 + await requireWorkerDoneSettlement(client, type, sendParams.payload, result.result) + if ('lifecycle' in result.result && result.result.lifecycle?.action === 'rejected') { + throw new RuntimeClientError(result.result.lifecycle.code, result.result.lifecycle.reason) } printResult(result, json, (r) => { if ('message' in r) { - if (r.lifecycle?.action === 'rejected') { - return `Rejected ${r.message.id}: ${r.lifecycle.reason}` - } return `Sent ${r.message.id}` } if ('relay' in r) { diff --git a/src/cli/handlers/terminal.test.ts b/src/cli/handlers/terminal.test.ts index 7dadf41c2d3..8c5ff460c77 100644 --- a/src/cli/handlers/terminal.test.ts +++ b/src/cli/handlers/terminal.test.ts @@ -61,3 +61,67 @@ describe('terminal close CLI', () => { expect(help).toContain('durable persistence') }) }) + +describe('terminal split CLI', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + it('sends the old-host attribution bypass through the legacy-compatible env field', async () => { + const call = vi.fn(async (method: string) => + method === 'status.get' + ? { + result: { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + } + } + : { result: { split: { handle: 'term-2', parentHandle: 'term-1' } } } + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await TERMINAL_HANDLERS['terminal split']({ + flags: new Map([ + ['terminal', 'term-1'], + ['direction', 'horizontal'] + ]), + client: { call } as unknown as RuntimeClient, + cwd: '/tmp/worktree', + json: true + }) + + expect(call).toHaveBeenNthCalledWith(1, 'status.get') + expect(call).toHaveBeenNthCalledWith( + 2, + 'terminal.split', + { + terminal: 'term-1', + direction: 'horizontal', + command: undefined, + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'] + }, + { expectedRuntimeId: 'runtime-1' } + ) + }) + + it('refuses legacy hosts because renderer-owned splits discard environment fields', async () => { + const call = vi.fn().mockResolvedValue({ + result: { appVersion: '1.4.181', capabilities: ['mobile.tasks.v1'] } + }) + + await expect( + TERMINAL_HANDLERS['terminal split']({ + flags: new Map([['terminal', 'term-1']]), + client: { call } as unknown as RuntimeClient, + cwd: '/tmp/worktree', + json: true + }) + ).rejects.toMatchObject({ + code: 'runtime_update_required', + message: expect.stringContaining('Update the host and try again') + }) + expect(call).toHaveBeenCalledTimes(1) + expect(call).not.toHaveBeenCalledWith('terminal.split', expect.anything()) + }) +}) diff --git a/src/cli/handlers/terminal.ts b/src/cli/handlers/terminal.ts index 551ab8d95c1..677cdc81034 100644 --- a/src/cli/handlers/terminal.ts +++ b/src/cli/handlers/terminal.ts @@ -8,7 +8,8 @@ import type { RuntimeTerminalSend, RuntimeTerminalShow, RuntimeTerminalSplit, - RuntimeTerminalWait + RuntimeTerminalWait, + RuntimeStatus } from '../../shared/runtime-types' import type { CommandHandler } from '../dispatch' import { shouldUseRendererBackedInteractiveTerminal } from '../codex-command-classification' @@ -37,6 +38,14 @@ import { getRequiredWorktreeSelector, getTerminalHandle } from '../selectors' +import { + addLegacyTerminalAttributionDisableRequest, + hostSupportsTerminalCreateAttributionDisable, + hostSupportsTerminalSplitAttributionDisable, + TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE, + TERMINAL_SPLIT_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE, + withLegacyTerminalAttributionDisabledEnv +} from '../../shared/legacy-terminal-attribution-env' // Why: terminal wait legitimately needs to outlive the CLI's default RPC // timeout. Even without an explicit server timeout, the client must allow @@ -137,17 +146,30 @@ export const TERMINAL_HANDLERS: Record = { const useRendererBackedInteractiveTerminal = !client.isRemote && shouldUseRendererBackedInteractiveTerminal(command) const focus = flags.get('focus') === true - const result = await client.call<{ terminal: RuntimeTerminalCreate }>('terminal.create', { - worktree: await getBrowserWorktreeSelector(flags, cwd, client), - command, - title: getOptionalStringFlag(flags, 'title'), - // Why: interactive local agent TUIs need the renderer-backed terminal - // path for browser-side features, but CLI creates must stay backgrounded - // unless the caller explicitly asks for focus. - focus, - ...(focus ? { presentation: 'focused' } : {}), - ...(useRendererBackedInteractiveTerminal ? { rendererBacked: true, activate: focus } : {}) - }) + const status = await client.call('status.get') + if (!hostSupportsTerminalCreateAttributionDisable(status.result)) { + throw new RuntimeClientError( + 'runtime_update_required', + TERMINAL_CREATE_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE + ) + } + const result = await client.call<{ terminal: RuntimeTerminalCreate }>( + 'terminal.create', + { + worktree: await getBrowserWorktreeSelector(flags, cwd, client), + command, + env: withLegacyTerminalAttributionDisabledEnv(undefined), + envToDelete: addLegacyTerminalAttributionDisableRequest(undefined), + title: getOptionalStringFlag(flags, 'title'), + // Why: interactive local agent TUIs need the renderer-backed terminal + // path for browser-side features, but CLI creates must stay backgrounded + // unless the caller explicitly asks for focus. + focus, + ...(focus ? { presentation: 'focused' } : {}), + ...(useRendererBackedInteractiveTerminal ? { rendererBacked: true, activate: focus } : {}) + }, + { expectedRuntimeId: status.result.runtimeId } + ) printResult(result, json, formatTerminalCreate) }, // `focus` resolves to this canonical path via CommandSpec.aliases before dispatch. @@ -168,11 +190,24 @@ export const TERMINAL_HANDLERS: Record = { ) { throw new RuntimeClientError('invalid_argument', '--direction must be horizontal or vertical') } - const result = await client.call<{ split: RuntimeTerminalSplit }>('terminal.split', { - terminal: await getTerminalHandle(flags, cwd, client), - direction: directionFlag, - command: getOptionalStringFlag(flags, 'command') - }) + const status = await client.call('status.get') + if (!hostSupportsTerminalSplitAttributionDisable(status.result)) { + throw new RuntimeClientError( + 'runtime_update_required', + TERMINAL_SPLIT_ATTRIBUTION_UPDATE_REQUIRED_MESSAGE + ) + } + const result = await client.call<{ split: RuntimeTerminalSplit }>( + 'terminal.split', + { + terminal: await getTerminalHandle(flags, cwd, client), + direction: directionFlag, + command: getOptionalStringFlag(flags, 'command'), + env: withLegacyTerminalAttributionDisabledEnv(undefined), + envToDelete: addLegacyTerminalAttributionDisableRequest(undefined) + }, + { expectedRuntimeId: status.result.runtimeId } + ) printResult(result, json, formatTerminalSplit) } } diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 4867aebc29b..2f86ee9583f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -3112,6 +3112,10 @@ describe('orca cli worktree awareness', () => { it('passes explicit focus through terminal.create', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3136,13 +3140,19 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: undefined, - title: 'RUNNER', - focus: true, - presentation: 'focused' - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: undefined, + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'RUNNER', + focus: true, + presentation: 'focused' + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('prints terminal.read fallback screen lines in json mode', async () => { @@ -3184,6 +3194,10 @@ describe('orca cli worktree awareness', () => { it('keeps interactive Codex startup commands backgrounded unless focus is explicit', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3209,19 +3223,29 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'codex', - title: 'Codex', - focus: false, - rendererBacked: true, - activate: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'codex', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex', + focus: false, + rendererBacked: true, + activate: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('keeps explicit focus semantics when forcing Codex through the renderer path', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3248,20 +3272,30 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'codex', - title: 'Codex', - focus: true, - presentation: 'focused', - rendererBacked: true, - activate: true - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'codex', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex', + focus: true, + presentation: 'focused', + rendererBacked: true, + activate: true + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('does not force the visible terminal path for explicit Codex exec commands', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3287,17 +3321,27 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'codex exec summarize', - title: 'Codex exec', - focus: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'codex exec summarize', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex exec', + focus: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('does not force the visible terminal path for Codex exec commands after global options', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3323,17 +3367,27 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'codex -m gpt-5 --sandbox workspace-write exec summarize', - title: 'Codex exec', - focus: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'codex -m gpt-5 --sandbox workspace-write exec summarize', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex exec', + focus: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('does not force the visible terminal path for Codex review commands after long options', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3359,17 +3413,27 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'codex --model=gpt-5 --sandbox=workspace-write review', - title: 'Codex review', - focus: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'codex --model=gpt-5 --sandbox=workspace-write review', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex review', + focus: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('does not force the visible terminal path for Codex help commands', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3395,17 +3459,27 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'codex --help', - title: 'Codex help', - focus: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'codex --help', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex help', + focus: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('keeps Codex prompts after global options backgrounded unless focus is explicit', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3431,19 +3505,29 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'codex -m gpt-5 "fix the flaky test"', - title: 'Codex prompt', - focus: false, - rendererBacked: true, - activate: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'codex -m gpt-5 "fix the flaky test"', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex prompt', + focus: false, + rendererBacked: true, + activate: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('keeps interactive Claude startup commands backgrounded unless focus is explicit', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3469,19 +3553,29 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'claude', - title: 'Claude', - focus: false, - rendererBacked: true, - activate: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'claude', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Claude', + focus: false, + rendererBacked: true, + activate: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('keeps Claude print commands on the background terminal path', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3507,12 +3601,18 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'path:/tmp/repo/feature', - command: 'claude -p "summarize"', - title: 'Claude print', - focus: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'path:/tmp/repo/feature', + command: 'claude -p "summarize"', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Claude print', + focus: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('uses the resolved enclosing worktree for other worktree consumers', async () => { @@ -3819,6 +3919,10 @@ describe('orca cli worktree awareness', () => { it('sends explicit remote terminal create worktree selectors unchanged', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3842,12 +3946,18 @@ describe('orca cli worktree awareness', () => { '/tmp/client/repo/src' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'id:repo-1::/srv/orca/feature', - command: undefined, - title: undefined, - focus: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'id:repo-1::/srv/orca/feature', + command: undefined, + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: undefined, + focus: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('collects and formats memory diagnostics', async () => { @@ -3955,6 +4065,10 @@ describe('orca cli worktree awareness', () => { it('does not force remote Codex terminal creates through a local renderer path', async () => { queueFixtures( callMock, + okFixture('req_status', { + runtimeId: 'runtime-1', + capabilities: ['terminal.attribution-removed.v1'] + }), okFixture('req_terminal_create', { terminal: { handle: 'term_1', @@ -3982,12 +4096,18 @@ describe('orca cli worktree awareness', () => { '/tmp/client/repo/src' ) - expect(callMock).toHaveBeenCalledWith('terminal.create', { - worktree: 'id:repo-1::/srv/orca/feature', - command: 'codex', - title: 'Codex', - focus: false - }) + expect(callMock).toHaveBeenCalledWith( + 'terminal.create', + { + worktree: 'id:repo-1::/srv/orca/feature', + command: 'codex', + env: { ORCA_ATTRIBUTION_BYPASS: '1' }, + envToDelete: ['ORCA_ENABLE_GIT_ATTRIBUTION'], + title: 'Codex', + focus: false + }, + { expectedRuntimeId: 'runtime-1' } + ) }) it('does not resolve implicit remote browser targets from client cwd', async () => { diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index 3a8951de554..b6c49ff7c22 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -87,6 +87,7 @@ export class RuntimeClient { } : {} const envelope = { + expectedRuntimeId: options?.expectedRuntimeId, orchestrationCapability: options?.orchestrationCapability, orchestrationContractVersion: method.startsWith('orchestration.') ? ORCHESTRATION_CONTRACT_VERSION diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.ts index 8de35f619e5..7858d6cd131 100644 --- a/src/cli/runtime/transport.test.ts +++ b/src/cli/runtime/transport.test.ts @@ -50,6 +50,48 @@ describe('runtime transport timeout validation', () => { // Why: these tests create Unix domain socket servers in temp directories. // Windows does not support Unix domain sockets in the same way. describe.skipIf(process.platform === 'win32')('runtime transport', () => { + it('forwards the expected runtime fence in local requests', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-')) + const endpoint = join(userDataPath, 'runtime.sock') + let receivedRequest: Record | null = null + const server = createServer((socket) => { + sockets.add(socket) + socket.once('close', () => sockets.delete(socket)) + socket.once('data', (data) => { + receivedRequest = JSON.parse(String(data).trim()) as Record + socket.write( + `${JSON.stringify({ + id: receivedRequest.id, + ok: true, + result: { terminal: { handle: 'terminal-1' } }, + _meta: { runtimeId: 'runtime-1' } + })}\n` + ) + }) + }) + servers.add(server) + await new Promise((resolve) => server.listen(endpoint, resolve)) + + await sendRequest( + { + runtimeId: 'runtime-1', + pid: 123, + transports: [{ kind: 'unix', endpoint }], + authToken: 'token', + startedAt: 1 + }, + 'terminal.create', + { worktree: 'id:worktree-1' }, + 1_000, + { expectedRuntimeId: 'runtime-1' } + ) + + expect(receivedRequest).toMatchObject({ + method: 'terminal.create', + expectedRuntimeId: 'runtime-1' + }) + }) + it('refreshes the per-call timeout when the runtime sends keepalive frames', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-')) const endpoint = join(userDataPath, 'runtime.sock') diff --git a/src/cli/runtime/transport.ts b/src/cli/runtime/transport.ts index 091ca9da0e0..998052dc4b6 100644 --- a/src/cli/runtime/transport.ts +++ b/src/cli/runtime/transport.ts @@ -186,6 +186,7 @@ export async function sendRequest( authToken: metadata.authToken, method, params, + expectedRuntimeId: envelope?.expectedRuntimeId, orchestrationCapability: envelope?.orchestrationCapability, orchestrationContractVersion: envelope?.orchestrationContractVersion, orchestrationRequestId: envelope?.orchestrationRequestId, diff --git a/src/cli/selectors.ts b/src/cli/selectors.ts index 3729b8598a7..aef583ad0ac 100644 --- a/src/cli/selectors.ts +++ b/src/cli/selectors.ts @@ -237,6 +237,14 @@ export async function getEmulatorWorktreeSelector( if (client.isRemote) { return undefined } + const terminalWorktreeId = process.env.ORCA_WORKTREE_ID + if (terminalWorktreeId?.trim()) { + return terminalWorktreeId + } + const folderWorkspaceId = process.env.ORCA_WORKSPACE_ID?.trim() + if (folderWorkspaceId?.startsWith('folder:')) { + return folderWorkspaceId + } try { return await resolveCurrentWorktreeSelector(cwd, client) } catch { diff --git a/src/main/agent-hooks/installer-utils-remote.ts b/src/main/agent-hooks/installer-utils-remote.ts index aa7e47d258a..b4518220e90 100644 --- a/src/main/agent-hooks/installer-utils-remote.ts +++ b/src/main/agent-hooks/installer-utils-remote.ts @@ -8,8 +8,6 @@ // We deliberately keep the JSON merge logic in the existing // `installer-utils.ts` and only swap fs primitives — the JSON shape and // managed-command matching must stay identical to the local install. -// -// See docs/design/agent-status-over-ssh.md §8 (commit #8). import { randomUUID } from 'node:crypto' import type { SFTPWrapper, FileEntryWithStats } from 'ssh2' @@ -83,9 +81,9 @@ export async function writeHooksJsonRemote( } } -/** Write the managed hook script to the remote and chmod 0o755. POSIX-only — - * the relay deliberately does not support Windows-remote in v1 (see design - * doc §3 + §6). */ +/** Write the managed hook script to the remote and chmod 0o755. POSIX-only: + * the payload is a shell script and every path here is POSIX-joined, so a + * Windows SSH target would need a separate installer, not a tweak to this one. */ export async function writeManagedScriptRemote( sftp: SFTPWrapper, remotePath: string, diff --git a/src/main/agent-hooks/managed-hook-local-filesystem.test.ts b/src/main/agent-hooks/managed-hook-local-filesystem.test.ts index f6dcf14471a..3213ee0210e 100644 --- a/src/main/agent-hooks/managed-hook-local-filesystem.test.ts +++ b/src/main/agent-hooks/managed-hook-local-filesystem.test.ts @@ -2,7 +2,10 @@ import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import { + installRemoteManagedAgentHooks, + REMOTE_MANAGED_HOOK_INSTALLER_AGENTS +} from './remote-managed-hook-installers' import { createManagedHookLocalFilesystem } from './managed-hook-local-filesystem' const tempHomes: string[] = [] @@ -34,7 +37,10 @@ describe('managed-hook local filesystem', () => { it('supports cold and warm aggregate installs without SFTP or temp-file residue', async () => { const home = await createTempHome() const filesystem = createManagedHookLocalFilesystem() - const options = { grokHomeDir: join(home, '.grok') } + const options = { + grokHomeDir: join(home, '.grok'), + agents: REMOTE_MANAGED_HOOK_INSTALLER_AGENTS + } const cold = await installRemoteManagedAgentHooks(filesystem, home, options) const warm = await installRemoteManagedAgentHooks(filesystem, home, options) @@ -61,7 +67,8 @@ describe('managed-hook local filesystem', () => { await writeFile(claudeConfig, '{"hooks": }', 'utf8') const results = await installRemoteManagedAgentHooks(createManagedHookLocalFilesystem(), home, { - grokHomeDir: join(home, '.grok') + grokHomeDir: join(home, '.grok'), + agents: REMOTE_MANAGED_HOOK_INSTALLER_AGENTS }) expect(results).toHaveLength(14) diff --git a/src/main/agent-hooks/managed-hook-owner-identity.ts b/src/main/agent-hooks/managed-hook-owner-identity.ts index 7f60956e6e4..51f299595cd 100644 --- a/src/main/agent-hooks/managed-hook-owner-identity.ts +++ b/src/main/agent-hooks/managed-hook-owner-identity.ts @@ -32,7 +32,7 @@ function hasCode(error: unknown, code: string): boolean { export function parseLinuxStartTicks(statLine: string): string | null { const commandEnd = statLine.lastIndexOf(')') - if (commandEnd < 0) { + if (commandEnd === -1) { return null } // Field 22 is index 19 after removing pid and the parenthesized command. diff --git a/src/main/agent-hooks/managed-hook-runtime.test.ts b/src/main/agent-hooks/managed-hook-runtime.test.ts index 456a741df87..e4c23e13959 100644 --- a/src/main/agent-hooks/managed-hook-runtime.test.ts +++ b/src/main/agent-hooks/managed-hook-runtime.test.ts @@ -1,22 +1,160 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { resolveRelayGrokHome } from './managed-hook-runtime' +import { chmod, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeChildProcess from 'node:child_process' -afterEach(() => { +// Why: the probe spawns a real login shell, and `resolveRelayGrokHome` swallows every +// spawn failure into its fallback. Left unmocked this asserts the runner's scheduling +// latency, not the parser: on a loaded sharded CI box the 8s timeout expires and the +// first case silently flips to the fallback path. +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, execFile: vi.fn() } +}) + +const { execFile } = await import('node:child_process') +const execFileMock = vi.mocked(execFile) +const { execFile: actualExecFile } = + await vi.importActual('node:child_process') +const { installManagedHooks, resolveRelayGrokHome } = await import('./managed-hook-runtime') + +type ExecFileCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void + +function stubProbeOutput(stdout: string): void { + execFileMock.mockImplementation(((...args: unknown[]) => { + ;(args.at(-1) as ExecFileCallback)(null, { stdout, stderr: '' }) + return undefined + }) as unknown as typeof execFile) +} + +function stubProbeFailure(error: Error): void { + execFileMock.mockImplementation(((...args: unknown[]) => { + ;(args.at(-1) as ExecFileCallback)(error) + return undefined + }) as unknown as typeof execFile) +} + +beforeEach(() => { + execFileMock.mockReset() + // Why: `installManagedHooks` proves a skipped probe through the login-shell run log, so the + // probe must really spawn unless a case above stubs it. The mock loses `promisify.custom`, + // so the real `(error, stdout, stderr)` callback is reshaped into the `{ stdout, stderr }` + // that `promisify(execFile)` resolves in production. + execFileMock.mockImplementation(((...args: unknown[]) => { + const callback = args.at(-1) as ExecFileCallback + return (actualExecFile as (...callArgs: unknown[]) => unknown)( + ...args.slice(0, -1), + (error: Error | null, stdout: string, stderr: string) => callback(error, { stdout, stderr }) + ) + }) as unknown as typeof execFile) +}) + +const tempHomes: string[] = [] +const tempRoot = process.platform === 'win32' ? tmpdir() : '/tmp' +const SHELL_NAME = 'login-shell' +const SHELL_RUNS_NAME = 'login-shell-runs' + +async function createTempHome(): Promise { + const home = await mkdtemp(join(tempRoot, 'orca-managed-hook-runtime-')) + tempHomes.push(home) + return home +} + +/** Login shell that records each invocation, so a skipped GROK_HOME probe is observable. */ +async function stubLoginShell(home: string): Promise { + const shell = join(home, SHELL_NAME) + await writeFile( + shell, + `#!/bin/sh\necho ran >> "${join(home, SHELL_RUNS_NAME)}"\nexit 0\n`, + 'utf8' + ) + await chmod(shell, 0o755) + vi.stubEnv('HOME', home) + vi.stubEnv('SHELL', shell) +} + +afterEach(async () => { vi.unstubAllEnvs() + await Promise.all(tempHomes.splice(0).map((home) => rm(home, { recursive: true, force: true }))) }) describe.runIf(process.platform !== 'win32')('resolveRelayGrokHome', () => { it('uses the login-shell GROK_HOME and normalizes trailing separators', async () => { vi.stubEnv('SHELL', '/bin/sh') - vi.stubEnv('GROK_HOME', '/srv/grok///') + stubProbeOutput('/srv/grok///\n') await expect(resolveRelayGrokHome('/home/orca')).resolves.toBe('/srv/grok') + + const [shell, args] = execFileMock.mock.calls[0] ?? [] + expect(shell).toBe('/bin/sh') + // `sh`/`dash` reject `-lc`, so the mode choice is part of the contract under test. + expect(args?.[0]).toBe('-c') + }) + + it('passes -lc to a login shell that supports it', async () => { + vi.stubEnv('SHELL', '/bin/zsh') + stubProbeOutput('/srv/grok\n') + + await expect(resolveRelayGrokHome('/home/orca')).resolves.toBe('/srv/grok') + + const [shell, args] = execFileMock.mock.calls[0] ?? [] + expect(shell).toBe('/bin/zsh') + expect(args?.[0]).toBe('-lc') }) it('falls back when the login-shell GROK_HOME is not an absolute POSIX path', async () => { vi.stubEnv('SHELL', '/bin/sh') - vi.stubEnv('GROK_HOME', '../relative') + stubProbeOutput('../relative\n') + + await expect(resolveRelayGrokHome('/home/orca')).resolves.toBe('/home/orca/.grok') + }) + + // Why: this is the branch that made the old test flaky — pin it so a probe failure is + // an asserted fallback rather than an invisible substitution for a real answer. + it('falls back when the probe fails or times out', async () => { + vi.stubEnv('SHELL', '/bin/sh') + stubProbeFailure(Object.assign(new Error('spawn timed out'), { killed: true })) await expect(resolveRelayGrokHome('/home/orca')).resolves.toBe('/home/orca/.grok') }) }) + +describe.runIf(process.platform !== 'win32')('installManagedHooks', () => { + it.each([ + ['omitted', undefined], + ['empty', { agents: [] }] + ])( + 'writes nothing and runs no probe when the allowlist is %s (issue #11641)', + async (_label, options) => { + const home = await createTempHome() + await stubLoginShell(home) + + await expect(installManagedHooks(options)).resolves.toEqual({ installers: 0, errors: 0 }) + + // Why: no agent config home, no ~/.orca install lock, and no GROK_HOME login-shell probe. + expect(await readdir(home)).toEqual([SHELL_NAME]) + } + ) + + it('still rejects an aborted request rather than resolving an empty summary', async () => { + const controller = new AbortController() + controller.abort() + + await expect( + installManagedHooks({ signal: controller.signal, agents: [] }) + ).rejects.toMatchObject({ name: 'AbortError' }) + }) + + it('installs only the allowlisted agent, under the install lock', async () => { + const home = await createTempHome() + await stubLoginShell(home) + + await expect(installManagedHooks({ agents: ['claude'] })).resolves.toEqual({ + installers: 1, + errors: 0 + }) + + expect((await readdir(home)).sort()).toEqual(['.claude', '.orca', SHELL_NAME, SHELL_RUNS_NAME]) + }) +}) diff --git a/src/main/agent-hooks/managed-hook-runtime.ts b/src/main/agent-hooks/managed-hook-runtime.ts index bdd7195b50d..e995467ee7d 100644 --- a/src/main/agent-hooks/managed-hook-runtime.ts +++ b/src/main/agent-hooks/managed-hook-runtime.ts @@ -79,6 +79,11 @@ export async function installManagedHooks(options?: { agents?: readonly AgentHookTarget[] }): Promise { options?.signal?.throwIfAborted() + // Why: empty/omitted allowlist fails closed before any home/host probes. + const agents = options?.agents ?? [] + if (agents.length === 0) { + return { installers: 0, errors: 0 } + } const home = homedir() const grokHomeDir = await resolveRelayGrokHome(home, options?.signal) options?.signal?.throwIfAborted() @@ -96,7 +101,7 @@ export async function installManagedHooks(options?: { { grokHomeDir, signal: options?.signal, - agents: options?.agents + agents } ) return { diff --git a/src/main/agent-hooks/remote-hook-service-installers.test.ts b/src/main/agent-hooks/remote-hook-service-installers.test.ts index 2b2cfcdcf38..9ba01bc81c6 100644 --- a/src/main/agent-hooks/remote-hook-service-installers.test.ts +++ b/src/main/agent-hooks/remote-hook-service-installers.test.ts @@ -707,7 +707,9 @@ describe('remote hook service installers', () => { it('installs Droid and Copilot when running the aggregate remote installer (issue #7253)', async () => { const { sftp } = createFakeSftp() - const results = await installRemoteManagedAgentHooks(sftp, '/home/dev') + const results = await installRemoteManagedAgentHooks(sftp, '/home/dev', { + agents: REMOTE_MANAGED_HOOK_INSTALLER_AGENTS + }) const byAgent = new Map(results.map((r) => [r.agent, r.state])) expect(byAgent.get('droid')).toBe('installed') expect(byAgent.get('copilot')).toBe('installed') @@ -727,6 +729,19 @@ describe('remote hook service installers', () => { } }) + it('fails closed when the agent allowlist is omitted or empty (issue #11641)', async () => { + const { sftp, fs } = createFakeSftp() + + await expect(installRemoteManagedAgentHooks(sftp, '/home/dev')).resolves.toEqual([]) + await expect( + installRemoteManagedAgentHooks(sftp, '/home/dev', { agents: [] }) + ).resolves.toEqual([]) + + // Why: fake SFTP seeds '/' only; no agent config homes or files may appear. + expect([...fs.files.keys()]).toEqual([]) + expect([...fs.dirs]).toEqual(['/']) + }) + it('stops before the next installer when its relay request is cancelled', async () => { const controller = new AbortController() const claudeInstall = vi @@ -746,7 +761,10 @@ describe('remote hook service installers', () => { const { sftp } = createFakeSftp() await expect( - installRemoteManagedAgentHooks(sftp, '/home/dev', { signal: controller.signal }) + installRemoteManagedAgentHooks(sftp, '/home/dev', { + signal: controller.signal, + agents: REMOTE_MANAGED_HOOK_INSTALLER_AGENTS + }) ).rejects.toMatchObject({ name: 'AbortError' }) expect(claudeInstall).toHaveBeenCalledTimes(1) expect(openClaudeInstall).not.toHaveBeenCalled() diff --git a/src/main/agent-hooks/remote-managed-hook-installers.ts b/src/main/agent-hooks/remote-managed-hook-installers.ts index 0fdf0c47da4..6471ec5cfb4 100644 --- a/src/main/agent-hooks/remote-managed-hook-installers.ts +++ b/src/main/agent-hooks/remote-managed-hook-installers.ts @@ -26,7 +26,8 @@ export type RemoteManagedHookInstallOptions = { /** Stops before starting the next installer when the owning relay request * is cancelled. Individual filesystem mutations remain atomic. */ signal?: AbortSignal - /** Positively detected and enabled agents allowed to mutate config. */ + /** Positively detected and enabled agents allowed to mutate config. + * Required for any install: omit/empty fails closed (no config mutation). */ agents?: readonly AgentHookTarget[] } @@ -81,10 +82,15 @@ export async function installRemoteManagedAgentHooks( remoteHome: string, options?: RemoteManagedHookInstallOptions ): Promise { + // Why: omit/empty allowlist must never mean "install every agent" — that + // recreates config homes for CLIs the user never installed (issue #11641). + const allowedAgents = new Set(options?.agents ?? []) + if (allowedAgents.size === 0) { + return [] + } const results: AgentHookInstallStatus[] = [] - const allowedAgents = options?.agents ? new Set(options.agents) : null for (const [agent, install] of REMOTE_MANAGED_HOOK_INSTALLERS) { - if (allowedAgents && !allowedAgents.has(agent)) { + if (!allowedAgents.has(agent)) { continue } // Why: relay requests can disappear during reconnect; do not start more diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index e5ef70e1395..4dc64d523de 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -1,5 +1,5 @@ /* eslint-disable max-lines -- Why: this file owns the loopback HTTP adapter, the on-disk last-status persistence layer (hydrate, sanitize, TTL, atomic write, drop), and the relay ingest path in one place so the cache lifecycle (set → schedule → drain) lives next to the surfaces that mutate it. Splitting would force mutual `private` accessor scaffolding for a single class. */ -// Why: this main-process adapter keeps listener internals in shared/ (`src/shared/agent-hook-listener.ts`) so the relay can host the same pipeline without Electron. See docs/design/agent-status-over-ssh.md §5. +// Why: this main-process adapter keeps listener internals in shared/ (`src/shared/agent-hook-listener.ts`) so the relay can host the same pipeline without Electron; parsing that drifts back into this file stops applying to SSH panes. import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' import { createHash, randomBytes, randomUUID } from 'node:crypto' import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs' diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts index cb538595c19..e6a3a727fb4 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts +++ b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts @@ -11,7 +11,10 @@ import { RelayDispatcher } from '../../relay/dispatcher' import { registerWslHookFsHandlers } from '../../relay/wsl-hook-fs-bridge' import { SshChannelMultiplexer, type MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' import { createWslHookSftpAdapter } from './wsl-hook-fs-adapter' -import { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import { + installRemoteManagedAgentHooks, + REMOTE_MANAGED_HOOK_INSTALLER_AGENTS +} from './remote-managed-hook-installers' import { WslHookRelayManager } from './wsl-hook-relay-manager' import { FAILURE_COOLDOWN_BASE_MS, type WslHookRelayManagerDeps } from './wsl-hook-relay-deps' import { @@ -122,7 +125,9 @@ describe.skipIf(process.platform === 'win32')( it('runs the unchanged remote managed hook installers against a WSL guest home', async () => { const adapter = createWslHookSftpAdapter(harness.mux) - const results = await installRemoteManagedAgentHooks(adapter, home) + const results = await installRemoteManagedAgentHooks(adapter, home, { + agents: REMOTE_MANAGED_HOOK_INSTALLER_AGENTS + }) expect(results.length).toBeGreaterThan(0) expect(results.every((r) => r.state !== 'error')).toBe(true) @@ -233,13 +238,6 @@ describe('WslHookRelayManager', () => { return { manager: new WslHookRelayManager(deps), deps } } - it('exposes the stable guest endpoint instance key with a port fallback', () => { - expect(createManager({}).manager.getInstanceKey()).toBe('testinstance') - expect(createManager({ instanceKey: () => 'unsafe/key' }).manager.getInstanceKey()).toBe( - 'port43117' - ) - }) - it('starts one relay per distro, installs hooks, exposes the guest endpoint path, and forwards envelopes', async () => { const { manager, deps } = createManager({}) manager.ensureForDistro('Ubuntu') diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.ts b/src/main/agent-hooks/wsl-hook-relay-manager.ts index 828e2fa888a..74d163ca42f 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.ts +++ b/src/main/agent-hooks/wsl-hook-relay-manager.ts @@ -109,15 +109,6 @@ export class WslHookRelayManager { return this.stateFor(distro)?.opencodeOverlayDir ?? null } - getInstanceKey(): string | null { - const stableKey = sanitizeWslHookInstanceKey(this.deps.instanceKey() ?? undefined) - if (stableKey) { - return stableKey - } - const port = Number(this.deps.hookCoordsEnv().ORCA_AGENT_HOOK_PORT ?? '') - return Number.isInteger(port) && port > 0 ? `port${port}` : null - } - /** Kills every live relay. Non-permanent (hooks switched off mid-session) leaves the * manager reusable, so re-enabling hooks can start relays again without an app restart. */ disposeAll({ permanent = true }: { permanent?: boolean } = {}): void { @@ -181,7 +172,8 @@ export class WslHookRelayManager { } // Why: restart-stable instance identity keeps the guest endpoint file at // ONE path across restarts so daemon-surviving agents re-coordinate. - const instanceKey = this.getInstanceKey() ?? `port${port}` + const instanceKey = + sanitizeWslHookInstanceKey(this.deps.instanceKey() ?? undefined) ?? `port${port}` if (existing) { this.recovery.clearTimers(existing) } diff --git a/src/main/ai-vault/remote-session-file-stat.ts b/src/main/ai-vault/remote-session-file-stat.ts index aa5809a776d..57e6d2c8ed6 100644 --- a/src/main/ai-vault/remote-session-file-stat.ts +++ b/src/main/ai-vault/remote-session-file-stat.ts @@ -2,7 +2,7 @@ import type { AiVaultAgent, AiVaultScanIssue } from '../../shared/ai-vault-types import type { ExecutionHostId } from '../../shared/execution-host' import type { FileStat } from '../providers/types' import { throwIfAiVaultScanCancelled } from './ai-vault-scan-cancellation' -import { recordRemoteSessionScanIssue } from './remote-session-scan-issues' +import { recordSessionScanIssue } from './session-scan-issues' import type { RemoteSessionFilesystemProvider } from './remote-session-scanner-types' import type { FileWithMtime } from './session-scanner-types' import { errorMessage } from './session-scanner-values' @@ -32,7 +32,7 @@ export async function statRemoteSessionFile( } catch (error) { throwIfAiVaultScanCancelled(options?.signal) if (!options?.missingIsExpected || !isMissingRemoteSessionPathError(error)) { - recordRemoteSessionScanIssue(issues, { + recordSessionScanIssue(issues, { executionHostId, agent, path, diff --git a/src/main/ai-vault/remote-session-scan-issues.ts b/src/main/ai-vault/remote-session-scan-issues.ts deleted file mode 100644 index aee229f443c..00000000000 --- a/src/main/ai-vault/remote-session-scan-issues.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { AiVaultScanIssue } from '../../shared/ai-vault-types' - -const REMOTE_SCAN_ISSUE_LIMIT = 500 - -export function recordRemoteSessionScanIssue( - issues: AiVaultScanIssue[], - issue: AiVaultScanIssue -): void { - if (issues.length < REMOTE_SCAN_ISSUE_LIMIT - 1) { - issues.push(issue) - return - } - if (issues.length === REMOTE_SCAN_ISSUE_LIMIT - 1) { - // Kinded: this row is a scan notice, not a skipped transcript — the panel - // counts unkinded issues as skipped transcript files. - issues.push({ - executionHostId: issue.executionHostId, - agent: issue.agent, - kind: 'notice', - path: 'Agent Session History scan', - message: 'Additional scan issues were omitted.' - }) - } -} diff --git a/src/main/ai-vault/remote-session-scanner-discovery.ts b/src/main/ai-vault/remote-session-scanner-discovery.ts index 91f21eab720..329bdb2e584 100644 --- a/src/main/ai-vault/remote-session-scanner-discovery.ts +++ b/src/main/ai-vault/remote-session-scanner-discovery.ts @@ -7,7 +7,7 @@ import type { FileWithMtime } from './session-scanner-types' import { errorMessage } from './session-scanner-values' import { mapRemoteScanBatches } from './remote-session-scan-batching' import { throwIfAiVaultScanCancelled } from './ai-vault-scan-cancellation' -import { recordRemoteSessionScanIssue } from './remote-session-scan-issues' +import { recordSessionScanIssue } from './session-scan-issues' import type { RemoteScannerContext, RemoteSessionCandidate, @@ -124,7 +124,7 @@ function recordRemoteDirectoryIssue( err: unknown ): void { if (!isMissingRemoteSessionPathError(err)) { - recordRemoteSessionScanIssue(issues, { + recordSessionScanIssue(issues, { executionHostId, agent: source.agent, kind: 'host', diff --git a/src/main/ai-vault/remote-session-scanner.ts b/src/main/ai-vault/remote-session-scanner.ts index 2523cd22a43..568b42c27cd 100644 --- a/src/main/ai-vault/remote-session-scanner.ts +++ b/src/main/ai-vault/remote-session-scanner.ts @@ -24,7 +24,7 @@ import { createAntigravityWorkspaceResolver } from './session-scanner-antigravit import { errorMessage } from './session-scanner-values' import { mapRemoteScanBatches } from './remote-session-scan-batching' import { throwIfAiVaultScanCancelled } from './ai-vault-scan-cancellation' -import { recordRemoteSessionScanIssue } from './remote-session-scan-issues' +import { recordSessionScanIssue } from './session-scan-issues' import { limitRemoteScanFilesystemConcurrency } from './remote-session-scan-concurrency' import { aiVaultScanLimit } from '../../shared/ai-vault-session-depth' @@ -205,7 +205,7 @@ async function scanRemoteInScopeSessions(args: { } if (index < candidates.length && sessions.length < args.limit) { - recordRemoteSessionScanIssue(args.issues, { + recordSessionScanIssue(args.issues, { executionHostId: args.context.executionHostId, agent: 'codex', kind: 'scope', @@ -241,7 +241,7 @@ async function parseRemoteSessionCandidate( return session } catch (err) { throwIfAiVaultScanCancelled(context.signal) - recordRemoteSessionScanIssue(issues, { + recordSessionScanIssue(issues, { executionHostId: context.executionHostId, agent: candidate.source.agent, path: candidate.file.path, diff --git a/src/main/ai-vault/session-first-user-prompt-read.ts b/src/main/ai-vault/session-first-user-prompt-read.ts index f250846a20e..ac5a35f2a53 100644 --- a/src/main/ai-vault/session-first-user-prompt-read.ts +++ b/src/main/ai-vault/session-first-user-prompt-read.ts @@ -1,10 +1,10 @@ -import { stat } from 'node:fs/promises' import type { AiVaultAgent, AiVaultFirstUserPromptResult, AiVaultSession } from '../../shared/ai-vault-types' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host' +import { wslGatedStat } from '../native-chat/wsl-transcript-fs-access' import { parseAgentSessionFile } from './session-scanner-agent-parser' import { withFullFirstUserPromptCapture } from './session-scanner-first-user-prompt-capture' import { parseOpenCodeSqliteSession } from './session-scanner-opencode-sqlite' @@ -118,7 +118,9 @@ async function fileWithMtimeForPath( } try { - const info = await stat(filePath) + // 'scan' matches the parser this feeds, so the two halves of one re-parse + // share a lane instead of the stat jumping the live-transcript queue. + const info = await wslGatedStat(filePath, 'scan') return { path: filePath, mtimeMs: info.mtimeMs, diff --git a/src/main/ai-vault/session-scan-issues.ts b/src/main/ai-vault/session-scan-issues.ts new file mode 100644 index 00000000000..b3e21f9c5a8 --- /dev/null +++ b/src/main/ai-vault/session-scan-issues.ts @@ -0,0 +1,27 @@ +import type { AiVaultScanIssue } from '../../shared/ai-vault-types' + +// Why: a stalled WSL distro or an unreachable remote host fails one probe per +// discovered path, so an uncapped list ships one row per transcript file in the +// tree over IPC. Local and remote scans share the bound — the failure shape is +// the same and both feed the same panel. +const SCAN_ISSUE_LIMIT = 500 + +/** Append a scan issue, collapsing everything past the cap into one notice. */ +export function recordSessionScanIssue(issues: AiVaultScanIssue[], issue: AiVaultScanIssue): void { + if (issues.length < SCAN_ISSUE_LIMIT - 1) { + issues.push(issue) + return + } + if (issues.length === SCAN_ISSUE_LIMIT - 1) { + // Kinded: this row is a scan notice, not a skipped transcript — the panel + // counts unkinded issues as skipped transcript files. Spread first so a + // remote issue keeps its executionHostId and a local one never gains an + // explicit `undefined` (which would outrank the scanner's own stamping). + issues.push({ + ...issue, + kind: 'notice', + path: 'Agent Session History scan', + message: 'Additional scan issues were omitted.' + }) + } +} diff --git a/src/main/ai-vault/session-scanner-antigravity-history.ts b/src/main/ai-vault/session-scanner-antigravity-history.ts index 989ac7b4179..ccfb506b7f7 100644 --- a/src/main/ai-vault/session-scanner-antigravity-history.ts +++ b/src/main/ai-vault/session-scanner-antigravity-history.ts @@ -1,8 +1,28 @@ import type { AiVaultSession } from '../../shared/ai-vault-types' +import { wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { normalizeTitleText, parseJsonObject, timestampMs } from './session-scanner-values' const HISTORY_MATCH_WINDOW_MS = 2_000 +/** + * The local-scan `readHistory`; remote scans inject their own transport. A + * missing or unreadable history file is genuinely "no enrichment", but a gate + * refusal must propagate so the caller records a scan issue — degrading it to + * null lists the session with a missing cwd and no retry signal, and the + * resolver's memo relies on the rejection to evict rather than pin a stall. + */ +export async function readLocalAntigravityHistory(path: string): Promise { + try { + return await wslGatedReadFile(path, 'utf-8', 'scan') + } catch (error) { + if (error instanceof WslTranscriptFsError) { + throw error + } + return null + } +} + type AntigravityHistoryEntry = { timestampMs: number workspace: string @@ -26,8 +46,19 @@ export function createAntigravityWorkspaceResolver( } let index = indexes.get(historyPath) if (!index) { - index = readHistory(historyPath).then(indexAntigravityHistory) - indexes.set(historyPath, index) + // Why: a read failure is transient (a stalled WSL distro refuses here), + // so it must not be memoized — every later session under this history + // file would inherit the rejection for the process lifetime. + const pending: Promise = readHistory(historyPath) + .then(indexAntigravityHistory) + .catch((error: unknown) => { + if (indexes.get(historyPath) === pending) { + indexes.delete(historyPath) + } + throw error + }) + index = pending + indexes.set(historyPath, pending) } const workspace = findAntigravityWorkspace(session, await index) return workspace ? { ...session, cwd: workspace } : session diff --git a/src/main/ai-vault/session-scanner-antigravity-parser.ts b/src/main/ai-vault/session-scanner-antigravity-parser.ts index 818167fbd0c..1896138749c 100644 --- a/src/main/ai-vault/session-scanner-antigravity-parser.ts +++ b/src/main/ai-vault/session-scanner-antigravity-parser.ts @@ -1,5 +1,5 @@ import { remoteSessionContentLines } from './remote-session-content-lines' -import { createReadStream } from 'node:fs' +import { openTranscriptReadStream } from '../native-chat/wsl-transcript-fs-access' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' @@ -26,11 +26,16 @@ export async function parseAntigravitySessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) - return parseAntigravitySessionLines({ file, lines, platform }) + const input = openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan') + const lines = createInterface({ input, crlfDelay: Infinity }) + try { + return await parseAntigravitySessionLines({ file, lines, platform }) + } finally { + // readline.close() leaves the underlying stream open; destroy it so a + // mid-parse throw cannot leak the gated transcript handle. + lines.close() + input.destroy() + } } export async function parseAntigravitySessionContent( diff --git a/src/main/ai-vault/session-scanner-claude-subagents.ts b/src/main/ai-vault/session-scanner-claude-subagents.ts index 5c269d91cf3..a2dc5745948 100644 --- a/src/main/ai-vault/session-scanner-claude-subagents.ts +++ b/src/main/ai-vault/session-scanner-claude-subagents.ts @@ -1,5 +1,3 @@ -import { createReadStream } from 'node:fs' -import { readdir, readFile, stat } from 'node:fs/promises' import { basename, extname, join } from 'node:path' import { createInterface } from 'node:readline' import type { @@ -8,6 +6,14 @@ import type { AiVaultSubagentListResult, AiVaultSubagentRunStatus } from '../../shared/ai-vault-types' +import { + openTranscriptReadStream, + wslGatedReaddir, + wslGatedReadFile, + wslGatedStat +} from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' +import { recordSessionScanIssue } from './session-scan-issues' import { sessionIdFromFileName, sessionSortTime } from './session-scanner-accumulator' import { parseClaudeSessionFile } from './session-scanner-primary-parsers' import { @@ -29,6 +35,10 @@ const SUBAGENT_RUNNING_RECENCY_MS = 5 * 60_000 // Match the main scanner's deliberate parse batching (SESSION_PARSE_CONCURRENCY): // opening every subagent read stream at once stalls over SSH/WSL UNC paths. const SUBAGENT_PARSE_CONCURRENCY = 8 +// 'scan', not 'exact', even though a user expands this on demand: it is bulk +// directory work feeding the same parsers as the main scan, and the exact lane +// stays reserved for live transcript probes. +const SUBAGENT_FS_PRIORITY = 'scan' const TASK_NOTIFICATION_MARKER = '' const TOOL_USE_RESULT_MARKER = '"toolUseResult"' @@ -71,8 +81,13 @@ export async function listClaudeSubagentSessions(args: { let entries try { - entries = await readdir(subagentsDir, { withFileTypes: true }) - } catch { + entries = await wslGatedReaddir(subagentsDir, SUBAGENT_FS_PRIORITY) + } catch (err) { + // A gate refusal is a stalled distro, not a session without subagents — + // report it so the panel offers a retry instead of showing an empty list. + if (err instanceof WslTranscriptFsError) { + recordSessionScanIssue(issues, { agent: 'claude', path: subagentsDir, message: err.message }) + } return { sessions: [], issues } } @@ -130,7 +145,7 @@ async function parseSubagentTranscript(args: { issues: AiVaultScanIssue[] }): Promise { try { - const fileStat = await stat(args.filePath) + const fileStat = await wslGatedStat(args.filePath, SUBAGENT_FS_PRIORITY) const session = await parseClaudeSessionFile( { path: args.filePath, @@ -161,7 +176,11 @@ async function parseSubagentTranscript(args: { } } } catch (err) { - args.issues.push({ agent: 'claude', path: args.filePath, message: errorMessage(err) }) + recordSessionScanIssue(args.issues, { + agent: 'claude', + path: args.filePath, + message: errorMessage(err) + }) return null } } @@ -187,11 +206,13 @@ function resolveSubagentStatus(args: { // 'async_launched', notification 'running') are superseded by terminal ones. async function collectSubagentTaskStatuses(parentFilePath: string): Promise> { const statuses = new Map() + const input = openTranscriptReadStream( + parentFilePath, + { encoding: 'utf-8' }, + SUBAGENT_FS_PRIORITY + ) + const lines = createInterface({ input, crlfDelay: Infinity }) try { - const lines = createInterface({ - input: createReadStream(parentFilePath, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) for await (const line of lines) { const hasNotification = line.includes(TASK_NOTIFICATION_MARKER) const hasTaskResult = @@ -232,6 +253,11 @@ async function collectSubagentTaskStatuses(parentFilePath: string): Promise { const metaPath = `${transcriptPath.slice(0, -extname(transcriptPath).length)}.meta.json` try { - const record = asRecord(JSON.parse(await readFile(metaPath, 'utf-8')) as unknown) + const raw = await wslGatedReadFile(metaPath, 'utf-8', SUBAGENT_FS_PRIORITY) + const record = asRecord(JSON.parse(raw) as unknown) return { description: normalizeTitleText(extractString(record?.description) ?? ''), agentType: extractString(record?.agentType) diff --git a/src/main/ai-vault/session-scanner-codex-parser.ts b/src/main/ai-vault/session-scanner-codex-parser.ts index 0f73fa54126..6887b7ed5d8 100644 --- a/src/main/ai-vault/session-scanner-codex-parser.ts +++ b/src/main/ai-vault/session-scanner-codex-parser.ts @@ -1,4 +1,4 @@ -import { createReadStream } from 'node:fs' +import { openTranscriptReadStream } from '../native-chat/wsl-transcript-fs-access' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import { readCodexSessionIndexTitle } from './session-scanner-codex-title-index' @@ -42,7 +42,7 @@ export async function parseCodexSessionFile( executionHostId?: ExecutionHostId ): Promise { const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), + input: openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan'), crlfDelay: Infinity }) diff --git a/src/main/ai-vault/session-scanner-codex-title-index.ts b/src/main/ai-vault/session-scanner-codex-title-index.ts index 8ef2d5645cb..635a215562a 100644 --- a/src/main/ai-vault/session-scanner-codex-title-index.ts +++ b/src/main/ai-vault/session-scanner-codex-title-index.ts @@ -1,7 +1,7 @@ -import { createReadStream } from 'node:fs' -import { stat } from 'node:fs/promises' import { basename, dirname, join } from 'node:path' import { createInterface } from 'node:readline' +import { openTranscriptReadStream, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { extractString, normalizeTitleText, parseJsonObject } from './session-scanner-values' // Codex names threads lazily in /session_index.jsonl; transcripts @@ -77,7 +77,7 @@ async function readCodexSessionIndexTitles(codexHome: string): Promise ({ - signature, - titles - })) + const pending = readCodexSessionIndexTitlesFromDisk(indexPath).then(({ titles, refused }) => { + // Why: a gate refusal is a stalled distro, not a title-less index — caching + // it would pin "no titles" until the index's size or mtime changes. + if (refused && codexSessionIndexTitleCache.get(codexHome) === pending) { + codexSessionIndexTitleCache.delete(codexHome) + } + return { signature, titles } + }) storeCodexSessionIndexTitleCacheEntry(codexHome, pending) return (await pending).titles } @@ -133,11 +137,11 @@ function storeCodexSessionIndexTitleCacheEntry( async function readCodexSessionIndexTitlesFromDisk( indexPath: string -): Promise> { +): Promise<{ titles: Map; refused: boolean }> { const titleBySessionId = new Map() try { const lines = createInterface({ - input: createReadStream(indexPath, { encoding: 'utf-8' }), + input: openTranscriptReadStream(indexPath, { encoding: 'utf-8' }, 'scan'), crlfDelay: Infinity }) for await (const line of lines) { @@ -151,8 +155,9 @@ async function readCodexSessionIndexTitlesFromDisk( titleBySessionId.set(sessionId, title) } } - } catch { + } catch (error) { // Codex creates the index opportunistically; older homes may only have raw transcripts. + return { titles: titleBySessionId, refused: error instanceof WslTranscriptFsError } } - return titleBySessionId + return { titles: titleBySessionId, refused: false } } diff --git a/src/main/ai-vault/session-scanner-copilot-parser.ts b/src/main/ai-vault/session-scanner-copilot-parser.ts index 4d0140fc3df..7e5450393e0 100644 --- a/src/main/ai-vault/session-scanner-copilot-parser.ts +++ b/src/main/ai-vault/session-scanner-copilot-parser.ts @@ -1,5 +1,5 @@ import { remoteSessionContentLines } from './remote-session-content-lines' -import { createReadStream } from 'node:fs' +import { openTranscriptReadStream } from '../native-chat/wsl-transcript-fs-access' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' @@ -35,7 +35,7 @@ export async function parseCopilotSessionFile( platform: NodeJS.Platform = process.platform ): Promise { const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), + input: openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan'), crlfDelay: Infinity }) return parseCopilotSessionLines({ file, lines, platform }) diff --git a/src/main/ai-vault/session-scanner-core-parser-wsl-stall.test.ts b/src/main/ai-vault/session-scanner-core-parser-wsl-stall.test.ts new file mode 100644 index 00000000000..44fe71c80b2 --- /dev/null +++ b/src/main/ai-vault/session-scanner-core-parser-wsl-stall.test.ts @@ -0,0 +1,267 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFsPromisesModule from 'node:fs/promises' +import type * as NodePathModule from 'node:path' +import type { SessionFileCandidate } from './session-scanner-types' + +const mocks = vi.hoisted(() => ({ + open: vi.fn(), + readFile: vi.fn(), + readdir: vi.fn(), + stat: vi.fn() +})) + +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...(await importOriginal()), + open: mocks.open, + readFile: mocks.readFile, + readdir: mocks.readdir, + stat: mocks.stat +})) + +// Derived sibling paths must retain Windows separators in this cross-platform test. +vi.mock('node:path', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual.win32, default: actual.win32 } +}) + +import { + parseAgentSessionFileCached, + resetSessionParseCacheForTests +} from './session-scanner-parse-cache' +import { + WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS, + WslTranscriptFsError +} from '../native-chat/wsl-transcript-fs-gate' + +function uncPath(distro: string, ...segments: string[]): string { + return `\\\\wsl.localhost\\${distro}\\home\\ada\\${segments.join('\\')}` +} + +const KIMI_HOME = ['.kimi-code', 'sessions', 'wd_app_9f2', 'session_abc'] +const GROK_DIR = ['.grok', 'sessions', 'ses-1'] +const OPENCODE_ROOT = ['.local', 'share', 'opencode', 'storage'] + +const KIMI_STATE = JSON.stringify({ + title: 'Kimi session', + createdAt: '2026-06-01T10:00:00.000Z', + updatedAt: '2026-06-01T10:05:00.000Z', + agents: { main: { type: 'main', parentAgentId: null } } +}) + +const KIMI_WIRE = `${JSON.stringify({ + type: 'context.append_message', + message: { role: 'user', origin: { kind: 'user' }, content: 'ship it' } +})}\n` + +const GROK_SESSION = JSON.stringify({ + info: { id: 'ses-1', cwd: '/repo/app' }, + generated_title: 'Grok session', + created_at: '2026-06-01T10:00:00.000Z' +}) + +const GROK_HISTORY = `${JSON.stringify({ + type: 'user', + content: 'ship it' +})}\n` + +const OPENCODE_SESSION = JSON.stringify({ + id: 'ses-1', + title: 'OpenCode session', + directory: '/repo/app', + time: { created: 1780000000000 } +}) + +const OPENCODE_MESSAGE = JSON.stringify({ + role: 'user', + content: [{ type: 'text', text: 'ship it' }], + time: { created: 1780000000000 } +}) + +type ReadResult = { bytesRead: number; buffer: Buffer } + +let releaseStall: (() => void) | undefined + +function stalls(): Promise { + return new Promise((resolve) => { + releaseStall = () => resolve({ bytesRead: 0, buffer: Buffer.alloc(0) } as T) + }) +} + +function stallingHandle() { + return { read: vi.fn(stalls), close: vi.fn(async () => {}) } +} + +function servingHandle(body: string) { + const bytes = Buffer.from(body) + return { + read: vi.fn(async (buffer: Buffer, offset: number, length: number, position: number) => { + const slice = bytes.subarray(position, Math.min(position + length, bytes.length)) + slice.copy(buffer, offset) + return { bytesRead: slice.length, buffer } + }), + close: vi.fn(async () => {}) + } +} + +function missing(): Error { + return Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) +} + +function dirent(name: string) { + return { name, isFile: () => true } +} + +function candidate(agent: SessionFileCandidate['agent'], path: string): SessionFileCandidate { + return { + agent, + file: { + path, + mtimeMs: 1, + modifiedAt: '2026-06-01T10:05:00.000Z', + sizeBytes: 128 + }, + codexHome: null + } +} + +async function expectRefusal(target: SessionFileCandidate): Promise { + const refusal = expect(parseAgentSessionFileCached(target, 'linux')).rejects.toBeInstanceOf( + WslTranscriptFsError + ) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + await refusal +} + +async function releaseAndSettle(): Promise { + releaseStall?.() + releaseStall = undefined + await vi.advanceTimersByTimeAsync(0) +} + +beforeEach(() => { + resetSessionParseCacheForTests() + mocks.open.mockReset() + mocks.readFile.mockReset() + mocks.readdir.mockReset() + mocks.stat.mockReset() + releaseStall = undefined + mocks.stat.mockRejectedValue(missing()) + vi.useFakeTimers() +}) + +afterEach(async () => { + await releaseAndSettle() + vi.useRealTimers() +}) + +describe('Kimi session parse against a stalled WSL transcript', () => { + it('refuses a stalled state.json read instead of reporting no session', async () => { + const state = uncPath('KimiState', ...KIMI_HOME, 'state.json') + mocks.readFile.mockImplementation(stalls) + + await expectRefusal(candidate('kimi', state)) + }) + + it('refuses a stalled wire read, then caches the full session once it recovers', async () => { + const state = uncPath('KimiWire', ...KIMI_HOME, 'state.json') + mocks.readFile.mockResolvedValue(KIMI_STATE) + mocks.open.mockResolvedValue(stallingHandle()) + + await expectRefusal(candidate('kimi', state)) + await releaseAndSettle() + + mocks.open.mockResolvedValue(servingHandle(KIMI_WIRE)) + const recovered = await parseAgentSessionFileCached(candidate('kimi', state), 'linux') + + expect(recovered?.messageCount).toBe(1) + }) + + // Pins the narrowness of the parser's `instanceof WslTranscriptFsError` + // rethrow: widening it to every error turns this into a hard scan issue. + it('still returns a metadata-only session when the wire file is simply missing', async () => { + const state = uncPath('KimiMissing', ...KIMI_HOME, 'state.json') + mocks.readFile.mockResolvedValue(KIMI_STATE) + mocks.open.mockRejectedValue(missing()) + + const session = await parseAgentSessionFileCached(candidate('kimi', state), 'linux') + + expect(session).toMatchObject({ agent: 'kimi', title: 'Kimi session', messageCount: 0 }) + }) +}) + +describe('Grok session parse against a stalled WSL transcript', () => { + it('refuses a stalled chat_history read instead of reporting a summary-only session', async () => { + const file = uncPath('GrokHistory', ...GROK_DIR, 'session.json') + mocks.readFile.mockResolvedValue(GROK_SESSION) + mocks.open.mockResolvedValue(stallingHandle()) + + await expectRefusal(candidate('grok', file)) + await releaseAndSettle() + + mocks.open.mockResolvedValue(servingHandle(GROK_HISTORY)) + const recovered = await parseAgentSessionFileCached(candidate('grok', file), 'linux') + + expect(recovered?.previewMessages).toEqual([ + expect.objectContaining({ role: 'user', text: 'ship it' }) + ]) + }) + + it('still returns the summary-only session when chat_history is missing', async () => { + const file = uncPath('GrokMissing', ...GROK_DIR, 'session.json') + mocks.readFile.mockResolvedValue(GROK_SESSION) + mocks.open.mockRejectedValue(missing()) + + const session = await parseAgentSessionFileCached(candidate('grok', file), 'linux') + + expect(session).toMatchObject({ + agent: 'grok', + title: 'Grok session', + previewMessages: [] + }) + }) +}) + +describe('OpenCode session parse against a stalled WSL transcript', () => { + function sessionPath(distro: string): string { + return uncPath(distro, ...OPENCODE_ROOT, 'session', 'prj', 'ses-1.json') + } + + it('refuses a stalled message-directory listing instead of an empty transcript', async () => { + mocks.readFile.mockResolvedValue(OPENCODE_SESSION) + mocks.readdir.mockImplementation(stalls) + + await expectRefusal(candidate('opencode', sessionPath('OpenCodeDir'))) + }) + + it('refuses a stalled per-message read instead of a partial transcript', async () => { + const file = sessionPath('OpenCodeMessage') + mocks.readdir.mockResolvedValue([dirent('msg-1.json')]) + mocks.readFile.mockImplementation((path: string) => + path === file ? Promise.resolve(OPENCODE_SESSION) : stalls() + ) + + await expectRefusal(candidate('opencode', file)) + await releaseAndSettle() + + mocks.readFile.mockImplementation((path: string) => + Promise.resolve(path === file ? OPENCODE_SESSION : OPENCODE_MESSAGE) + ) + const recovered = await parseAgentSessionFileCached(candidate('opencode', file), 'linux') + + expect(recovered?.messageCount).toBe(1) + }) + + // Same guard as Kimi's: a live process mid-write must stay a parseable + // session, not a refusal. + it('still returns the session when a live process left a half-written message', async () => { + const file = sessionPath('OpenCodeHalfWritten') + mocks.readdir.mockResolvedValue([dirent('msg-1.json')]) + mocks.readFile.mockImplementation((path: string) => + Promise.resolve(path === file ? OPENCODE_SESSION : '{"role":"user",') + ) + + const session = await parseAgentSessionFileCached(candidate('opencode', file), 'linux') + + expect(session).toMatchObject({ agent: 'opencode', title: 'OpenCode session', messageCount: 0 }) + }) +}) diff --git a/src/main/ai-vault/session-scanner-cursor-parser.ts b/src/main/ai-vault/session-scanner-cursor-parser.ts index b18402584e5..0f44aa923fa 100644 --- a/src/main/ai-vault/session-scanner-cursor-parser.ts +++ b/src/main/ai-vault/session-scanner-cursor-parser.ts @@ -1,5 +1,5 @@ import { remoteSessionContentLines } from './remote-session-content-lines' -import { createReadStream } from 'node:fs' +import { openTranscriptReadStream } from '../native-chat/wsl-transcript-fs-access' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' @@ -33,7 +33,7 @@ export async function parseCursorSessionFile( platform: NodeJS.Platform = process.platform ): Promise { const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), + input: openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan'), crlfDelay: Infinity }) return parseCursorSessionLines({ file, lines, platform }) diff --git a/src/main/ai-vault/session-scanner-devin-parser.ts b/src/main/ai-vault/session-scanner-devin-parser.ts index 4ad6fa45f78..a43603bca47 100644 --- a/src/main/ai-vault/session-scanner-devin-parser.ts +++ b/src/main/ai-vault/session-scanner-devin-parser.ts @@ -1,4 +1,4 @@ -import { readFile } from 'node:fs/promises' +import { wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' import type { FileWithMtime } from './session-scanner-types' @@ -27,7 +27,11 @@ export async function parseDevinSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - return parseDevinSessionContent(file, await readFile(file.path, 'utf-8'), platform) + return parseDevinSessionContent( + file, + await wslGatedReadFile(file.path, 'utf-8', 'scan'), + platform + ) } export function parseDevinSessionContent( diff --git a/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts new file mode 100644 index 00000000000..962a2e20fa9 --- /dev/null +++ b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts @@ -0,0 +1,137 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Dirent } from 'node:fs' +import type * as NodeFsPromisesModule from 'node:fs/promises' +import type { AiVaultScanIssue } from '../../shared/ai-vault-types' + +const fsMocks = vi.hoisted(() => ({ readdir: vi.fn(), stat: vi.fn() })) + +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...(await importOriginal()), + readdir: fsMocks.readdir, + stat: fsMocks.stat +})) + +import { + WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS, + WslTranscriptFsError +} from '../native-chat/wsl-transcript-fs-gate' +import { discoverFiles, walkSessionFiles } from './session-scanner-discovery' + +const SLOW_MESSAGE = + 'WSL transcript files are temporarily unavailable because filesystem access is taking too long. Try again shortly or restart Orca if the issue continues.' + +function dirent(name: string): Dirent { + return { name, isDirectory: () => false, isFile: () => true } as Dirent +} + +let releaseStall: (() => void) | undefined + +function stalls(): Promise { + return new Promise((resolve) => { + releaseStall = () => resolve(undefined as T) + }) +} + +beforeEach(() => { + fsMocks.readdir.mockReset() + fsMocks.stat.mockReset() + fsMocks.readdir.mockResolvedValue([]) + releaseStall = undefined +}) + +// A stalled task holds its gate permit until the call settles; releasing it +// keeps the next case from fast-failing on an already-exhausted gate. +afterEach(async () => { + if (!vi.isFakeTimers()) { + return + } + releaseStall?.() + await vi.advanceTimersByTimeAsync(0) + vi.useRealTimers() +}) + +describe('walkSessionFiles WSL gate refusals', () => { + it('rethrows gate refusals instead of reporting an empty tree', async () => { + const refusal = new WslTranscriptFsError('timeout', 'slow share') + await expect( + walkSessionFiles('\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex\\sessions', 'codex', [], { + extensions: new Set(['.jsonl']), + readDirectory: async () => { + throw refusal + } + }) + ).rejects.toBe(refusal) + }) + + it('still treats ordinary readdir failures as an empty tree', async () => { + await expect( + walkSessionFiles('/missing/root', 'codex', [], { + extensions: new Set(['.jsonl']), + readDirectory: async () => { + throw Object.assign(new Error('no such directory'), { code: 'ENOENT' }) + } + }) + ).resolves.toEqual([]) + }) +}) + +describe('discoverFiles containment for a stalled WSL root', () => { + const UNC_ROOT = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex\\sessions' + + it('contains a stalled readdir to one root so a Promise.all fan-out still resolves', async () => { + vi.useFakeTimers() + { + fsMocks.readdir.mockImplementation((dir: string) => + dir === UNC_ROOT ? stalls() : Promise.resolve([]) + ) + const issues: AiVaultScanIssue[] = [] + const discovery = discoverFiles({ + rootDir: UNC_ROOT, + limit: 10, + agent: 'codex', + issues, + extensions: ['.jsonl'] + }) + const healthy = discoverFiles({ + rootDir: '/home/ada/.codex/sessions', + limit: 10, + agent: 'codex', + issues: [], + extensions: ['.jsonl'] + }) + + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + + await expect(Promise.all([discovery, healthy])).resolves.toEqual([ + { agent: 'codex', rootDir: UNC_ROOT, files: [] }, + { agent: 'codex', rootDir: '/home/ada/.codex/sessions', files: [] } + ]) + expect(issues).toEqual([{ agent: 'codex', path: UNC_ROOT, message: SLOW_MESSAGE }]) + } + }) + + it('reports every stalled file without spending one deadline per file', async () => { + vi.useFakeTimers() + { + const names = ['a', 'b', 'c', 'd', 'e'].map((name) => dirent(`${name}.jsonl`)) + fsMocks.readdir.mockResolvedValue(names) + fsMocks.stat.mockImplementation(stalls) + const issues: AiVaultScanIssue[] = [] + const discovery = discoverFiles({ + rootDir: UNC_ROOT, + limit: 10, + agent: 'codex', + issues, + extensions: ['.jsonl'] + }) + + // Two deadlines total, not five: once the first stalled stat is marked + // stuck, every later file fast-fails on the route instead of queueing. + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS * 2 + 2) + + await expect(discovery).resolves.toEqual({ agent: 'codex', rootDir: UNC_ROOT, files: [] }) + expect(issues).toHaveLength(names.length) + expect(issues.every((issue) => issue.path.startsWith(UNC_ROOT))).toBe(true) + } + }) +}) diff --git a/src/main/ai-vault/session-scanner-discovery.ts b/src/main/ai-vault/session-scanner-discovery.ts index 031f94f3619..9ec569bc547 100644 --- a/src/main/ai-vault/session-scanner-discovery.ts +++ b/src/main/ai-vault/session-scanner-discovery.ts @@ -1,7 +1,9 @@ import type { Dirent } from 'node:fs' -import { readdir, stat } from 'node:fs/promises' import { extname, join } from 'node:path' import type { AiVaultAgent, AiVaultScanIssue } from '../../shared/ai-vault-types' +import { wslGatedReaddir, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' +import { recordSessionScanIssue } from './session-scan-issues' import type { FileWithMtime, SessionFileDiscovery } from './session-scanner-types' import { errorMessage } from './session-scanner-values' @@ -14,15 +16,31 @@ export async function discoverFiles(args: { filePredicate?: (path: string) => boolean directoryPredicate?: (name: string, depth: number) => boolean }): Promise { - const paths = await walkSessionFiles(args.rootDir, args.agent, args.issues, { - extensions: new Set(args.extensions), - filePredicate: args.filePredicate, - directoryPredicate: args.directoryPredicate - }) + let paths: string[] + try { + paths = await walkSessionFiles(args.rootDir, args.agent, args.issues, { + extensions: new Set(args.extensions), + filePredicate: args.filePredicate, + directoryPredicate: args.directoryPredicate + }) + } catch (err) { + // Why: discoverAiVaultSessionSources fans out with Promise.all, so one + // stalled distro would otherwise reject the whole vault scan — including + // every healthy local agent. Contain it to this root. + if (!(err instanceof WslTranscriptFsError)) { + throw err + } + recordSessionScanIssue(args.issues, { + agent: args.agent, + path: args.rootDir, + message: err.message + }) + return { agent: args.agent, rootDir: args.rootDir, files: [] } + } const files: FileWithMtime[] = [] for (const path of paths) { try { - const fileStat = await stat(path) + const fileStat = await wslGatedStat(path, 'scan') files.push({ path, mtimeMs: fileStat.mtimeMs, @@ -33,7 +51,11 @@ export async function discoverFiles(args: { nlink: fileStat.nlink }) } catch (err) { - args.issues.push({ agent: args.agent, path, message: errorMessage(err) }) + recordSessionScanIssue(args.issues, { + agent: args.agent, + path, + message: errorMessage(err) + }) } } return { @@ -63,9 +85,14 @@ export async function walkSessionFiles( try { entries = options.readDirectory ? await options.readDirectory(dirPath) - : await readdir(dirPath, { withFileTypes: true }) - } catch { + : await wslGatedReaddir(dirPath, 'scan', options.signal) + } catch (error) { options.signal?.throwIfAborted() + // Why: a gate refusal means the scan could not run, not that the tree is + // empty — swallowing it would misreport a stalled distro as "no transcript". + if (error instanceof WslTranscriptFsError) { + throw error + } return [] } diff --git a/src/main/ai-vault/session-scanner-droid-parser.ts b/src/main/ai-vault/session-scanner-droid-parser.ts index 557920e7f40..c896b47a3e8 100644 --- a/src/main/ai-vault/session-scanner-droid-parser.ts +++ b/src/main/ai-vault/session-scanner-droid-parser.ts @@ -1,5 +1,5 @@ import { remoteSessionContentLines } from './remote-session-content-lines' -import { createReadStream } from 'node:fs' +import { openTranscriptReadStream } from '../native-chat/wsl-transcript-fs-access' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' @@ -34,11 +34,16 @@ export async function parseDroidSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) - return parseDroidSessionLines({ file, lines, platform }) + const input = openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan') + const lines = createInterface({ input, crlfDelay: Infinity }) + try { + return await parseDroidSessionLines({ file, lines, platform }) + } finally { + // readline.close() leaves the underlying stream open; destroy it so a + // mid-parse throw cannot leak the gated transcript handle. + lines.close() + input.destroy() + } } export async function parseDroidSessionContent( diff --git a/src/main/ai-vault/session-scanner-fs-import-guard.test.ts b/src/main/ai-vault/session-scanner-fs-import-guard.test.ts new file mode 100644 index 00000000000..472ca932eac --- /dev/null +++ b/src/main/ai-vault/session-scanner-fs-import-guard.test.ts @@ -0,0 +1,81 @@ +import { readFile, readdir } from 'node:fs/promises' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + +const AI_VAULT_DIR = join(import.meta.dirname, '.') +const NATIVE_CHAT_DIR = join(import.meta.dirname, '..', 'native-chat') + +// Transcript I/O in these modules must go through the WSL admission gate, so a +// stalled 9P mount cannot hang a scan or a Native Chat load (STA-4049). +const NATIVE_CHAT_MODULES = [ + 'transcript-read-cache.ts', + 'transcript-reader.ts', + 'transcript-tail-reader.ts', + 'transcript-file-version.ts', + 'transcript-incremental-reader.ts', + 'transcript-watch-engine.ts' +] + +// Adding to this list must be a reviewed act: each entry names why the file +// touches a path that can never be a WSL UNC transcript. +const ALLOWLIST = new Set([ + // `existsSync` on bundled module paths inside the app dir. + 'session-scanner-service-entry-path.ts', + 'session-scanner-service-spawn.ts', + 'session-scanner-worker-spawn.ts', + 'session-scanner-opencode-sqlite-worker-spawn.ts', + // On-demand IPC readers, gated in the STA-4049 follow-up. + 'session-scanner-claude-subagents.ts', + 'session-scanner-omp-subagent-listing.ts', + // Test-only fixture builder. + 'session-scanner-test-fixtures.ts' +]) + +const FS_IMPORT = /import\s+([\s\S]*?)\s+from\s+['"]node:fs(?:\/promises)?['"]/g + +function valueImportsOfNodeFs(source: string): string[] { + return [...source.matchAll(FS_IMPORT)] + .map((match) => match[1]!.trim()) + .filter((clause) => !clause.startsWith('type')) +} + +async function guardedFiles(): Promise<{ name: string; path: string }[]> { + const aiVault = (await readdir(AI_VAULT_DIR)) + .filter((name) => name.startsWith('session-scanner') || name === 'session-title-file-reader.ts') + .filter((name) => name.endsWith('.ts') && !name.endsWith('.test.ts')) + .filter((name) => !ALLOWLIST.has(name)) + .map((name) => ({ name, path: join(AI_VAULT_DIR, name) })) + return [ + ...aiVault, + ...NATIVE_CHAT_MODULES.map((name) => ({ name, path: join(NATIVE_CHAT_DIR, name) })) + ] +} + +describe('WSL transcript gate import guard', () => { + it('leaves no raw node:fs value import in a gated transcript module', async () => { + const files = await guardedFiles() + const offenders: string[] = [] + for (const file of files) { + for (const clause of valueImportsOfNodeFs(await readFile(file.path, 'utf-8'))) { + offenders.push(`${file.name}: import ${clause} from 'node:fs…'`) + } + } + expect(offenders).toEqual([]) + }) + + it('actually covers the modules it claims to', async () => { + const names = (await guardedFiles()).map((file) => file.name) + expect(names).toEqual(expect.arrayContaining(NATIVE_CHAT_MODULES)) + // The V12–V17 sites the previous `*parser*` wording silently skipped. + expect(names).toEqual( + expect.arrayContaining([ + 'session-title-file-reader.ts', + 'session-scanner.ts', + 'session-scanner-values.ts', + 'session-scanner-codex-title-index.ts', + 'session-scanner-kimi-paths.ts', + 'session-scanner-opencode-sources.ts' + ]) + ) + }) +}) diff --git a/src/main/ai-vault/session-scanner-gemini-parsers.ts b/src/main/ai-vault/session-scanner-gemini-parsers.ts index c3cda8856bb..d8d8a485d8f 100644 --- a/src/main/ai-vault/session-scanner-gemini-parsers.ts +++ b/src/main/ai-vault/session-scanner-gemini-parsers.ts @@ -1,6 +1,5 @@ import { remoteSessionContentLines } from './remote-session-content-lines' -import { createReadStream } from 'node:fs' -import { readFile } from 'node:fs/promises' +import { openTranscriptReadStream, wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { @@ -34,7 +33,11 @@ export async function parseGeminiSessionFile( return parseGeminiJsonlSessionFile(file, platform) } - return parseGeminiJsonSessionContent(file, await readFile(file.path, 'utf-8'), platform) + return parseGeminiJsonSessionContent( + file, + await wslGatedReadFile(file.path, 'utf-8', 'scan'), + platform + ) } export async function parseGeminiSessionContent( @@ -83,7 +86,7 @@ export async function parseGeminiJsonlSessionFile( platform: NodeJS.Platform ): Promise { const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), + input: openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan'), crlfDelay: Infinity }) return parseGeminiJsonlSessionLines({ file, lines, platform }) diff --git a/src/main/ai-vault/session-scanner-graph-parsers.ts b/src/main/ai-vault/session-scanner-graph-parsers.ts index 250ebaf9ac9..d99893acaa2 100644 --- a/src/main/ai-vault/session-scanner-graph-parsers.ts +++ b/src/main/ai-vault/session-scanner-graph-parsers.ts @@ -1,6 +1,5 @@ import { remoteSessionContentLines } from './remote-session-content-lines' -import { createReadStream } from 'node:fs' -import { readFile } from 'node:fs/promises' +import { openTranscriptReadStream, wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' import { basename, dirname, join } from 'node:path' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' @@ -41,7 +40,9 @@ export async function parseRovoSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - const metadata = asRecord(JSON.parse(await readFile(file.path, 'utf-8')) as unknown) + const metadata = asRecord( + JSON.parse(await wslGatedReadFile(file.path, 'utf-8', 'scan')) as unknown + ) if (!metadata) { return null } @@ -175,11 +176,16 @@ export async function parseMessageGraphSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) - return parseMessageGraphSessionLines({ agent, file, lines, platform }) + const input = openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan') + const lines = createInterface({ input, crlfDelay: Infinity }) + try { + return await parseMessageGraphSessionLines({ agent, file, lines, platform }) + } finally { + // readline.close() leaves the underlying stream open; destroy it so a + // mid-parse throw cannot leak the gated transcript handle. + lines.close() + input.destroy() + } } export async function parseMessageGraphSessionContent( diff --git a/src/main/ai-vault/session-scanner-grok-parser.ts b/src/main/ai-vault/session-scanner-grok-parser.ts index 46ed29e8f1f..94e41e4b052 100644 --- a/src/main/ai-vault/session-scanner-grok-parser.ts +++ b/src/main/ai-vault/session-scanner-grok-parser.ts @@ -1,5 +1,5 @@ -import { createReadStream } from 'node:fs' -import { readFile } from 'node:fs/promises' +import { openTranscriptReadStream, wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { dirname, join } from 'node:path' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' @@ -36,7 +36,7 @@ export async function parseGrokSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - const record = asRecord(JSON.parse(await readFile(file.path, 'utf-8')) as unknown) + const record = asRecord(JSON.parse(await wslGatedReadFile(file.path, 'utf-8', 'scan')) as unknown) if (!record) { return null } @@ -62,12 +62,13 @@ async function consumeGrokChatHistory( accumulator: SessionAccumulator, sessionDir: string ): Promise { + const input = openTranscriptReadStream( + join(sessionDir, 'chat_history.jsonl'), + { encoding: 'utf-8' }, + 'scan' + ) + const lines = createInterface({ input, crlfDelay: Infinity }) try { - const lines = createInterface({ - input: createReadStream(join(sessionDir, 'chat_history.jsonl'), { encoding: 'utf-8' }), - crlfDelay: Infinity - }) - for await (const line of lines) { const record = parseJsonObject(line) if (!record) { @@ -111,8 +112,18 @@ async function consumeGrokChatHistory( seedFirstUserPrompt: false }) } - } catch { - // Summary-only sessions still provide enough metadata for the Vault list. + } catch (error) { + // Summary-only sessions still provide enough metadata for the Vault list. A + // gate refusal is a different thing — the history exists but is unreachable, + // so a message-less session must not be cached under the summary's mtime. + if (error instanceof WslTranscriptFsError) { + throw error + } + } finally { + // readline.close() leaves the underlying stream open; destroy it so a + // mid-read failure cannot leak the gated transcript handle. + lines.close() + input.destroy() } } diff --git a/src/main/ai-vault/session-scanner-hermes-parser.ts b/src/main/ai-vault/session-scanner-hermes-parser.ts index be844cc6627..017fd9c8fdc 100644 --- a/src/main/ai-vault/session-scanner-hermes-parser.ts +++ b/src/main/ai-vault/session-scanner-hermes-parser.ts @@ -1,4 +1,4 @@ -import { readFile } from 'node:fs/promises' +import { wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' import type { FileWithMtime } from './session-scanner-types' @@ -26,7 +26,11 @@ export async function parseHermesSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - return parseHermesSessionContent(file, await readFile(file.path, 'utf-8'), platform) + return parseHermesSessionContent( + file, + await wslGatedReadFile(file.path, 'utf-8', 'scan'), + platform + ) } export async function parseHermesSessionContent( diff --git a/src/main/ai-vault/session-scanner-index-cache-wsl-stall.test.ts b/src/main/ai-vault/session-scanner-index-cache-wsl-stall.test.ts new file mode 100644 index 00000000000..1a5da65f1a9 --- /dev/null +++ b/src/main/ai-vault/session-scanner-index-cache-wsl-stall.test.ts @@ -0,0 +1,136 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFsPromisesModule from 'node:fs/promises' + +const CODEX_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex' +const CODEX_SESSION_FILE = `${CODEX_HOME}\\sessions\\2026\\01\\01\\rollout-1.jsonl` +const SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const KIMI_INDEX = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.kimi\\session_index.jsonl' + +const mocks = vi.hoisted(() => ({ stat: vi.fn(), open: vi.fn(), readFile: vi.fn() })) + +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...(await importOriginal()), + stat: mocks.stat, + open: mocks.open, + readFile: mocks.readFile +})) + +import { + readCodexSessionIndexTitle, + resetCodexSessionIndexTitleCacheForTests, + _hasCodexSessionIndexTitleCacheEntryForTest +} from './session-scanner-codex-title-index' +import { + clearKimiSessionIndexCache, + hasKimiSessionIndexCacheEntryForTests, + readKimiWorkDirBySessionId +} from './session-scanner-kimi-paths' +import { readJsonObjectIfExists } from './session-scanner-values' +import { + WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS, + WslTranscriptFsError +} from '../native-chat/wsl-transcript-fs-gate' + +// Identity must not change between the refused and the recovered read, or the +// cache would miss for that reason instead of because the entry was evicted. +const INDEX_STATS = { size: 128, mtimeMs: 7, ctimeMs: 7 } + +let releaseStall: (() => void) | undefined + +function stalls(): Promise { + return new Promise((resolve) => { + releaseStall = () => resolve(undefined as never) + }) +} + +function servingHandle(body: string) { + const bytes = Buffer.from(body) + return { + read: vi.fn(async (buffer: Buffer, offset: number, length: number, position: number) => { + const slice = bytes.subarray(position, Math.min(position + length, bytes.length)) + slice.copy(buffer, offset) + return { bytesRead: slice.length, buffer } + }), + close: vi.fn(async () => {}) + } +} + +async function releaseAndSettle(): Promise { + releaseStall?.() + releaseStall = undefined + await vi.advanceTimersByTimeAsync(0) +} + +beforeEach(() => { + resetCodexSessionIndexTitleCacheForTests() + clearKimiSessionIndexCache() + mocks.stat.mockReset() + mocks.open.mockReset() + mocks.readFile.mockReset() + mocks.stat.mockResolvedValue(INDEX_STATS) + releaseStall = undefined + vi.useFakeTimers() +}) + +afterEach(async () => { + await releaseAndSettle() + vi.useRealTimers() +}) + +describe('memoized WSL session indexes under a stalled mount', () => { + it('evicts the Codex title index instead of pinning "no titles"', async () => { + mocks.open.mockResolvedValue({ read: vi.fn(stalls), close: vi.fn(async () => {}) }) + const refused = readCodexSessionIndexTitle(CODEX_SESSION_FILE, CODEX_HOME, SESSION_ID) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + + expect(await refused).toBeNull() + expect(_hasCodexSessionIndexTitleCacheEntryForTest(CODEX_HOME)).toBe(false) + + await releaseAndSettle() + mocks.open.mockResolvedValue( + servingHandle(`${JSON.stringify({ id: SESSION_ID, thread_name: 'Ship the gate' })}\n`) + ) + + // Same size/mtime as the refused read: only the eviction can produce a hit. + expect(await readCodexSessionIndexTitle(CODEX_SESSION_FILE, CODEX_HOME, SESSION_ID)).toBe( + 'Ship the gate' + ) + }) + + it('evicts the Kimi work-dir index instead of pinning "no cwd"', async () => { + mocks.open.mockResolvedValue({ read: vi.fn(stalls), close: vi.fn(async () => {}) }) + const refused = readKimiWorkDirBySessionId(KIMI_INDEX) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + + expect(await refused).toEqual(new Map()) + expect(hasKimiSessionIndexCacheEntryForTests(KIMI_INDEX)).toBe(false) + + await releaseAndSettle() + mocks.open.mockResolvedValue( + servingHandle(`${JSON.stringify({ sessionId: SESSION_ID, workDir: '/repo/app' })}\n`) + ) + + expect(await readKimiWorkDirBySessionId(KIMI_INDEX)).toEqual( + new Map([[SESSION_ID, '/repo/app']]) + ) + }) + + it('surfaces a refused optional JSON enrichment instead of caching it as absent', async () => { + mocks.readFile.mockImplementation(stalls) + const pending = readJsonObjectIfExists(`${CODEX_HOME}\\history.json`).catch( + (error: unknown) => error + ) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + + // A throw, not `null`: `parseSessionCandidate` turns it into a scan issue, + // where `null` would cache an un-enriched session that never re-reads. + expect(await pending).toBeInstanceOf(WslTranscriptFsError) + }) + + it('still degrades a missing optional JSON file to null', async () => { + mocks.readFile.mockRejectedValue( + Object.assign(new Error('ENOENT'), { code: 'ENOENT' as const }) + ) + await expect(readJsonObjectIfExists(`${CODEX_HOME}\\missing.json`)).resolves.toBeNull() + }) +}) diff --git a/src/main/ai-vault/session-scanner-kimi-parser.ts b/src/main/ai-vault/session-scanner-kimi-parser.ts index 61341098e0d..ba6deaa8fb8 100644 --- a/src/main/ai-vault/session-scanner-kimi-parser.ts +++ b/src/main/ai-vault/session-scanner-kimi-parser.ts @@ -1,5 +1,5 @@ -import { createReadStream } from 'node:fs' -import { readFile } from 'node:fs/promises' +import { openTranscriptReadStream, wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import { @@ -36,8 +36,16 @@ export async function parseKimiSessionFile( ): Promise { let stateRecord: Record | null try { - stateRecord = asRecord(JSON.parse(await readFile(file.path, 'utf-8')) as unknown) - } catch { + stateRecord = asRecord( + JSON.parse(await wslGatedReadFile(file.path, 'utf-8', 'scan')) as unknown + ) + } catch (error) { + // Why: a missing/half-written state file is genuinely "no session", but a + // gate refusal is not — returning null would let the parse cache store that + // degraded answer under the file's unchanged mtime and never retry. + if (error instanceof WslTranscriptFsError) { + throw error + } return null } if (!stateRecord) { @@ -83,11 +91,9 @@ async function consumeKimiWireTranscript( } } + const input = openTranscriptReadStream(wirePath, { encoding: 'utf-8' }, 'scan') + const lines = createInterface({ input, crlfDelay: Infinity }) try { - const lines = createInterface({ - input: createReadStream(wirePath, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) for await (const line of lines) { const record = parseJsonObject(line) if (!record) { @@ -111,9 +117,18 @@ async function consumeKimiWireTranscript( break } } - } catch { + } catch (error) { // No transcript yet (session created but never ran a turn) — metadata-only - // sessions still belong in the panel. + // sessions still belong in the panel. A gate refusal instead means the wire + // bytes exist but are unreachable; a partial session must not be cached. + if (error instanceof WslTranscriptFsError) { + throw error + } + } finally { + // readline.close() leaves the underlying stream open; destroy it so a + // mid-read failure cannot leak the gated transcript handle. + lines.close() + input.destroy() } flushAssistant() } diff --git a/src/main/ai-vault/session-scanner-kimi-paths.ts b/src/main/ai-vault/session-scanner-kimi-paths.ts index 7ed457f6c07..590e4aee814 100644 --- a/src/main/ai-vault/session-scanner-kimi-paths.ts +++ b/src/main/ai-vault/session-scanner-kimi-paths.ts @@ -1,8 +1,8 @@ -import { stat } from 'node:fs/promises' -import { createReadStream } from 'node:fs' import { homedir } from 'node:os' import { basename, dirname, join } from 'node:path' import { createInterface } from 'node:readline' +import { openTranscriptReadStream, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { asRecord, extractString } from './session-scanner-values' import { KimiSessionIndexCache, @@ -78,9 +78,9 @@ export function hasKimiSessionIndexCacheEntryForTests(indexPath: string): boolea export async function readKimiWorkDirBySessionId(indexPath: string): Promise> { const generation = workDirCacheByIndexPath.beginRead() - let identity: Awaited> + let identity: Awaited> try { - identity = await stat(indexPath) + identity = await wslGatedStat(indexPath, 'scan') } catch { // Missing index (e.g. user deleted it): sessions still list, just without cwd. workDirCacheByIndexPath.delete(indexPath, generation) @@ -95,18 +95,30 @@ export async function readKimiWorkDirBySessionId(indexPath: string): Promise parseKimiSessionIndex(indexPath) + () => + parseKimiSessionIndex(indexPath).then(({ map, refused }) => { + // Why: a gate refusal is a stalled distro, not a cwd-less index — evict + // so the partial map is not served until the index's identity changes. + // Inside the loader, not at the call site: only the caller that missed + // runs this, so a concurrent hit would otherwise serve and keep it. + if (refused) { + workDirCacheByIndexPath.delete(indexPath, generation) + } + return map + }) ) } -async function parseKimiSessionIndex(indexPath: string): Promise> { +async function parseKimiSessionIndex( + indexPath: string +): Promise<{ map: Map; refused: boolean }> { const map = new Map() // Why: never reject. This promise is memoized and shared by every session // under one Kimi home; a mid-read failure (file deleted after stat, EACCES) // must degrade to whatever was parsed so the other sessions still list. try { const lines = createInterface({ - input: createReadStream(indexPath, { encoding: 'utf-8' }), + input: openTranscriptReadStream(indexPath, { encoding: 'utf-8' }, 'scan'), crlfDelay: Infinity }) for await (const line of lines) { @@ -126,8 +138,9 @@ async function parseKimiSessionIndex(indexPath: string): Promise { const filePath = join(args.artifactDir, args.name) try { - const fileStat = await stat(filePath) + const fileStat = await wslGatedStat(filePath, OMP_SUBAGENT_FS_PRIORITY) // The shared OMP parser decorates every parse with an artifact-dir count, so // a child row carries its own grandchild count. It is accurate but has no // renderer — subagent rows don't expand — and this lister is local-only, so @@ -107,7 +116,11 @@ async function parseOmpSubagentTranscript(args: { } } } catch (err) { - args.issues.push({ agent: 'omp', path: filePath, message: errorMessage(err) }) + recordSessionScanIssue(args.issues, { + agent: 'omp', + path: filePath, + message: errorMessage(err) + }) return null } } diff --git a/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts b/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts index 9136e8c0d34..57cadebeee0 100644 --- a/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts +++ b/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts @@ -1,4 +1,4 @@ -import { readdir } from 'node:fs/promises' +import { wslGatedReaddir } from '../native-chat/wsl-transcript-fs-access' import { basename, dirname, extname, join } from 'node:path' import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' import type { SubagentTranscriptPartition } from './session-scanner-subagent-transcripts' @@ -51,7 +51,7 @@ export function isOmpSubagentTranscriptFileName(name: string, isFile: boolean): export async function countOmpSubagentTranscripts(transcriptFilePath: string): Promise { let entries try { - entries = await readdir(ompArtifactDirFor(transcriptFilePath), { withFileTypes: true }) + entries = await wslGatedReaddir(ompArtifactDirFor(transcriptFilePath), 'scan') } catch { return 0 } diff --git a/src/main/ai-vault/session-scanner-opencode-parser.ts b/src/main/ai-vault/session-scanner-opencode-parser.ts index 4231f7d9de4..30223e70866 100644 --- a/src/main/ai-vault/session-scanner-opencode-parser.ts +++ b/src/main/ai-vault/session-scanner-opencode-parser.ts @@ -1,4 +1,5 @@ -import { readFile, readdir } from 'node:fs/promises' +import { wslGatedReaddir, wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { join } from 'node:path' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { FileWithMtime, SessionAccumulator } from './session-scanner-types' @@ -26,7 +27,7 @@ export async function parseOpenCodeSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { - const record = asRecord(JSON.parse(await readFile(file.path, 'utf-8')) as unknown) + const record = asRecord(JSON.parse(await wslGatedReadFile(file.path, 'utf-8', 'scan')) as unknown) if (!record) { return null } @@ -47,8 +48,13 @@ export async function parseOpenCodeSessionFile( async function readOpenCodeMessagesInOrder(messageDir: string): Promise[]> { let entries try { - entries = await readdir(messageDir, { withFileTypes: true }) - } catch { + entries = await wslGatedReaddir(messageDir, 'scan') + } catch (error) { + // A session with no message dir yet is empty; a gate refusal is not — an + // empty transcript would otherwise be cached under the session's mtime. + if (error instanceof WslTranscriptFsError) { + throw error + } return [] } const messages: { name: string; createdMs: number; message: Record }[] = [] @@ -59,11 +65,15 @@ async function readOpenCodeMessagesInOrder(messageDir: string): Promise | null = null try { message = asRecord( - JSON.parse(await readFile(join(messageDir, entry.name), 'utf-8')) as unknown + JSON.parse(await wslGatedReadFile(join(messageDir, entry.name), 'utf-8', 'scan')) as unknown ) - } catch { + } catch (error) { // A live OpenCode process can leave a half-written file; skip it rather - // than discard the whole session. + // than discard the whole session. A refused read is not a bad file — the + // partial transcript it would produce must not become the cached answer. + if (error instanceof WslTranscriptFsError) { + throw error + } continue } if (!message) { diff --git a/src/main/ai-vault/session-scanner-opencode-sources-wsl-stall.test.ts b/src/main/ai-vault/session-scanner-opencode-sources-wsl-stall.test.ts new file mode 100644 index 00000000000..accc60d008f --- /dev/null +++ b/src/main/ai-vault/session-scanner-opencode-sources-wsl-stall.test.ts @@ -0,0 +1,104 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Dirent } from 'node:fs' +import type * as NodeFsPromisesModule from 'node:fs/promises' +import type { AiVaultScanIssue } from '../../shared/ai-vault-types' + +const WSL_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada' +const WSL_DATA_DIR = `${WSL_HOME}/.local/share/opencode` + +const mocks = vi.hoisted(() => ({ readdir: vi.fn(), stat: vi.fn() })) + +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...(await importOriginal()), + readdir: mocks.readdir, + stat: mocks.stat +})) + +// The SQLite leg spawns a real worker thread, which fake timers cannot drive. +vi.mock('./session-scanner-opencode-sqlite-worker-spawn', () => ({ + listOpenCodeSqliteSessionsViaWorker: async () => [] +})) + +import { opencodeDiscoveries } from './session-scanner-opencode-sources' +import { WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS } from '../native-chat/wsl-transcript-fs-gate' + +let releaseStall: (() => void) | undefined + +function restoreEnv(key: string, value: string | undefined): void { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } +} + +function stalls(): Promise { + return new Promise((resolve) => { + releaseStall = () => resolve(undefined as never) + }) +} + +beforeEach(() => { + mocks.readdir.mockReset() + mocks.stat.mockReset() + releaseStall = undefined + vi.useFakeTimers() +}) + +afterEach(async () => { + releaseStall?.() + releaseStall = undefined + await vi.advanceTimersByTimeAsync(0) + vi.useRealTimers() +}) + +describe('OpenCode source discovery with a stalled WSL data directory', () => { + it('reports the stalled home as an issue and still resolves every discovery', async () => { + mocks.readdir.mockImplementation((dir: string) => + dir === WSL_DATA_DIR ? stalls() : Promise.resolve([] as Dirent[]) + ) + const issues: AiVaultScanIssue[] = [] + const discoveries = Promise.all( + opencodeDiscoveries( + { opencodeStorageDir: '/home/ada/.local/share/opencode/storage' }, + [WSL_HOME], + 10, + issues + ) + ) + // Two deadlines: the data-dir probe, then the storage scan that queued + // behind it before the route was flagged stuck. + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS * 2 + 2) + + // Zero databases for that home is the degraded answer; without the issue it + // would be indistinguishable from "OpenCode was never installed there". + const resolved = await discoveries + expect(resolved).toHaveLength(2) + expect(resolved.every((discovery) => discovery.files.length === 0)).toBe(true) + expect(issues.some((issue) => issue.path === WSL_DATA_DIR)).toBe(true) + expect(issues.every((issue) => issue.agent === 'opencode')).toBe(true) + }) + + it('reports a refused primary data directory instead of scanning clean', async () => { + const previousXdg = process.env.XDG_DATA_HOME + const previousDb = process.env.OPENCODE_DB + process.env.XDG_DATA_HOME = WSL_HOME + delete process.env.OPENCODE_DB + try { + mocks.readdir.mockImplementation(stalls) + const issues: AiVaultScanIssue[] = [] + const discoveries = Promise.all(opencodeDiscoveries({}, [], 10, issues)) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS * 2 + 2) + + // The primary source is the one per-root containment cannot reach, so a + // silent [] here reads as "no OpenCode sessions" on a clean scan. + await expect(discoveries).resolves.toHaveLength(1) + expect( + issues.some((issue) => issue.agent === 'opencode' && issue.path === `${WSL_HOME}/opencode`) + ).toBe(true) + } finally { + restoreEnv('XDG_DATA_HOME', previousXdg) + restoreEnv('OPENCODE_DB', previousDb) + } + }) +}) diff --git a/src/main/ai-vault/session-scanner-opencode-sources.ts b/src/main/ai-vault/session-scanner-opencode-sources.ts index 6d84965f8c0..365e6334512 100644 --- a/src/main/ai-vault/session-scanner-opencode-sources.ts +++ b/src/main/ai-vault/session-scanner-opencode-sources.ts @@ -1,8 +1,10 @@ -import { readdir } from 'node:fs/promises' import { dirname, join } from 'node:path' import type { AiVaultScanIssue } from '../../shared/ai-vault-types' +import { wslGatedReaddir } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { resolveOpenCodeStorageDirectory } from '../opencode/opencode-data-directory' import { listOpenCodeDatabases } from '../opencode-usage/scanner' +import { recordSessionScanIssue } from './session-scan-issues' import { discoverOpenCodeSessions } from './session-scanner-opencode-sqlite-discovery' import type { AiVaultScanOptions, SessionFileDiscovery } from './session-scanner-types' @@ -16,7 +18,7 @@ export function opencodeDiscoveries( return storageDirs.map(async (storageDir, index) => discoverOpenCodeSessions({ storageDir, - dbPaths: await opencodeDbPathsForSource(options, wslHomeDirs, storageDir, index), + dbPaths: await opencodeDbPathsForSource(options, wslHomeDirs, storageDir, index, issues), limitPerAgent: limit, issues }) @@ -37,32 +39,47 @@ async function opencodeDbPathsForSource( options: AiVaultScanOptions, wslHomeDirs: readonly string[], storageDir: string, - sourceIndex: number + sourceIndex: number, + issues: AiVaultScanIssue[] ): Promise { if (options.opencodeDbPaths) { return sourceIndex === 0 ? options.opencodeDbPaths : [] } // Why: custom OpenCode storage roots still keep SQLite DBs in the parent data dir. if (sourceIndex === 0 && options.opencodeStorageDir) { - return listOpenCodeDatabasesInDirectory(dirname(storageDir)) + return listOpenCodeDatabasesInDirectory(dirname(storageDir), issues) } if (sourceIndex === 0) { - return listOpenCodeDatabases() + return listOpenCodeDatabases((path, error) => { + recordSessionScanIssue(issues, { agent: 'opencode', path, message: error.message }) + }) } const wslHomeDir = wslHomeDirs[sourceIndex - 1] return wslHomeDir - ? listOpenCodeDatabasesInDirectory(join(wslHomeDir, '.local', 'share', 'opencode')) + ? listOpenCodeDatabasesInDirectory(join(wslHomeDir, '.local', 'share', 'opencode'), issues) : [] } -async function listOpenCodeDatabasesInDirectory(dataDir: string): Promise { +async function listOpenCodeDatabasesInDirectory( + dataDir: string, + issues: AiVaultScanIssue[] +): Promise { try { - const entries = await readdir(dataDir, { withFileTypes: true }) + const entries = await wslGatedReaddir(dataDir, 'scan') return entries .filter((entry) => entry.isFile() && /^opencode(?:-[A-Za-z0-9_.-]+)?\.db$/.test(entry.name)) .map((entry) => join(dataDir, entry.name)) .sort() - } catch { + } catch (error) { + // A stalled WSL data dir still degrades to "no databases", but the gap has + // to be reportable — an empty list otherwise reads as "OpenCode not used". + if (error instanceof WslTranscriptFsError) { + recordSessionScanIssue(issues, { + agent: 'opencode', + path: dataDir, + message: error.message + }) + } return [] } } diff --git a/src/main/ai-vault/session-scanner-parse-cache.ts b/src/main/ai-vault/session-scanner-parse-cache.ts index 727d70ac319..563055ffa39 100644 --- a/src/main/ai-vault/session-scanner-parse-cache.ts +++ b/src/main/ai-vault/session-scanner-parse-cache.ts @@ -1,5 +1,7 @@ -import { createReadStream } from 'node:fs' -import { open } from 'node:fs/promises' +import { + openTranscriptReadStream, + readTranscriptSlice +} from '../native-chat/wsl-transcript-fs-access' import type { AiVaultSession } from '../../shared/ai-vault-types' import { createAntigravitySessionResumeState } from './session-scanner-antigravity-parser' import { parseAgentSessionFile } from './session-scanner-agent-parser' @@ -305,13 +307,8 @@ async function parseResumableCandidate(args: { // agent transcripts are append-only so that trade is accepted (worst case is // a stale vault row until the file is next truncated or the app restarts). async function endsWithNewlineAt(path: string, offset: number): Promise { - const handle = await open(path, 'r') - try { - const { bytesRead, buffer } = await handle.read(Buffer.alloc(1), 0, 1, offset - 1) - return bytesRead === 1 && buffer[0] === NEWLINE_BYTE - } finally { - await handle.close() - } + const slice = await readTranscriptSlice(path, offset - 1, 1, 'scan') + return slice.length === 1 && slice[0] === NEWLINE_BYTE } type JsonlReadResult = { @@ -336,7 +333,7 @@ async function consumeCompleteJsonlLines(args: { let remainderParts: Buffer[] = [] let remainderLength = 0 - const stream = createReadStream(args.path, { start: args.start }) + const stream = openTranscriptReadStream(args.path, { start: args.start }, 'scan') for await (const chunk of stream as AsyncIterable) { bytesRead += chunk.length // Why check the chunk alone: the pieces held over are all mid-line, so none diff --git a/src/main/ai-vault/session-scanner-parse-wsl-stall.test.ts b/src/main/ai-vault/session-scanner-parse-wsl-stall.test.ts new file mode 100644 index 00000000000..9eea5176c66 --- /dev/null +++ b/src/main/ai-vault/session-scanner-parse-wsl-stall.test.ts @@ -0,0 +1,154 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFsPromisesModule from 'node:fs/promises' +import type { SessionFileCandidate } from './session-scanner-types' + +const STALLED_PATH = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.claude\\projects\\p\\a.jsonl' +const SIBLING_PATH = '\\\\wsl.localhost\\Debian\\home\\ada\\.claude\\projects\\p\\b.jsonl' + +const mocks = vi.hoisted(() => ({ open: vi.fn(), readdir: vi.fn() })) + +// readdir too: every claude parse counts sibling subagent transcripts, and an +// unmocked one would reach the host UNC path and stall under fake timers. +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...(await importOriginal()), + open: mocks.open, + readdir: mocks.readdir +})) + +import { + parseAgentSessionFileCached, + resetSessionParseCacheForTests +} from './session-scanner-parse-cache' +import { + WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS, + WslTranscriptFsError +} from '../native-chat/wsl-transcript-fs-gate' + +type ReadResult = { bytesRead: number; buffer: Buffer } + +// A stalled task keeps the gate's single scan slot until the call settles, so +// every case releases its stall before the next one runs. +let releaseStall: (() => void) | undefined + +function stalls(): Promise { + return new Promise((resolve) => { + releaseStall = () => resolve({ bytesRead: 0, buffer: Buffer.alloc(0) }) + }) +} + +function servingHandle(body: Buffer) { + return { + read: vi.fn(async (buffer: Buffer, offset: number, length: number, position: number) => { + const slice = body.subarray(position, Math.min(position + length, body.length)) + slice.copy(buffer, offset) + return { bytesRead: slice.length, buffer } + }), + close: vi.fn(async () => {}) + } +} + +function record(index: number, text: string): string { + return JSON.stringify({ + type: 'user', + sessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + timestamp: new Date(1740000000000 + index * 60_000).toISOString(), + cwd: '/repo/app', + gitBranch: 'main', + message: { role: 'user', content: text } + }) +} + +function body(count: number): Buffer { + return Buffer.from( + Array.from({ length: count }, (_, index) => `${record(index, `line ${index}`)}\n`).join('') + ) +} + +function candidate(path: string, bytes: Buffer, mtimeMs: number): SessionFileCandidate { + return { + agent: 'claude', + file: { + path, + mtimeMs, + modifiedAt: new Date(mtimeMs).toISOString(), + sizeBytes: bytes.length + }, + codexHome: null + } +} + +async function releaseAndSettle(): Promise { + releaseStall?.() + releaseStall = undefined + await vi.advanceTimersByTimeAsync(0) +} + +beforeEach(() => { + resetSessionParseCacheForTests() + mocks.open.mockReset() + mocks.readdir.mockReset() + mocks.readdir.mockResolvedValue([]) + releaseStall = undefined + vi.useFakeTimers() +}) + +afterEach(async () => { + await releaseAndSettle() + vi.useRealTimers() +}) + +describe('AI Vault session parse with a stalled WSL transcript body read', () => { + it('refuses the stalled candidate and still parses a sibling on a healthy distro', async () => { + mocks.open.mockResolvedValue({ read: vi.fn(stalls), close: vi.fn(async () => {}) }) + // Rejecting (not resolving null) is what lets `parseSessionCandidate` + // report it as an issue instead of silently dropping the session. The + // assertion is attached before the clock moves so the rejection is never + // momentarily unhandled. + const refusal = expect( + parseAgentSessionFileCached(candidate(STALLED_PATH, body(2), 1), 'linux') + ).rejects.toBeInstanceOf(WslTranscriptFsError) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + await refusal + + await releaseAndSettle() + const siblingBytes = body(2) + mocks.open.mockResolvedValue(servingHandle(siblingBytes)) + + const sibling = await parseAgentSessionFileCached( + candidate(SIBLING_PATH, siblingBytes, 1), + 'linux' + ) + expect(sibling?.messageCount).toBe(2) + }) + + it('caches no resume point when the newline probe is refused mid-append', async () => { + const first = body(2) + mocks.open.mockResolvedValue(servingHandle(first)) + const seeded = await parseAgentSessionFileCached(candidate(STALLED_PATH, first, 1), 'linux') + expect(seeded?.messageCount).toBe(2) + + const grown = body(3) + const serving = servingHandle(grown) + mocks.open.mockResolvedValue({ + // Only the 1-byte resume probe stalls; the body read stays healthy. + read: vi.fn((buffer: Buffer, offset: number, length: number, position: number) => + length === 1 ? stalls() : serving.read(buffer, offset, length, position) + ), + close: vi.fn(async () => {}) + }) + const refused = expect( + parseAgentSessionFileCached(candidate(STALLED_PATH, grown, 2), 'linux') + ).rejects.toBeInstanceOf(WslTranscriptFsError) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + await refused + + await releaseAndSettle() + mocks.open.mockResolvedValue(servingHandle(grown)) + const recovered = await parseAgentSessionFileCached(candidate(STALLED_PATH, grown, 2), 'linux') + + resetSessionParseCacheForTests() + const cold = await parseAgentSessionFileCached(candidate(STALLED_PATH, grown, 2), 'linux') + expect(recovered).toEqual(cold) + expect(recovered?.messageCount).toBe(3) + }) +}) diff --git a/src/main/ai-vault/session-scanner-parser-stream-cleanup.test.ts b/src/main/ai-vault/session-scanner-parser-stream-cleanup.test.ts new file mode 100644 index 00000000000..7470b3430d2 --- /dev/null +++ b/src/main/ai-vault/session-scanner-parser-stream-cleanup.test.ts @@ -0,0 +1,127 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { Readable } from 'node:stream' +import type * as NodeReadlineModule from 'node:readline' +import type * as WslFsAccessModule from '../native-chat/wsl-transcript-fs-access' +import type { FileWithMtime } from './session-scanner-types' + +// readline.close() leaves its input open, so a parser that stops consuming +// mid-file (a throw, a break) strands the gated transcript handle until the +// gate's deadline and delays every later scan. These pin the finally blocks. +const mocks = vi.hoisted(() => ({ + openStream: vi.fn(), + readFile: vi.fn(), + stat: vi.fn(), + createInterface: vi.fn() +})) + +vi.mock('../native-chat/wsl-transcript-fs-access', async (importOriginal) => ({ + ...(await importOriginal()), + openTranscriptReadStream: mocks.openStream, + wslGatedReadFile: mocks.readFile, + wslGatedStat: mocks.stat +})) + +vi.mock('node:readline', async (importOriginal) => ({ + ...(await importOriginal()), + createInterface: mocks.createInterface +})) + +import { parseAntigravitySessionFile } from './session-scanner-antigravity-parser' +import { parseDroidSessionFile } from './session-scanner-droid-parser' +import { parseMessageGraphSessionFile } from './session-scanner-graph-parsers' +import { parseGrokSessionFile } from './session-scanner-grok-parser' +import { parseKimiSessionFile } from './session-scanner-kimi-parser' +import { clearKimiSessionIndexCache } from './session-scanner-kimi-paths' + +const PARSE_FAILURE = 'parser failed mid-transcript' + +const opened: { path: string; stream: Readable }[] = [] +const interfaces: { close: ReturnType }[] = [] + +function file(path: string): FileWithMtime { + return { path, mtimeMs: 1, modifiedAt: '2026-06-01T10:05:00.000Z', sizeBytes: 128 } +} + +function lastOpened(): { path: string; stream: Readable } { + const entry = opened.at(-1) + if (!entry) { + throw new Error('no transcript stream was opened') + } + return entry +} + +function expectStreamTornDown(): void { + expect(lastOpened().stream.destroyed).toBe(true) + expect(interfaces.at(-1)?.close).toHaveBeenCalled() +} + +beforeEach(() => { + opened.length = 0 + interfaces.length = 0 + clearKimiSessionIndexCache() + mocks.openStream.mockReset() + mocks.readFile.mockReset() + mocks.stat.mockReset() + mocks.createInterface.mockReset() + + mocks.openStream.mockImplementation((path: string) => { + const stream = new Readable({ + read() { + this.push(null) + } + }) + opened.push({ path, stream }) + return stream + }) + // One line, then a consumer-side throw: the parser must still tear the + // stream down on its way out. + mocks.createInterface.mockImplementation(() => { + const lines = { + close: vi.fn(), + [Symbol.asyncIterator]: async function* () { + yield '{}' + throw new Error(PARSE_FAILURE) + } + } + interfaces.push(lines) + return lines + }) +}) + +describe('session parsers that stop consuming a gated transcript early', () => { + it.each([ + ['antigravity', () => parseAntigravitySessionFile(file('/w/conversation.jsonl'), 'linux')], + ['droid', () => parseDroidSessionFile(file('/w/session.jsonl'), 'linux')], + ['message graph', () => parseMessageGraphSessionFile('pi', file('/w/session.jsonl'), 'linux')] + ])('destroys the stream when the %s parse throws', async (_agent, parse) => { + await expect(parse()).rejects.toThrow(PARSE_FAILURE) + + expectStreamTornDown() + }) + + it('destroys the chat_history stream when the Grok parse swallows the failure', async () => { + mocks.readFile.mockResolvedValue(JSON.stringify({ info: { id: 'ses-1' } })) + + // Grok degrades to a summary-only session on a non-gate failure, so the + // teardown has no rejection to ride out on. + await expect( + parseGrokSessionFile(file('/w/.grok/sessions/ses-1/session.json')) + ).resolves.toBeTruthy() + + expect(lastOpened().path).toContain('chat_history.jsonl') + expectStreamTornDown() + }) + + it('destroys the wire stream when the Kimi parse swallows the failure', async () => { + mocks.readFile.mockResolvedValue(JSON.stringify({ title: 'Kimi session' })) + // No session_index.jsonl, so only the wire transcript opens a stream. + mocks.stat.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })) + + await expect( + parseKimiSessionFile(file('/w/.kimi-code/sessions/wd_app/session_abc/state.json')) + ).resolves.toBeTruthy() + + expect(lastOpened().path).toContain('wire.jsonl') + expectStreamTornDown() + }) +}) diff --git a/src/main/ai-vault/session-scanner-primary-parsers.ts b/src/main/ai-vault/session-scanner-primary-parsers.ts index 92db2241320..f554268c7e5 100644 --- a/src/main/ai-vault/session-scanner-primary-parsers.ts +++ b/src/main/ai-vault/session-scanner-primary-parsers.ts @@ -1,5 +1,5 @@ import { remoteSessionContentLines } from './remote-session-content-lines' -import { createReadStream } from 'node:fs' +import { openTranscriptReadStream } from '../native-chat/wsl-transcript-fs-access' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host' @@ -210,7 +210,7 @@ export async function parseClaudeSessionFile( platform: NodeJS.Platform = process.platform ): Promise { const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), + input: openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan'), crlfDelay: Infinity }) return parseClaudeSessionLines({ file, lines, platform }) diff --git a/src/main/ai-vault/session-scanner-scope-discovery.ts b/src/main/ai-vault/session-scanner-scope-discovery.ts index b0a4792ffd6..e787aef628e 100644 --- a/src/main/ai-vault/session-scanner-scope-discovery.ts +++ b/src/main/ai-vault/session-scanner-scope-discovery.ts @@ -1,13 +1,18 @@ -import { createReadStream } from 'node:fs' -import { readdir, stat } from 'node:fs/promises' import { createInterface } from 'node:readline' import { extname, join } from 'node:path' +import { + openTranscriptReadStream, + wslGatedReaddir, + wslGatedStat +} from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { isPathInsideOrEqual, normalizeRuntimePathSeparators } from '../../shared/cross-platform-path' import type { AiVaultScanIssue } from '../../shared/ai-vault-types' import { parseWslUncPath } from '../../shared/wsl-paths' +import { recordSessionScanIssue } from './session-scan-issues' import type { FileWithMtime } from './session-scanner-types' import { errorMessage, extractString, parseJsonObject } from './session-scanner-values' @@ -26,7 +31,18 @@ export function resetProjectDirCwdCacheForTests(): void { projectDirCwdCache.clear() } -async function cachedProjectDirCwd(projectDir: string): Promise { +// A gate refusal is a stalled WSL root, not an empty one: keep the existing +// degrade-to-empty containment but make the gap visible in the scan issues. +function recordRefusal(issues: AiVaultScanIssue[], path: string, error: unknown): void { + if (error instanceof WslTranscriptFsError) { + recordSessionScanIssue(issues, { agent: 'claude', path, message: error.message }) + } +} + +async function cachedProjectDirCwd( + projectDir: string, + issues: AiVaultScanIssue[] +): Promise { const cached = projectDirCwdCache.get(projectDir) if (cached !== undefined) { // Refresh recency so hot in-scope dirs outlive one-off ones at the cap. @@ -34,7 +50,7 @@ async function cachedProjectDirCwd(projectDir: string): Promise { projectDirCwdCache.set(projectDir, cached) return cached } - const cwd = await readProjectDirCwd(projectDir) + const cwd = await readProjectDirCwd(projectDir, issues) if (cwd) { if (projectDirCwdCache.size >= PROJECT_DIR_CWD_CACHE_MAX) { const oldest = projectDirCwdCache.keys().next() @@ -70,8 +86,8 @@ export async function discoverInScopeClaudeFiles(args: { const scopeProjectPrefixes = claudeProjectScopePrefixes(args.scopePaths) const collected = new Map() for (const rootDir of args.rootDirs) { - for (const projectDir of await listProjectDirs(rootDir, scopeProjectPrefixes)) { - const cwd = await cachedProjectDirCwd(projectDir) + for (const projectDir of await listProjectDirs(rootDir, scopeProjectPrefixes, args.issues)) { + const cwd = await cachedProjectDirCwd(projectDir, args.issues) if (!cwd || !args.scopePaths.some((scopePath) => isCwdInsideScopePath(scopePath, cwd))) { continue } @@ -148,12 +164,14 @@ function isCwdInsideScopePath(scopePath: string, cwd: string): boolean { async function listProjectDirs( rootDir: string, - scopeProjectPrefixes: ReadonlySet + scopeProjectPrefixes: ReadonlySet, + issues: AiVaultScanIssue[] ): Promise { let entries try { - entries = await readdir(rootDir, { withFileTypes: true }) - } catch { + entries = await wslGatedReaddir(rootDir, 'scan') + } catch (err) { + recordRefusal(issues, rootDir, err) return [] } return entries @@ -163,10 +181,13 @@ async function listProjectDirs( .map((entry) => join(rootDir, entry.name)) } -async function readProjectDirCwd(projectDir: string): Promise { - const files = await newestClaudeFilesInDir(projectDir) +async function readProjectDirCwd( + projectDir: string, + issues: AiVaultScanIssue[] +): Promise { + const files = await newestClaudeFilesInDir(projectDir, issues) for (const file of files.slice(0, REPRESENTATIVE_FILE_LIMIT)) { - const cwd = await readFirstCwd(file) + const cwd = await readFirstCwd(file, issues) if (cwd) { return cwd } @@ -174,11 +195,15 @@ async function readProjectDirCwd(projectDir: string): Promise { return null } -async function newestClaudeFilesInDir(projectDir: string): Promise { +async function newestClaudeFilesInDir( + projectDir: string, + issues: AiVaultScanIssue[] +): Promise { let entries try { - entries = await readdir(projectDir, { withFileTypes: true }) - } catch { + entries = await wslGatedReaddir(projectDir, 'scan') + } catch (err) { + recordRefusal(issues, projectDir, err) return [] } const newest: { path: string; mtimeMs: number }[] = [] @@ -190,18 +215,19 @@ async function newestClaudeFilesInDir(projectDir: string): Promise { try { addBoundedPath(newest, REPRESENTATIVE_FILE_LIMIT, { path, - mtimeMs: (await stat(path)).mtimeMs + mtimeMs: (await wslGatedStat(path, 'scan')).mtimeMs }) - } catch { + } catch (err) { // Best effort: unreadable candidates are ignored here and reported during // full collection if the project directory proves in-scope. + recordRefusal(issues, path, err) } } return newest.sort((left, right) => right.mtimeMs - left.mtimeMs).map((value) => value.path) } -async function readFirstCwd(filePath: string): Promise { - const input = createReadStream(filePath, { encoding: 'utf-8' }) +async function readFirstCwd(filePath: string, issues: AiVaultScanIssue[]): Promise { + const input = openTranscriptReadStream(filePath, { encoding: 'utf-8' }, 'scan') const lines = createInterface({ input, crlfDelay: Infinity }) let read = 0 try { @@ -214,7 +240,8 @@ async function readFirstCwd(filePath: string): Promise { return cwd } } - } catch { + } catch (err) { + recordRefusal(issues, filePath, err) return null } finally { // readline.close() leaves the underlying stream open; destroy it so the early @@ -234,8 +261,9 @@ async function collectClaudeFiles(args: { }): Promise { let entries try { - entries = await readdir(args.projectDir, { withFileTypes: true }) - } catch { + entries = await wslGatedReaddir(args.projectDir, 'scan') + } catch (err) { + recordRefusal(args.issues, args.projectDir, err) return } for (const entry of entries) { @@ -247,7 +275,7 @@ async function collectClaudeFiles(args: { continue } try { - const fileStat = await stat(path) + const fileStat = await wslGatedStat(path, 'scan') addBoundedFile(args.collected, args.limit, { path, mtimeMs: fileStat.mtimeMs, @@ -255,7 +283,7 @@ async function collectClaudeFiles(args: { sizeBytes: fileStat.size }) } catch (err) { - args.issues.push({ agent: 'claude', path, message: errorMessage(err) }) + recordSessionScanIssue(args.issues, { agent: 'claude', path, message: errorMessage(err) }) } } } diff --git a/src/main/ai-vault/session-scanner-service-client.ts b/src/main/ai-vault/session-scanner-service-client.ts index cfcee4c2240..4f46dc643c5 100644 --- a/src/main/ai-vault/session-scanner-service-client.ts +++ b/src/main/ai-vault/session-scanner-service-client.ts @@ -130,7 +130,7 @@ export class AiVaultScannerServiceClient { continue } const index = this.queue.findIndex((call) => call.lane === lane) - if (index < 0) { + if (index === -1) { continue } const call = this.queue.splice(index, 1)[0]! @@ -257,7 +257,7 @@ export class AiVaultScannerServiceClient { call.cancelled = true call.reject(createAiVaultScanCancelledError()) const queuedIndex = this.queue.indexOf(call) - if (queuedIndex >= 0) { + if (queuedIndex !== -1) { this.queue.splice(queuedIndex, 1) clearAiVaultServiceCall(call) this.pump() diff --git a/src/main/ai-vault/session-scanner-subagent-transcripts.ts b/src/main/ai-vault/session-scanner-subagent-transcripts.ts index d7df4aeedac..8d477f450af 100644 --- a/src/main/ai-vault/session-scanner-subagent-transcripts.ts +++ b/src/main/ai-vault/session-scanner-subagent-transcripts.ts @@ -1,4 +1,4 @@ -import { readdir } from 'node:fs/promises' +import { wslGatedReaddir } from '../native-chat/wsl-transcript-fs-access' import { basename, dirname, extname, join } from 'node:path' // Exported so discovery can prune these subtrees using the same literal that @@ -38,7 +38,7 @@ export function subagentTranscriptsDirFor(transcriptFilePath: string): string { export async function countSubagentTranscripts(transcriptFilePath: string): Promise { let entries try { - entries = await readdir(subagentTranscriptsDirFor(transcriptFilePath), { withFileTypes: true }) + entries = await wslGatedReaddir(subagentTranscriptsDirFor(transcriptFilePath), 'scan') } catch { return 0 } diff --git a/src/main/ai-vault/session-scanner-values.ts b/src/main/ai-vault/session-scanner-values.ts index b058876fda3..f7d62611adb 100644 --- a/src/main/ai-vault/session-scanner-values.ts +++ b/src/main/ai-vault/session-scanner-values.ts @@ -1,6 +1,7 @@ import { homedir } from 'node:os' import { basename, dirname, isAbsolute, join } from 'node:path' -import { readFile } from 'node:fs/promises' +import { wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { asRecord } from './session-scanner-record-value' export { asRecord } @@ -76,8 +77,15 @@ export async function readJsonObjectIfExists( filePath: string ): Promise | null> { try { - return asRecord(JSON.parse(await readFile(filePath, 'utf-8')) as unknown) - } catch { + return asRecord(JSON.parse(await wslGatedReadFile(filePath, 'utf-8', 'scan')) as unknown) + } catch (error) { + // A missing or malformed file is genuinely "no enrichment", but a gate + // refusal must reach `parseSessionCandidate` as an issue — degrading it to + // null caches the un-enriched session under an unchanged mtime, and the + // non-resumable agents that use this never re-read it. + if (error instanceof WslTranscriptFsError) { + throw error + } return null } } diff --git a/src/main/ai-vault/session-scanner-worker-client.ts b/src/main/ai-vault/session-scanner-worker-client.ts index 6b780c5086d..70e75c4f982 100644 --- a/src/main/ai-vault/session-scanner-worker-client.ts +++ b/src/main/ai-vault/session-scanner-worker-client.ts @@ -176,7 +176,7 @@ export class AiVaultScannerWorkerClient { return } const index = this.queue.indexOf(call) - if (index >= 0) { + if (index !== -1) { this.queue.splice(index, 1) this.clearCall(call) } diff --git a/src/main/ai-vault/session-scanner.ts b/src/main/ai-vault/session-scanner.ts index 3a98b7018ac..b4ef6f06ce7 100644 --- a/src/main/ai-vault/session-scanner.ts +++ b/src/main/ai-vault/session-scanner.ts @@ -1,4 +1,3 @@ -import { readFile } from 'node:fs/promises' import type { AiVaultListResult, AiVaultScanIssue, @@ -14,6 +13,7 @@ import { } from './codex-session-root-dedup' import { createAntigravityWorkspaceResolver, + readLocalAntigravityHistory, type AntigravityWorkspaceResolver } from './session-scanner-antigravity-history' import { antigravityHistoryPathForBrainDir } from './session-scanner-antigravity-paths' @@ -27,6 +27,7 @@ import { parseAgentSessionFileCached, type SessionParseStats } from './session-scanner-parse-cache' +import { recordSessionScanIssue } from './session-scan-issues' import { discoverInScopeClaudeFiles } from './session-scanner-scope-discovery' import { DEFAULT_CODEX_HOME_DIR, @@ -71,7 +72,9 @@ export async function scanAiVaultSessions( const executionHostId = options.executionHostId ?? LOCAL_EXECUTION_HOST_ID const issues: AiVaultScanIssue[] = [] const parseStats = createSessionParseStats() - const antigravityWorkspaceResolver = createAntigravityWorkspaceResolver(readOptionalTextFile) + const antigravityWorkspaceResolver = createAntigravityWorkspaceResolver( + readLocalAntigravityHistory + ) // Why: persisted entries must be seeded before any candidate is parsed, or // the cold scan gains nothing from the cache file (#9210). throwIfAiVaultScanCancelled(options.signal) @@ -255,7 +258,7 @@ async function parseSessionCandidates(args: { for (const result of results) { if (result.issue) { - args.issues.push(result.issue) + recordSessionScanIssue(args.issues, result.issue) } if (result.session) { sessions.push(result.session) @@ -305,14 +308,6 @@ async function parseSessionCandidate( } } -async function readOptionalTextFile(path: string): Promise { - try { - return await readFile(path, 'utf-8') - } catch { - return null - } -} - function withSessionExecutionHost( session: AiVaultSession, executionHostId: ExecutionHostId diff --git a/src/main/ai-vault/session-title-file-reader-wsl-stall.test.ts b/src/main/ai-vault/session-title-file-reader-wsl-stall.test.ts new file mode 100644 index 00000000000..337c2064d8a --- /dev/null +++ b/src/main/ai-vault/session-title-file-reader-wsl-stall.test.ts @@ -0,0 +1,83 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFsPromisesModule from 'node:fs/promises' + +const UNC_PATH = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.claude\\projects\\p\\stalled.jsonl' +const STALLED_SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const LOCAL_SESSION_ID = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff' + +const mocks = vi.hoisted(() => ({ lstat: vi.fn() })) + +vi.mock('node:fs/promises', async (importOriginal) => { + const original = await importOriginal() + return { + ...original, + // Only the WSL request is faked; the local sibling reads a real temp file. + lstat: (path: string, ...rest: unknown[]) => + path.startsWith('\\\\') + ? mocks.lstat(path) + : (original.lstat as (...args: unknown[]) => unknown)(path, ...rest) + } +}) + +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { readAiVaultSessionTitlesFromFiles } from './session-title-file-reader' +import { resetSessionParseCacheForTests } from './session-scanner-parse-cache' +import { WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS } from '../native-chat/wsl-transcript-fs-gate' + +let releaseStall: (() => void) | undefined +let tempRoot: string | undefined + +function stalls(): Promise { + return new Promise((resolve) => { + releaseStall = () => resolve(undefined as never) + }) +} + +function userRecord(sessionId: string, text: string): string { + return JSON.stringify({ + type: 'user', + sessionId, + timestamp: new Date(1740000000000).toISOString(), + cwd: '/repo/app', + gitBranch: 'main', + message: { role: 'user', content: text } + }) +} + +beforeEach(async () => { + resetSessionParseCacheForTests() + mocks.lstat.mockReset() + releaseStall = undefined + tempRoot = await mkdtemp(join(tmpdir(), 'orca-title-stall-')) +}) + +afterEach(async () => { + releaseStall?.() + releaseStall = undefined + await vi.advanceTimersByTimeAsync(0) + vi.useRealTimers() + if (tempRoot) { + await rm(tempRoot, { recursive: true, force: true }) + tempRoot = undefined + } +}) + +describe('AI Vault session titles with a stalled WSL transcript lstat', () => { + it('drops only the stalled request and still returns the rest of the batch', async () => { + const localPath = join(tempRoot!, `${LOCAL_SESSION_ID}.jsonl`) + await writeFile(localPath, `${userRecord(LOCAL_SESSION_ID, 'hello world')}\n`) + mocks.lstat.mockImplementation(stalls) + vi.useFakeTimers() + + const pending = readAiVaultSessionTitlesFromFiles([ + { agent: 'claude', sessionId: STALLED_SESSION_ID, transcriptPath: UNC_PATH }, + { agent: 'claude', sessionId: LOCAL_SESSION_ID, transcriptPath: localPath } + ]) + await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS + 1) + + const { titles } = await pending + expect(titles).toEqual([{ agent: 'claude', sessionId: LOCAL_SESSION_ID, title: 'hello world' }]) + }) +}) diff --git a/src/main/ai-vault/session-title-file-reader.ts b/src/main/ai-vault/session-title-file-reader.ts index 799d2b95da9..15228d132bb 100644 --- a/src/main/ai-vault/session-title-file-reader.ts +++ b/src/main/ai-vault/session-title-file-reader.ts @@ -1,4 +1,4 @@ -import { lstat } from 'node:fs/promises' +import { wslGatedLstat } from '../native-chat/wsl-transcript-fs-access' import { AI_VAULT_SESSION_TITLE_REQUEST_MAX_COUNT, type AiVaultSessionTitle, @@ -27,7 +27,7 @@ async function readOneTitle( return cache?.get(request) ?? null } try { - const stats = await lstat(transcriptPath) + const stats = await wslGatedLstat(transcriptPath, 'scan', signal) if (!stats.isFile() || signal?.aborted) { return null } diff --git a/src/main/ai-vault/session-title-request-paths.ts b/src/main/ai-vault/session-title-request-paths.ts index 86e78ebc397..5e25e512d92 100644 --- a/src/main/ai-vault/session-title-request-paths.ts +++ b/src/main/ai-vault/session-title-request-paths.ts @@ -1,5 +1,6 @@ import type { AiVaultSessionTitleRequest } from '../../shared/ai-vault-session-title' import { toHostReadableTranscriptPath } from '../native-chat/host-readable-transcript-path' +import { wslTranscriptFsRefusal } from '../native-chat/wsl-transcript-fs-gate' export function resolveHostReadableAiVaultTitleRequests( requests: AiVaultSessionTitleRequest[], @@ -10,7 +11,15 @@ export function resolveHostReadableAiVaultTitleRequests( if (!request.transcriptPath || signal?.aborted) { return request } - const transcriptPath = await toHostReadableTranscriptPath(request.transcriptPath) + let transcriptPath: string | null + try { + transcriptPath = await toHostReadableTranscriptPath(request.transcriptPath) + } catch (error) { + // Why: one stalled distro's path must not fail the whole titles batch; + // degrade to the id-only shape like any unreadable path. + void wslTranscriptFsRefusal(error) // rethrows anything that is not a gate refusal + transcriptPath = null + } return transcriptPath && !signal?.aborted ? { ...request, transcriptPath } : { agent: request.agent, sessionId: request.sessionId } diff --git a/src/main/attribution/terminal-attribution-path-env-casing.test.ts b/src/main/attribution/terminal-attribution-path-env-casing.test.ts deleted file mode 100644 index 95ff6fdc2e3..00000000000 --- a/src/main/attribution/terminal-attribution-path-env-casing.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { applyTerminalAttributionEnv } from './terminal-attribution' - -describe('applyTerminalAttributionEnv PATH key casing', () => { - let tmpRoot: string | null = null - - afterEach(() => { - if (tmpRoot) { - rmSync(tmpRoot, { force: true, recursive: true }) - tmpRoot = null - } - }) - - function makeTmpRoot(): string { - tmpRoot = mkdtempSync(join(tmpdir(), 'orca-attribution-path-casing-')) - return tmpRoot - } - - // Why: a Windows child that inherits both spellings crashes the packaged orca.exe launcher - // with "Item has already been added. Key in dictionary: 'PATH'" (stablyai/orca#12046). - function pathEnvKeys(env: Record): string[] { - return Object.keys(env).filter((key) => /^path$/i.test(key)) - } - - it('writes back the inherited Windows `Path` spelling instead of adding `PATH`', () => { - const root = makeTmpRoot() - const userDataPath = join(root, 'user-data') - const baseEnv: Record = { - Path: 'C:\\Windows\\system32;C:\\Program Files\\Git\\cmd', - SystemRoot: 'C:\\Windows' - } - - applyTerminalAttributionEnv(baseEnv, { - enabled: true, - platform: 'win32', - shellFamily: 'native-windows', - userDataPath - }) - - const win32Dir = join(userDataPath, 'orca-terminal-attribution', 'win32') - const pathEntries = baseEnv.Path.split(';') - - expect(pathEnvKeys(baseEnv)).toEqual(['Path']) - expect(pathEntries[0]).toBe(win32Dir) - expect(pathEntries).toContain('C:\\Program Files\\Git\\cmd') - }) - - // Why: Win32 resolves a duplicated variable by taking the first match in the block, so the - // shim must land on the first-listed spelling and the shadowed one must keep its value — - // dropping it would promote it the moment anything downstream removes the live key. - it.each([ - { first: 'PATH', second: 'Path' }, - { first: 'Path', second: 'PATH' } - ])( - 'prepends the shim onto the first-listed `$first` and leaves `$second` untouched', - ({ first, second }) => { - const root = makeTmpRoot() - const userDataPath = join(root, 'user-data') - const baseEnv: Record = { - [first]: 'C:\\tools\\bin;C:\\Windows\\system32', - [second]: 'C:\\Windows\\system32' - } - - applyTerminalAttributionEnv(baseEnv, { - enabled: true, - platform: 'win32', - shellFamily: 'native-windows', - userDataPath - }) - - const win32Dir = join(userDataPath, 'orca-terminal-attribution', 'win32') - expect(baseEnv[first].split(';')).toEqual([ - win32Dir, - 'C:\\tools\\bin', - 'C:\\Windows\\system32' - ]) - expect(baseEnv[second]).toBe('C:\\Windows\\system32') - } - ) - - it('keeps a shadowed duplicate when the live spelling strips down to nothing', () => { - const root = makeTmpRoot() - const userDataPath = join(root, 'user-data') - const shimDir = join(userDataPath, 'orca-terminal-attribution', 'win32') - const baseEnv: Record = { Path: shimDir, PATH: 'C:\\Windows\\system32' } - - applyTerminalAttributionEnv(baseEnv, { - enabled: false, - platform: 'win32', - shellFamily: 'native-windows', - userDataPath - }) - - expect(pathEnvKeys(baseEnv)).toEqual(['PATH']) - expect(baseEnv.PATH).toBe('C:\\Windows\\system32') - }) - - it('strips shim entries from the inherited `Path` when attribution is disabled', () => { - const root = makeTmpRoot() - const userDataPath = join(root, 'user-data') - const shimDir = join(userDataPath, 'orca-terminal-attribution', 'win32') - const baseEnv: Record = { Path: `${shimDir};C:\\Windows\\system32` } - - applyTerminalAttributionEnv(baseEnv, { - enabled: false, - platform: 'win32', - shellFamily: 'native-windows', - userDataPath - }) - - expect(pathEnvKeys(baseEnv)).toEqual(['Path']) - expect(baseEnv.Path).toBe('C:\\Windows\\system32') - }) - - // Why: the daemon receives a sparse env patch with no path key and re-merges its own block - // underneath it, so guessing the spelling here hands the child both. - it.each([ - { hostKey: 'PATH', otherKey: 'Path' }, - { hostKey: 'Path', otherKey: 'PATH' } - ])('adopts a host block spelt `$hostKey` on a path-less env', ({ hostKey, otherKey }) => { - const root = makeTmpRoot() - const userDataPath = join(root, 'user-data') - const inherited = { PATH: process.env.PATH, Path: process.env.Path } - delete process.env.PATH - delete process.env.Path - process.env[hostKey] = 'C:\\Windows\\system32' - - try { - const baseEnv: Record = { SystemRoot: 'C:\\Windows' } - - applyTerminalAttributionEnv(baseEnv, { - enabled: true, - platform: 'win32', - shellFamily: 'native-windows', - userDataPath - }) - - expect(pathEnvKeys(baseEnv)).toEqual([hostKey]) - expect(baseEnv[otherKey]).toBeUndefined() - } finally { - delete process.env[hostKey] - for (const [key, value] of Object.entries(inherited)) { - if (value !== undefined) { - process.env[key] = value - } - } - } - }) - - it('leaves a case-sensitive POSIX `Path` variable alone', () => { - const root = makeTmpRoot() - const baseEnv: Record = { - PATH: '/usr/bin:/bin', - Path: '/decoy' - } - - applyTerminalAttributionEnv(baseEnv, { - enabled: true, - platform: 'linux', - userDataPath: join(root, 'user-data') - }) - - expect(baseEnv.Path).toBe('/decoy') - expect(baseEnv.PATH.split(':')).toContain('/usr/bin') - }) -}) diff --git a/src/main/attribution/terminal-attribution-win32-dash-argument.test.ts b/src/main/attribution/terminal-attribution-win32-dash-argument.test.ts deleted file mode 100644 index 810322a53c9..00000000000 --- a/src/main/attribution/terminal-attribution-win32-dash-argument.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { spawnSync } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { applyTerminalAttributionEnv } from './terminal-attribution' - -// Why (#12046 follow-up): `powershell.exe -File ' + ) + return + } + response.end(` + + + FedCM fallback oracle + + + + pending + + + + `) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const port = (server.address() as AddressInfo).port + return { url: `http://127.0.0.1:${port}/`, close: () => closeServer(server) } +} + +test('embedded browser omits unusable FedCM and reaches the popup fallback', async ({ + electronApp, + orcaPage +}) => { + const server = await startFedCmFallbackServer() + try { + await ensureTerminalVisible(orcaPage) + const worktreeId = await getActiveWorktreeId(orcaPage) + expect(worktreeId).not.toBeNull() + const browserTabId = await orcaPage.evaluate( + ({ targetWorktreeId, url }) => { + const tab = window.__store!.getState().createBrowserTab(targetWorktreeId!, url, { + title: 'FedCM fallback oracle', + activate: true + }) + return tab.id + }, + { targetWorktreeId: worktreeId, url: server.url } + ) + const readGuest = async (expression: string): Promise => + orcaPage.evaluate( + async ({ targetBrowserTabId, script }) => { + const slot = document.querySelector( + `[data-browser-overlay-tab-id="${targetBrowserTabId}"]` + ) + const webview = slot?.querySelector('webview') as Electron.WebviewTag | null + if (!webview) { + throw new Error(`Missing webview for browser tab ${targetBrowserTabId}`) + } + return (await webview.executeJavaScript(script)) as T + }, + { targetBrowserTabId: browserTabId, script: expression } + ) + + await expect + .poll(() => readGuest('document.title'), { timeout: 10_000 }) + .toBe('FedCM fallback oracle') + const capabilities = await readGuest<{ + hasIdentityCredential: boolean + hasIdentityProvider: boolean + }>('JSON.parse(document.querySelector("#capabilities").textContent)') + expect.soft(capabilities).toEqual({ + hasIdentityCredential: false, + hasIdentityProvider: false + }) + + await readGuest('document.querySelector("#sign-in").click()') + const path = await readGuest('document.querySelector("#path").textContent') + expect.soft(path).toBe('popup-live') + await expect + .poll(() => + electronApp.evaluate(async ({ webContents }) => { + const popup = webContents.getAllWebContents().find((contents) => { + return contents.getURL().endsWith('/popup') + }) + if (!popup) { + return null + } + return { + openerLive: await popup.executeJavaScript('Boolean(window.opener)'), + title: await popup.executeJavaScript('document.title'), + url: popup.getURL() + } + }) + ) + .toEqual({ + openerLive: true, + title: 'Popup fallback', + url: `${server.url}popup` + }) + await expect + .poll(() => readGuest('window.popupMessages')) + .toEqual(['popup-opener-live']) + } finally { + await server.close() + } +}) diff --git a/tests/e2e/chinese-ime-chat-input-repro.spec.ts b/tests/e2e/chinese-ime-chat-input-repro.spec.ts index 8c57b8e6a9f..9c72e8cdd4d 100644 --- a/tests/e2e/chinese-ime-chat-input-repro.spec.ts +++ b/tests/e2e/chinese-ime-chat-input-repro.spec.ts @@ -305,7 +305,7 @@ async function readPromptState(page: Page): Promise .filter((value): value is string => value !== null) const promptIndex = content.lastIndexOf(PROMPT) const liveLine = - promptIndex >= 0 ? (content.slice(promptIndex + PROMPT.length).split(/\r?\n/)[0] ?? '') : '' + promptIndex !== -1 ? (content.slice(promptIndex + PROMPT.length).split(/\r?\n/)[0] ?? '') : '' return { model: liveLine.trimEnd(), cursor: Array.from(liveLine.trimEnd()).length, diff --git a/tests/e2e/codex-composer-echo-latency-probe.ts b/tests/e2e/codex-composer-echo-latency-probe.ts index 9fc9cabf2c7..c49d98d3708 100644 --- a/tests/e2e/codex-composer-echo-latency-probe.ts +++ b/tests/e2e/codex-composer-echo-latency-probe.ts @@ -112,7 +112,7 @@ export async function installCodexEchoLatencyProbe(page: Page, target: string): const observeRender = (): void => { renderEvents += 1 const paintedAt = performance.now() - for (const entry of awaitingRender.splice(0, awaitingRender.length)) { + for (const entry of awaitingRender.splice(0)) { entry.sample.keyToRenderMs = paintedAt - entry.startedAt } } diff --git a/tests/e2e/cross-version-wire/cross-version-reattach-authorization.unit.test.ts b/tests/e2e/cross-version-wire/cross-version-reattach-authorization.unit.test.ts new file mode 100644 index 00000000000..50eebfeda95 --- /dev/null +++ b/tests/e2e/cross-version-wire/cross-version-reattach-authorization.unit.test.ts @@ -0,0 +1,156 @@ +import { beforeAll, describe, expect, it, vi } from 'vitest' + +// Why these three: `main/ipc/pty.ts` and `main/runtime/orca-runtime.ts` are real +// production modules here, so their Electron/native edges need stand-ins. Nothing +// on the decision path under test is mocked. +vi.mock('electron', () => ({ + BrowserWindow: undefined, + app: { isPackaged: true, getPath: () => '/tmp/orca-user-data', getVersion: () => '0.0.0-test' }, + powerMonitor: { on: vi.fn() }, + nativeTheme: { shouldUseDarkColors: false }, + ipcMain: { + handle: vi.fn(), + on: vi.fn(), + removeHandler: vi.fn(), + removeAllListeners: vi.fn() + } +})) +vi.mock('node-pty', () => ({ spawn: vi.fn() })) +vi.mock('psl', () => ({ parse: () => ({ domain: null }) })) + +const { resolveBaselineReleaseRef } = await import('./release-checkout') +const { driveHostRecoveryAuthorization, SKEW_HOST_PANE } = + await import('./reattach-recovery-authorization-skew') +const { loadTerminalWireBuild, WORKING_TREE } = await import('./versioned-terminal-wire') +type TerminalWireBuild = Awaited> +type Outcome = Awaited> + +const SUITE_TIMEOUT_MS = 180_000 + +let current: TerminalWireBuild +let baseline: TerminalWireBuild +let currentHost: Outcome +let baselineHost: Outcome +let currentHostAppIdSpace: Outcome +let baselineHostAppIdSpace: Outcome + +beforeAll(async () => { + current = await loadTerminalWireBuild(WORKING_TREE) + baseline = await loadTerminalWireBuild(resolveBaselineReleaseRef()) + // Serial on purpose: `ipc/pty.ts` keeps module-level provider state per build. + currentHost = await driveHostRecoveryAuthorization({ + hostBuild: current, + runtimePtyIdSpace: 'relay' + }) + baselineHost = await driveHostRecoveryAuthorization({ + hostBuild: baseline, + runtimePtyIdSpace: 'relay' + }) + currentHostAppIdSpace = await driveHostRecoveryAuthorization({ + hostBuild: current, + runtimePtyIdSpace: 'app' + }) + baselineHostAppIdSpace = await driveHostRecoveryAuthorization({ + hostBuild: baseline, + runtimePtyIdSpace: 'app' + }) +}, SUITE_TIMEOUT_MS) + +function expectDriveActuallyRan(outcome: Outcome): void { + // The anti-vacuous-pass oracle: a host that never attached, never published a + // failure, or never reached its recovery gate proves nothing about refusal. + expect(outcome.attachedBeforeFault).toBe(true) + expect(outcome.publishedFailure).not.toBe('') + expect(outcome.recoverPaneOutcome).toMatch(/^(granted|refused)$/) +} + +describe('cross-version reattach recovery authorization', () => { + it( + 'skews a real published release against current code', + () => { + expect(baseline.revision).toMatch(/^[0-9a-f]{40}$/) + expect(baseline.revision).not.toBe(current.revision) + expect(currentHost.publishedFailure).not.toBe(baselineHost.publishedFailure) + }, + SUITE_TIMEOUT_MS + ) + + it( + 'the current host neither expires its own lease nor grants a replacement shell', + () => { + expectDriveActuallyRan(currentHost) + // Rule 3 of remote-wire-compatibility: what the host publishes reaches old + // clients with no wire change. Here the host also acts on it locally — and + // a live shell whose output source must be restored is not an expiry, so + // no durable state may be destroyed on its behalf. + expect(currentHost.leaseWrites).toEqual([]) + expect(currentHost.leaseStateAfterFailure).toBe('attached') + // Any client version may still ASK for a replacement. The host is what + // must refuse, before the mutation. + expect(currentHost.recoverPaneOutcome).toBe('refused') + expect(currentHost.recoverPaneError).toContain('terminal_not_recoverable') + expect(currentHost.replacementShellsCreated).toBe(0) + }, + SUITE_TIMEOUT_MS + ) + + it( + 'the current host refuses whichever id space the pane was registered under', + () => { + // The refusal above must not be an id that happened not to match. Under the + // id shape production actually registers, the current host still writes no + // lease and still creates no shell. + expectDriveActuallyRan(currentHostAppIdSpace) + expect(currentHostAppIdSpace.leaseWrites).toEqual([]) + expect(currentHostAppIdSpace.recoverPaneOutcome).toBe('refused') + expect(currentHostAppIdSpace.replacementShellsCreated).toBe(0) + }, + SUITE_TIMEOUT_MS + ) + + it( + 'the published release expires the lease and grants the duplicate shell', + () => { + // The control. Same relay answer, same pane, same request — only the host + // build differs, and the legacy publication authorizes the mutation the + // current host refuses. Without this the case above could pass because the + // harness never reaches a grant at all. + expectDriveActuallyRan(baselineHost) + expect(baselineHost.leaseWrites).toEqual([ + { ptyId: SKEW_HOST_PANE.relaySessionId, state: 'expired' } + ]) + expect(baselineHost.leaseStateAfterFailure).toBe('expired') + expect(baselineHost.recoverPaneOutcome).toBe('granted') + expect(baselineHost.replacementShellsCreated).toBe(1) + // Recorded, not asserted as desirable: the legacy grant is only reachable + // when the pane's runtime PTY id is the RELAY id. `ipc/pty.ts` registers the + // APP id while writing the lease under the relay id, and the gate compares + // them directly — so under the shape production registers, the legacy host + // refuses too. That id-space mismatch needs its own decision; it is not what + // this branch changed. + expect(baselineHostAppIdSpace.leaseWrites).toEqual([ + { ptyId: SKEW_HOST_PANE.relaySessionId, state: 'expired' } + ]) + expect(baselineHostAppIdSpace.recoverPaneOutcome).toBe('refused') + }, + SUITE_TIMEOUT_MS + ) + + it( + 'the two hosts differ only in what they authorized, from the same relay answer', + () => { + // Names the skew explicitly so a future change that converges the two builds + // cannot quietly turn this file into a pair of tautologies. + expect({ + lease: currentHost.leaseStateAfterFailure, + recovery: currentHost.recoverPaneOutcome, + shells: currentHost.replacementShellsCreated + }).not.toEqual({ + lease: baselineHost.leaseStateAfterFailure, + recovery: baselineHost.recoverPaneOutcome, + shells: baselineHost.replacementShellsCreated + }) + }, + SUITE_TIMEOUT_MS + ) +}) diff --git a/tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts b/tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts index e49e0be3ecb..2deffa15253 100644 --- a/tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts +++ b/tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts @@ -1,5 +1,11 @@ import { afterEach, beforeAll, describe, expect, it } from 'vitest' -import { resolveBaselineReleaseRef } from './release-checkout' +import { + capturePublishedRestoreRequiredFailure, + driveClientReattachFailure, + SKEW_PANE, + type ClientReattachFailureOutcome +} from './reattach-failure-publication-skew' +import { resolveBaselineReleaseRef, selectLatestStableReleaseTag } from './release-checkout' import { JOURNEY_INPUTS, JOURNEY_STEPS, @@ -92,6 +98,18 @@ function expectWireCompatible(record: JourneyRecord): void { } describe('cross-version remote terminal wire', () => { + it('ignores legacy, mobile, and prerelease tags when selecting the baseline', () => { + expect( + selectLatestStableReleaseTag([ + 'v799', + 'mobile-v9.0.0', + 'v1.4.177-rc.3', + 'v1.4.175', + 'v1.4.176' + ]) + ).toBe('v1.4.176') + }) + it( 'skews current code against a real published release', () => { @@ -134,3 +152,98 @@ describe('cross-version remote terminal wire', () => { SUITE_TIMEOUT_MS ) }) + +/** + * The opcode journey above proves frames survive skew. It cannot see this: the + * failure token a reattach publishes is a plain string on an existing error + * channel, so nothing is rejected and nothing negotiates — yet the token decides + * whether the receiving client asks the host to REPLACE the pane's shell. + */ +function expectDriveActuallyRan(outcome: ClientReattachFailureOutcome): void { + expect(outcome.connectedBeforeFault).toBe(true) + expect(outcome.subscribedHandles[0]).toBe(SKEW_PANE.handle) + expect(outcome.methodsAfterFailure).toContain('terminal.resolvePane') +} + +describe('cross-version reattach failure publication', () => { + let currentPublication: string + let baselinePublication: string + + beforeAll(async () => { + currentPublication = await capturePublishedRestoreRequiredFailure(current) + baselinePublication = await capturePublishedRestoreRequiredFailure(baseline) + }, SUITE_TIMEOUT_MS) + + it( + 'the two builds publish different tokens for the same live-shell reattach', + () => { + // Guards the whole block: identical publications would make every case below + // pass for a reason that has nothing to do with skew. + expect(currentPublication).not.toBe(baselinePublication) + expect(baselinePublication).toContain('SSH_SESSION_EXPIRED') + expect(currentPublication).not.toContain('SSH_SESSION_EXPIRED') + }, + SUITE_TIMEOUT_MS + ) + + it( + 'the new host publication mutates nothing on an old client', + async () => { + const outcome = await driveClientReattachFailure({ + clientBuild: baseline, + publishedFailure: currentPublication + }) + expectDriveActuallyRan(outcome) + // The old client has no branch for this token, so it stops at its error + // surface — unsupported semantics failing before mutation, not adopting a + // replacement shell it was never granted. It fails visibly rather than + // silently, which is the difference between "fenced" and "dropped". + expect(outcome.paneReplacementRequests).toEqual([]) + expect(outcome.subscribedHandles).not.toContain(SKEW_PANE.replacementHandle) + expect(outcome.surfacedErrors).toHaveLength(1) + }, + SUITE_TIMEOUT_MS + ) + + it( + 'the new host publication mutates nothing on a new client', + async () => { + const outcome = await driveClientReattachFailure({ + clientBuild: current, + publishedFailure: currentPublication + }) + expectDriveActuallyRan(outcome) + expect(outcome.paneReplacementRequests).toEqual([]) + expect(outcome.subscribedHandles).not.toContain(SKEW_PANE.replacementHandle) + expect(outcome.surfacedErrors).toHaveLength(1) + }, + SUITE_TIMEOUT_MS + ) + + it( + 'the old host publication still replaces the pane on both clients', + async () => { + // The control that keeps the two cases above honest. The same driver, the + // same fault, the same clients: only the publishing build differs, and the + // legacy token still authorizes `terminal.recoverPane`. If the current host + // regressed to publishing expiry for a live shell, the cases above would + // look exactly like this one and fail. + for (const clientBuild of [baseline, current]) { + const outcome = await driveClientReattachFailure({ + clientBuild, + publishedFailure: baselinePublication + }) + expectDriveActuallyRan(outcome) + expect(outcome.paneReplacementRequests).toEqual([ + { + paneKey: SKEW_PANE.paneKey, + worktreeId: SKEW_PANE.worktreeId, + expectedTerminal: SKEW_PANE.handle + } + ]) + expect(outcome.subscribedHandles).toContain(SKEW_PANE.replacementHandle) + } + }, + SUITE_TIMEOUT_MS + ) +}) diff --git a/tests/e2e/cross-version-wire/reattach-failure-publication-skew.ts b/tests/e2e/cross-version-wire/reattach-failure-publication-skew.ts new file mode 100644 index 00000000000..b7869c9f72b --- /dev/null +++ b/tests/e2e/cross-version-wire/reattach-failure-publication-skew.ts @@ -0,0 +1,290 @@ +import { expect, vi } from 'vitest' +import { + importBuildModule, + type TerminalWireBuild, + type WireCodec +} from './versioned-terminal-wire' + +/** + * The second half of the cross-version contract: not "does the frame decode", but + * "what does the receiving build DO with what the other build publishes". + * + * A reattach whose output source must be re-established is the case this program + * changed. The host publishes a failure token for it, and the client turns that + * token into either nothing or `terminal.recoverPane` — a host-side mutation that + * replaces the pane's shell. Because the token is a plain string on an existing + * error channel, no opcode changes and no decoder rejects anything; the only way + * to see the skew is to run a real host build's publication into a real client + * build's decision. + */ + +const CONNECTION_ID = 'conn-1' +const SESSION_ID = 'pty-old' +const RUNTIME_ENVIRONMENT_ID = 'env-1' +const PANE_TAB_ID = 'tab-1' +const PANE_LEAF_ID = 'pane:1' +const PANE_WORKTREE_ID = 'wt-1' +const PANE_HANDLE = 'terminal-1' +const PANE_PTY_ID = `remote:${RUNTIME_ENVIRONMENT_ID}@@${PANE_HANDLE}` +const REPLACEMENT_HANDLE = 'terminal-2' +const DRIVE_TIMEOUT_MS = 10_000 + +type SshProviderModule = { + SshPtyProvider: new ( + connectionId: string, + mux: unknown + ) => { spawn: (options: unknown) => Promise } +} + +/** + * Drive a build's REAL `SshPtyProvider` through a reattach the relay answers with + * `sourceRecovery.restoreRequired`, and return the message that build publishes. + * Nothing here hardcodes a token, so the oracle moves when production moves. + */ +export async function capturePublishedRestoreRequiredFailure( + build: TerminalWireBuild +): Promise { + const module = (await importBuildModule( + build.label, + 'main/providers/ssh-pty-provider.ts' + )) as unknown as SshProviderModule + const mux = { + request: vi.fn().mockResolvedValue({ + incarnationId: 'incarnation-reattached', + sourceRecovery: { status: 'restoreRequired', reason: 'checkpointUnavailable' } + }), + notify: vi.fn(), + onNotification: vi.fn().mockReturnValue(vi.fn()) + } + const provider = new module.SshPtyProvider(CONNECTION_ID, mux) + try { + await provider.spawn({ cols: 80, rows: 24, sessionId: SESSION_ID }) + } catch (error) { + return error instanceof Error ? error.message : String(error) + } + throw new Error( + `${build.label}: reattach with sourceRecovery=restoreRequired resolved instead of failing closed` + ) +} + +export type ClientReattachFailureOutcome = { + clientLabel: string + /** Runtime RPC methods the client called after the failure, in order. */ + methodsAfterFailure: string[] + /** `terminal.recoverPane` params — a host mutation that replaces the pane's shell. */ + paneReplacementRequests: Record[] + /** Messages the client put on the pane's red error surface. */ + surfacedErrors: string[] + /** Handles the client subscribed to, including any replacement it adopted. */ + subscribedHandles: string[] + /** The client reached a genuinely connected pane before the fault was injected. */ + connectedBeforeFault: boolean +} + +type TransportModule = { + createRemoteRuntimePtyTransport: ( + environmentId: string, + options: Record + ) => { + attach: (options: Record) => void + isConnected: () => boolean + destroy?: () => void + } +} + +function paneResult(handle: string, paneKey: string, worktreeId: string): unknown { + const separator = paneKey.indexOf(':') + return { + ok: true, + result: { + terminal: { + handle, + tabId: paneKey.slice(0, separator), + leafId: paneKey.slice(separator + 1), + worktreeId + } + } + } +} + +function emitSnapshot( + codec: WireCodec, + send: (bytes: Uint8Array) => void, + streamId: number, + data: string +): void { + const opcodes = codec.TerminalStreamOpcode + send( + codec.encodeTerminalStreamFrame({ + opcode: Number(opcodes.SnapshotStart), + streamId, + seq: 1, + payload: codec.encodeTerminalStreamJson({ kind: 'scrollback' }) + }) + ) + send( + codec.encodeTerminalStreamFrame({ + opcode: Number(opcodes.SnapshotChunk), + streamId, + seq: 2, + payload: codec.encodeTerminalStreamText(data) + }) + ) + send( + codec.encodeTerminalStreamFrame({ + opcode: Number(opcodes.SnapshotEnd), + streamId, + seq: 3, + payload: new Uint8Array() + }) + ) +} + +async function settle(label: string, predicate: () => boolean): Promise { + try { + await vi.waitFor(() => expect(predicate()).toBe(true), { + timeout: DRIVE_TIMEOUT_MS, + interval: 5 + }) + } catch { + throw new Error(`Reattach-failure skew drive stalled at: ${label}`) + } +} + +/** + * Attach one client build to a live remote pane, then fail its post-outage + * resubscribe with `publishedFailure` — the exact string a host build published. + * The fault lands on `terminal.resolvePane` over the same Electron IPC boundary + * the transport really uses, so every lifecycle route stays reachable. + */ +export async function driveClientReattachFailure(args: { + clientBuild: TerminalWireBuild + publishedFailure: string +}): Promise { + const { clientBuild, publishedFailure } = args + const codec = clientBuild.codec + const methodLog: string[] = [] + const paneReplacementRequests: Record[] = [] + const surfacedErrors: string[] = [] + const sentFrames: Uint8Array[] = [] + let resolvePaneFailure: Error | null = null + let streamCallbacks: { + onResponse: (response: unknown) => void + onBinary?: (bytes: Uint8Array) => void + onClose?: () => void + } | null = null + + const call = vi.fn(async (request: { method: string; params?: unknown }) => { + methodLog.push(request.method) + const params = (request.params ?? {}) as { paneKey?: string; worktreeId?: string } + if (request.method === 'terminal.resolvePane') { + const failure = resolvePaneFailure + if (failure) { + resolvePaneFailure = null + throw failure + } + return paneResult(PANE_HANDLE, params.paneKey ?? '', params.worktreeId ?? '') + } + if (request.method === 'terminal.recoverPane') { + paneReplacementRequests.push(request.params as Record) + return paneResult(REPLACEMENT_HANDLE, params.paneKey ?? '', params.worktreeId ?? '') + } + return { ok: true, result: { terminal: { handle: PANE_HANDLE } } } + }) + + const subscribe = vi.fn(async (_args: unknown, callbacks: typeof streamCallbacks) => { + streamCallbacks = callbacks + queueMicrotask(() => callbacks?.onResponse({ ok: true, result: { type: 'ready' } })) + return { + unsubscribe: vi.fn(), + sendBinary: (bytes: Uint8Array) => { + sentFrames.push(bytes) + } + } + }) + + vi.stubGlobal('window', { + api: { runtimeEnvironments: { call, subscribe } }, + location: { search: '' } + }) + + const subscribePayloads = (): { streamId: number; terminal: string }[] => + sentFrames.flatMap((bytes) => { + const frame = codec.decodeTerminalStreamFrame(bytes) + if (!frame || frame.opcode !== Number(codec.TerminalStreamOpcode.Subscribe)) { + return [] + } + const payload = codec.decodeTerminalStreamJson<{ streamId: number; terminal: string }>( + frame.payload + ) + return payload ? [payload] : [] + }) + + const module = (await importBuildModule( + clientBuild.label, + 'renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts' + )) as unknown as TransportModule + + const transport = module.createRemoteRuntimePtyTransport(RUNTIME_ENVIRONMENT_ID, { + worktreeId: PANE_WORKTREE_ID, + tabId: PANE_TAB_ID, + leafId: PANE_LEAF_ID + }) + try { + transport.attach({ + existingPtyId: PANE_PTY_ID, + cols: 80, + rows: 24, + callbacks: { + onError: (message: string) => { + surfacedErrors.push(message) + } + } + }) + await settle('client never sent a subscribe frame', () => subscribePayloads().length >= 1) + const first = subscribePayloads().at(-1) + emitSnapshot( + codec, + (bytes) => streamCallbacks?.onBinary?.(bytes), + first?.streamId ?? 0, + 'live before the fault' + ) + const connectedBeforeFault = transport.isConnected() + + // Only now does the pane become skew-relevant: the stream drops, and the + // host answers the resubscribe with the token its build publishes. + const methodsBeforeFault = methodLog.length + resolvePaneFailure = new Error(publishedFailure) + streamCallbacks?.onClose?.() + await settle( + 'client never reacted to the failed resubscribe', + () => + methodLog.length > methodsBeforeFault && + (paneReplacementRequests.length > 0 || + surfacedErrors.length > 0 || + subscribePayloads().length > 1) + ) + + return { + clientLabel: clientBuild.label, + methodsAfterFailure: methodLog.slice(methodsBeforeFault), + paneReplacementRequests, + surfacedErrors, + subscribedHandles: subscribePayloads().map((payload) => payload.terminal), + connectedBeforeFault + } + } finally { + transport.destroy?.() + vi.unstubAllGlobals() + } +} + +export const SKEW_PANE = { + handle: PANE_HANDLE, + replacementHandle: REPLACEMENT_HANDLE, + ptyId: PANE_PTY_ID, + paneKey: `${PANE_TAB_ID}:${PANE_LEAF_ID}`, + worktreeId: PANE_WORKTREE_ID, + sessionId: SESSION_ID, + connectionId: CONNECTION_ID +} diff --git a/tests/e2e/cross-version-wire/reattach-recovery-authorization-skew.ts b/tests/e2e/cross-version-wire/reattach-recovery-authorization-skew.ts new file mode 100644 index 00000000000..65807ca1fd7 --- /dev/null +++ b/tests/e2e/cross-version-wire/reattach-recovery-authorization-skew.ts @@ -0,0 +1,333 @@ +import { vi } from 'vitest' +import { importBuildModule, type TerminalWireBuild } from './versioned-terminal-wire' + +/** + * The half of the reattach-failure contract the publication skew harness cannot see. + * + * `reattach-failure-publication-skew.ts` proves what each CLIENT build DOES with a + * published token, but it answers `terminal.recoverPane` from a mock that always + * grants a replacement handle. The client's request is not the mutation — the + * HOST's grant is. And the host decides that from durable state it wrote itself, + * long before any client version is in the picture: + * + * relay: sourceRecovery=restoreRequired (the shell is still running) + * -> SshPtyProvider publishes a failure token + * -> ipc/pty.ts marks the SSH lease `expired` iff that token reads as expiry + * -> OrcaRuntimeService.recoverTerminalPane creates a replacement shell iff a + * recent expired lease exists for the pane. + * + * So the duplicate-agent bug is host-authorized, not client-authorized, and it is + * reachable from ANY client version. This harness runs all three of those + * production decisions for one build and reports what the host actually did. + */ + +const CONNECTION_ID = 'ssh-1' +const RELAY_SESSION_ID = 'pty-live-shell' +const REPO_ID = 'repo-1' +const WORKTREE_PATH = '/tmp/orca-skew-worktree' +const WORKTREE_ID = `${REPO_ID}::${WORKTREE_PATH}` +const TAB_ID = 'tab-skew' +const LEAF_ID = '11111111-1111-4111-8111-111111111111' +const PANE_KEY = `${TAB_ID}:${LEAF_ID}` +const REPLACEMENT_HANDLE = 'term-replacement' +const APP_PTY_ID = `ssh:${CONNECTION_ID}@@${RELAY_SESSION_ID}` + +type SshLease = { + targetId: string + ptyId: string + worktreeId: string + tabId: string + leafId: string + state: string + createdAt: number + updatedAt: number +} + +type LeaseLedger = { + leases: SshLease[] + writes: { ptyId: string; state: string }[] + markSshRemotePtyLease: (targetId: string, ptyId: string, state: string) => void + upsertSshRemotePtyLease: (lease: Record) => void + removeSshRemotePtyLease: (targetId: string, ptyId: string) => void + getSshRemotePtyLeases: () => SshLease[] + persistPtyBinding: (binding: Record) => void + removePtyBinding: (ptyId: string) => void + getPtyBindings: () => Record[] +} + +/** + * Stands in for the sqlite lease table only. Every decision about WHAT to write + * and HOW to read it stays in production code on both ends. + */ +function createLeaseLedger(): LeaseLedger { + const now = Date.now() + const leases: SshLease[] = [ + { + targetId: CONNECTION_ID, + ptyId: RELAY_SESSION_ID, + worktreeId: WORKTREE_ID, + tabId: TAB_ID, + leafId: LEAF_ID, + state: 'attached', + createdAt: now, + updatedAt: now + } + ] + const writes: { ptyId: string; state: string }[] = [] + return { + leases, + writes, + markSshRemotePtyLease: (targetId, ptyId, state) => { + writes.push({ ptyId, state }) + const lease = leases.find((entry) => entry.targetId === targetId && entry.ptyId === ptyId) + if (lease) { + lease.state = state + lease.updatedAt = Date.now() + } + }, + upsertSshRemotePtyLease: () => {}, + removeSshRemotePtyLease: () => {}, + getSshRemotePtyLeases: () => leases, + persistPtyBinding: () => {}, + removePtyBinding: () => {}, + getPtyBindings: () => [] + } +} + +// The repo/settings surface OrcaRuntimeService reads while resolving a pane. +const RUNTIME_STORE_BASE = { + getRepo: (id: string) => RUNTIME_STORE_BASE.getRepos().find((repo) => repo.id === id), + getRepos: () => [ + { id: REPO_ID, path: WORKTREE_PATH, displayName: 'repo', badgeColor: 'blue', addedAt: 1 } + ], + getAllWorktreeMeta: () => ({ + [WORKTREE_ID]: { + displayName: 'skew', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0 + } + }), + getWorktreeMeta: (worktreeId: string) => RUNTIME_STORE_BASE.getAllWorktreeMeta()[worktreeId], + getSettings: () => ({ + workspaceDir: '/tmp/workspaces', + nestWorkspaces: false, + refreshLocalBaseRefOnWorktreeCreate: false, + branchPrefix: 'none', + branchPrefixCustom: '' + }), + getProjects: () => [], + getSparsePresets: () => [] +} + +type PtyIpcModule = { + registerPtyHandlers: (...args: unknown[]) => void + registerSshPtyProvider: (connectionId: string, provider: unknown) => void + unregisterSshPtyProvider: (connectionId: string) => void +} + +type SshProviderModule = { + SshPtyProvider: new (connectionId: string, mux: unknown) => unknown +} + +type RuntimeModule = { + OrcaRuntimeService: new (store: unknown) => { + registerPty: ( + ptyId: string, + worktreeId: string, + connectionId: string | null, + identity: { tabId: string; leafId: string } + ) => void + resolveTerminalPane: (paneKey: string, worktreeId: string) => { handle: string } + onPtyExit: (ptyId: string, code: number) => void + createTerminal: (...args: unknown[]) => Promise + } +} + +export type HostRecoveryAuthorizationOutcome = { + hostLabel: string + /** Which id space the pane's PTY was registered under for this drive. */ + runtimePtyIdSpace: 'relay' | 'app' + /** The token this build's real SshPtyProvider threw for a live-shell source loss. */ + publishedFailure: string + /** Lease-state writes this build's real ipc/pty.ts made while failing the reattach. */ + leaseWrites: { ptyId: string; state: string }[] + /** The pane's lease state after the failed reattach, as the host would persist it. */ + leaseStateAfterFailure: string + /** How the host's real `terminal.recoverPane` answered the client's request. */ + recoverPaneOutcome: 'granted' | 'refused' + recoverPaneError: string | null + /** Replacement shells the host actually created. The mutation, counted. */ + replacementShellsCreated: number + /** The pane was genuinely attached before the fault, so the drive is not vacuous. */ + attachedBeforeFault: boolean +} + +/** + * Run one host build end to end: real SSH provider, real `pty:spawn` handler, real + * runtime recovery gate, real RPC dispatcher. Nothing here names a token, so the + * oracle tracks production rather than restating it. + */ +export async function driveHostRecoveryAuthorization(args: { + hostBuild: TerminalWireBuild + /** + * Which id the pane's PTY is registered under in the runtime graph. + * + * `ipc/pty.ts` writes the lease with the RELAY id but calls `runtime.registerPty` + * with the APP id (`ssh:@@`), and the recovery gate compares the two + * directly. `relay` is the space where a legacy grant is reachable at all; `app` + * is the shape production registers. Both are driven so a refusal cannot be + * mistaken for an id that simply never matched. + */ + runtimePtyIdSpace: 'relay' | 'app' +}): Promise { + const { hostBuild } = args + const runtimePtyId = args.runtimePtyIdSpace === 'app' ? APP_PTY_ID : RELAY_SESSION_ID + const [ptyIpc, providerModule, runtimeModule] = (await Promise.all([ + importBuildModule(hostBuild.label, 'main/ipc/pty.ts'), + importBuildModule(hostBuild.label, 'main/providers/ssh-pty-provider.ts'), + importBuildModule(hostBuild.label, 'main/runtime/orca-runtime.ts') + ])) as unknown as [PtyIpcModule, SshProviderModule, RuntimeModule] + + const ledger = createLeaseLedger() + let attachAnswer: Record = { incarnationId: 'incarnation-attached' } + const mux = { + request: vi.fn(async (method: string) => (method === 'pty.attach' ? attachAnswer : {})), + notify: vi.fn(), + onNotification: vi.fn().mockReturnValue(vi.fn()) + } + const provider = new providerModule.SshPtyProvider(CONNECTION_ID, mux) + + const handlers = new Map Promise>() + const { ipcMain } = (await import('electron')) as unknown as { + ipcMain: { handle: { mockImplementation: (fn: unknown) => void } } + } + ipcMain.handle.mockImplementation( + (channel: string, handler: (event: unknown, payload: unknown) => Promise) => { + handlers.set(channel, handler) + } + ) + + const mainWindow = { + isDestroyed: () => false, + webContents: { + id: 1, + send: vi.fn(), + on: vi.fn(), + once: vi.fn(), + removeListener: vi.fn(), + removeAllListeners: vi.fn(), + setBackgroundThrottling: vi.fn(), + isDestroyed: () => false + } + } + + ptyIpc.registerSshPtyProvider(CONNECTION_ID, provider) + try { + ptyIpc.registerPtyHandlers(mainWindow, undefined, undefined, undefined, undefined, ledger) + const spawn = handlers.get('pty:spawn') + if (!spawn) { + throw new Error(`${hostBuild.label}: pty:spawn handler was never registered`) + } + const spawnArgs = { + cols: 80, + rows: 24, + env: {}, + connectionId: CONNECTION_ID, + sessionId: RELAY_SESSION_ID, + worktreeId: WORKTREE_ID, + tabId: TAB_ID, + leafId: LEAF_ID + } + + // The pane is genuinely attached first: a refusal below must mean the host + // withheld a replacement, not that nothing ever connected. + const attached = await spawn(null, spawnArgs) + const attachedBeforeFault = + typeof (attached as { id?: unknown })?.id === 'string' && + ledger.leases[0]?.state === 'attached' + + // The relay now answers the reattach the way it does for a live shell whose + // output source must be re-established. + attachAnswer = { + incarnationId: 'incarnation-reattached', + sourceRecovery: { status: 'restoreRequired', reason: 'checkpointUnavailable' } + } + let publishedFailure = '' + try { + await spawn(null, spawnArgs) + } catch (error) { + publishedFailure = error instanceof Error ? error.message : String(error) + } + if (!publishedFailure) { + throw new Error( + `${hostBuild.label}: reattach with sourceRecovery=restoreRequired resolved instead of failing closed` + ) + } + + // The client asks the host to replace the pane's shell. Whether that request + // is granted is the host's decision, and it reads the lease written above. + const runtime = new runtimeModule.OrcaRuntimeService({ + ...RUNTIME_STORE_BASE, + getSshRemotePtyLeases: ledger.getSshRemotePtyLeases + }) + runtime.registerPty(runtimePtyId, WORKTREE_ID, null, { tabId: TAB_ID, leafId: LEAF_ID }) + const paneHandle = runtime.resolveTerminalPane(PANE_KEY, WORKTREE_ID).handle + runtime.onPtyExit(runtimePtyId, -1) + const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ + handle: REPLACEMENT_HANDLE, + tabId: TAB_ID, + paneKey: PANE_KEY, + ptyId: 'pty-replacement', + worktreeId: WORKTREE_ID, + title: null, + surface: 'background' + }) + + const dispatcher = new hostBuild.host.RpcDispatcher({ + runtime, + methods: hostBuild.host.TERMINAL_METHODS + }) as unknown as { + dispatch: (request: Record) => Promise> + } + const response = await dispatcher.dispatch({ + id: 'recover-1', + authToken: 'cross-version-token', + method: 'terminal.recoverPane', + params: { paneKey: PANE_KEY, worktreeId: WORKTREE_ID, expectedTerminal: paneHandle } + }) + const granted = response.ok === true + const error = response.error as { message?: string } | undefined + + return { + hostLabel: hostBuild.label, + runtimePtyIdSpace: args.runtimePtyIdSpace, + publishedFailure, + leaseWrites: ledger.writes, + leaseStateAfterFailure: ledger.leases[0]?.state ?? 'missing', + recoverPaneOutcome: granted ? 'granted' : 'refused', + recoverPaneError: granted ? null : (error?.message ?? String(response.error ?? 'unknown')), + replacementShellsCreated: createTerminal.mock.calls.length, + attachedBeforeFault + } + } finally { + ptyIpc.unregisterSshPtyProvider(CONNECTION_ID) + vi.restoreAllMocks() + } +} + +export const SKEW_HOST_PANE = { + paneKey: PANE_KEY, + worktreeId: WORKTREE_ID, + relaySessionId: RELAY_SESSION_ID, + connectionId: CONNECTION_ID, + replacementHandle: REPLACEMENT_HANDLE +} diff --git a/tests/e2e/cross-version-wire/release-checkout.ts b/tests/e2e/cross-version-wire/release-checkout.ts index 205885a5e87..069375f4c18 100644 --- a/tests/e2e/cross-version-wire/release-checkout.ts +++ b/tests/e2e/cross-version-wire/release-checkout.ts @@ -21,6 +21,7 @@ const CHECKOUT_FORMAT = 1 const ARCHIVE_PATHS = ['src/main', 'src/shared', 'src/preload', 'src/renderer', 'src/types'] const BASELINE_REF_ENV = 'ORCA_CROSS_VERSION_BASELINE_REF' +const STABLE_DESKTOP_RELEASE_TAG = /^v\d+\.\d+\.\d+$/ export type ReleaseCheckout = { /** The ref as requested, e.g. `v1.4.169`. */ @@ -61,7 +62,7 @@ function compareReleaseTags(a: string, b: string): number { /** * The version point the harness pairs current code against. An explicit - * {@link BASELINE_REF_ENV} wins; otherwise the newest non-prerelease `v*` tag. + * {@link BASELINE_REF_ENV} wins; otherwise the newest stable desktop release tag. * * Throws rather than skipping: a cross-version lane that quietly runs nothing is * the exact failure this harness exists to prevent. @@ -80,11 +81,10 @@ export function resolveBaselineReleaseRef(): string { `Run it inside a git checkout, or pin a ref with ${BASELINE_REF_ENV}.` ) } - const releases = tags.filter((tag) => !tag.includes('-')).sort(compareReleaseTags) - const latest = releases.at(-1) + const latest = selectLatestStableReleaseTag(tags) if (!latest) { throw new Error( - `Cross-version harness found no release tags matching v[0-9]* (saw ${tags.length} tag(s) total). ` + + `Cross-version harness found no stable desktop release tags matching vX.Y.Z (saw ${tags.length} tag(s) total). ` + 'CI checkouts default to a shallow clone with no tags: use `actions/checkout` with `fetch-depth: 0`, ' + `or pin a ref with ${BASELINE_REF_ENV}.` ) @@ -92,6 +92,15 @@ export function resolveBaselineReleaseRef(): string { return latest } +export function selectLatestStableReleaseTag(tags: string[]): string | null { + return ( + tags + .filter((tag) => STABLE_DESKTOP_RELEASE_TAG.test(tag)) + .sort(compareReleaseTags) + .at(-1) ?? null + ) +} + function resolveCommit(ref: string): string { try { return git(['rev-parse', `${ref}^{commit}`]) diff --git a/tests/e2e/cross-version-wire/versioned-terminal-wire.ts b/tests/e2e/cross-version-wire/versioned-terminal-wire.ts index 6a0fd0f467b..812dc18d83a 100644 --- a/tests/e2e/cross-version-wire/versioned-terminal-wire.ts +++ b/tests/e2e/cross-version-wire/versioned-terminal-wire.ts @@ -1,4 +1,4 @@ -import { materializeReleaseCheckout, type ReleaseCheckout } from './release-checkout' +import { materializeReleaseCheckout, REPO_ROOT, type ReleaseCheckout } from './release-checkout' /** * Structural views of the three modules that make up the remote terminal wire. @@ -138,6 +138,22 @@ async function loadReleaseBuild(checkout: ReleaseCheckout): Promise> { + if (ref === WORKING_TREE) { + return await importFromCheckout(`${REPO_ROOT}/src/${pathUnderSrc}`) + } + const checkout = materializeReleaseCheckout(ref) + return await importFromCheckout(`${checkout.root}/src/${pathUnderSrc}`) +} + /** * Load the wire modules for one build. `WORKING_TREE` imports current source (so a * locally injected violation is exercised); any other value is a git ref extracted diff --git a/tests/e2e/daemon-restart-session-liveness.spec.ts b/tests/e2e/daemon-restart-session-liveness.spec.ts new file mode 100644 index 00000000000..fc0eeb87788 --- /dev/null +++ b/tests/e2e/daemon-restart-session-liveness.spec.ts @@ -0,0 +1,424 @@ +/** + * Journey 2 (daemon half): the same PTY — the same *OS shell process* — must + * survive both a client restart and a daemon restart, and an operation carrying + * a stale daemon generation must be refused without killing or replacing the + * live successor. + * + * What "daemon restart" means here, precisely: the PTY leader is a child of the + * daemon that spawned it, so a same-generation daemon exit takes its shells with + * it. The only PTY-preserving daemon restart Orca has is generation succession — + * a new protocol generation becomes `current` while the generation holding live + * sessions is preserved and stays reachable through a legacy adapter. That is + * the boundary these tests cross. + * + * Oracle notes: + * - Identity is the OS process: the shell reports its own PID through the + * production write path (`DaemonPtyRouter.write` -> daemon -> PTY) and the + * PID is then resolved to a kernel start time. A same-id/new-process respawn + * passes a session-id check, a `hasPty` check, and an `isReattach` check, and + * fails only this one. + * - Each phase uses a fresh nonce, because reattach replays scrollback and an + * earlier phase's answer is still in the stream. + * + * Clause separation is deliberate — one clause per test, so a mutation that + * reddens one leaves the others green: + * 1. off-socket inventory reads `unknown`, never `dead`; + * 2. the same OS shell survives client quit + daemon generation restart; + * 3. a stale-incarnation operation is refused and the live successor is intact. + * + * Discrimination protocol (each guard removal must turn the named test red): + * 1. `daemon-pty-adapter.ts` `hasPty` -> `return this.activeSessionIds.has(id)` + * → test 1 fails (a disconnected daemon makes a live session read dead); + * tests 2 and 3 stay green. + * 2. `daemon-session-owner-resolution.ts` `resolveInventory` — drop + * `!expectedIncarnationIsAuthoritative &&` from the sole-provider fallback + * → test 3 fails (the stale-generation operation is applied); tests 1 and 2 + * stay green. + */ + +import { randomUUID } from 'node:crypto' +import { expect, test, type TestInfo } from '@playwright/test' +import { DaemonPtyAdapter } from '../../src/main/daemon/daemon-pty-adapter' +import { DaemonPtyRouter } from '../../src/main/daemon/daemon-pty-router' +import { PROTOCOL_VERSION } from '../../src/main/daemon/types' +import { + cleanupDaemonGenerationFixtures, + createDaemonGenerationRuntime, + launchDaemonGeneration, + type DaemonGeneration, + type DaemonGenerationRuntime +} from './helpers/daemon-generation-safety-fixtures' +import { + processIdentityLiveness, + type RecordedProcessIdentity +} from './helpers/daemon-generation-processes' +import { + disposeDaemonShellSessions, + readShellProcessIdentity, + recordSessionOutput, + spawnDaemonShellSession, + type DaemonShellSession +} from './helpers/daemon-shell-process-identity' + +/** The generation that already holds live shells when the newer one starts. */ +const PRESERVED_PROTOCOL_VERSION = 23 + +type ReattachOptions = { cwd: string; expectedIncarnationId?: string } + +/** Rebuilds exactly what a restarted app constructs: cold adapters, no route, no inventory. */ +function restartedAppRouter(generations: readonly DaemonGeneration[]): { + router: DaemonPtyRouter + adapters: DaemonPtyAdapter[] +} { + const adapters = generations.map( + (generation) => + new DaemonPtyAdapter({ + socketPath: generation.socketPath, + tokenPath: generation.tokenPath, + protocolVersion: generation.protocolVersion + }) + ) + const current = adapters[0]! + return { + router: new DaemonPtyRouter({ current, legacy: adapters.slice(1) }), + adapters + } +} + +/** Models the app process going away while the daemon keeps the PTY. */ +async function quitAppSideOf(shell: DaemonShellSession): Promise { + await shell.adapter.disconnectOnly() + shell.adapter.dispose() +} + +/** The production reattach: attach-only, never a create. */ +async function reattach( + router: DaemonPtyRouter, + sessionId: string, + options: ReattachOptions +): Promise<{ id: string; isReattach?: boolean }> { + return await router.spawn({ + sessionId, + isNewSession: false, + attachOnly: true, + cols: 200, + rows: 30, + cwd: options.cwd, + ...(options.expectedIncarnationId === undefined + ? {} + : { + expectedIncarnationId: options.expectedIncarnationId, + expectedIncarnationIsAuthoritative: true + }) + }) +} + +/** Every session this daemon generation actually created or attached. */ +function sessionOwnershipEvents(generation: DaemonGeneration, sessionId: string): string[] { + return generation + .logEvents() + .filter( + (event) => + event.sessionId === sessionId && + (event.event === 'session-created' || event.event === 'session-attached') + ) + .map((event) => String(event.event)) +} + +async function inspectionVerdict(router: DaemonPtyRouter, sessionId: string): Promise { + try { + await router.inspectProcess(sessionId) + return 'resolved' + } catch (error) { + return error instanceof Error ? error.message : String(error) + } +} + +/** Exact incarnation, not just the PID: a recycled PID must not read as alive. */ +async function shellLeaderIsAlive(shell: DaemonShellSession): Promise { + const liveness = await processIdentityLiveness([shell.rootIdentity]) + return liveness.get(shell.rootIdentity.pid) === true +} + +/** Reads the shell's own PID through the router — the production write path. */ +async function shellIdentityThroughRouter( + router: DaemonPtyRouter, + shell: DaemonShellSession, + phase: string +): Promise { + const recorder = recordSessionOutput(router, shell.sessionId) + try { + return await readShellProcessIdentity({ + phase, + write: (data) => router.write(shell.sessionId, data), + readOutput: recorder.text + }) + } finally { + recorder.stop() + } +} + +async function cleanup(options: { + runtime: DaemonGenerationRuntime + generations: readonly DaemonGeneration[] + shells: readonly DaemonShellSession[] + adapters: readonly DaemonPtyAdapter[] + retainDiagnostics: boolean +}): Promise { + for (const adapter of options.adapters) { + adapter.dispose() + } + if (options.retainDiagnostics) { + options.runtime.retainDiagnostics(options.generations) + } + try { + await disposeDaemonShellSessions(options.shells) + await cleanupDaemonGenerationFixtures({ + generations: options.generations, + canaries: [] + }) + } catch (error) { + options.runtime.retainDiagnostics(options.generations) + throw error + } + options.runtime.remove() +} + +test.describe.configure({ mode: 'serial' }) + +test('a restarted client reads a daemon-held PTY as unknown, never dead', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires the fixture argument before testInfo. +{}, testInfo: TestInfo) => { + test.setTimeout(180_000) + const runtime = await createDaemonGenerationRuntime(testInfo) + const generations: DaemonGeneration[] = [] + const shells: DaemonShellSession[] = [] + let adapters: DaemonPtyAdapter[] = [] + let assertionsComplete = false + + try { + const daemon = await launchDaemonGeneration({ + runtime, + label: `generation-v${PROTOCOL_VERSION}`, + protocolVersion: PROTOCOL_VERSION + }) + generations.push(daemon) + const shell = await spawnDaemonShellSession({ + runtime, + generation: daemon, + role: 'live' + }) + shells.push(shell) + + await quitAppSideOf(shell) + // Ground truth for every assertion below: the shell is still running. + expect(await shellLeaderIsAlive(shell)).toBe(true) + + const restarted = restartedAppRouter(generations) + adapters = restarted.adapters + const { router } = restarted + + // A restarted client has an empty session cache and a socket it has not + // dialled yet. Absence of evidence is not evidence of absence — the only + // honest answer is "unknown". Answering false hands the renderer's + // dead-session reconcile a licence to exit a pane whose shell is running. + expect(router.hasPty(shell.sessionId)).toBeNull() + expect(await inspectionVerdict(router, shell.sessionId)).not.toBe('terminal_gone') + expect(await shellLeaderIsAlive(shell)).toBe(true) + assertionsComplete = true + } finally { + await cleanup({ + runtime, + generations, + shells, + adapters, + retainDiagnostics: !assertionsComplete + }) + } +}) + +test('the same OS shell process survives a client quit and a daemon generation restart', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires the fixture argument before testInfo. +{}, testInfo: TestInfo) => { + test.setTimeout(180_000) + const runtime = await createDaemonGenerationRuntime(testInfo) + const generations: DaemonGeneration[] = [] + const shells: DaemonShellSession[] = [] + let adapters: DaemonPtyAdapter[] = [] + let assertionsComplete = false + + try { + // The daemon the app is talking to when the shell is created. + const preserved = await launchDaemonGeneration({ + runtime, + label: `generation-v${PRESERVED_PROTOCOL_VERSION}`, + protocolVersion: PRESERVED_PROTOCOL_VERSION + }) + generations.push(preserved) + const shell = await spawnDaemonShellSession({ + runtime, + generation: preserved, + role: 'live' + }) + shells.push(shell) + + const bootRecorder = recordSessionOutput(shell.adapter, shell.sessionId) + const bootIdentity = await readShellProcessIdentity({ + phase: 'BOOT', + write: (data) => shell.adapter.write(shell.sessionId, data), + readOutput: bootRecorder.text + }) + bootRecorder.stop() + // The PTY leader the daemon reported is the shell that just answered. + expect(bootIdentity.pid).toBe(shell.spawnPid) + + // --- client restart boundary --- + await quitAppSideOf(shell) + + // --- daemon restart boundary: a newer generation takes over as `current` --- + const successor = await launchDaemonGeneration({ + runtime, + label: `generation-v${PROTOCOL_VERSION}`, + protocolVersion: PROTOCOL_VERSION + }) + generations.unshift(successor) + + const restarted = restartedAppRouter(generations) + adapters = restarted.adapters + const { router } = restarted + + await router.discoverLegacySessions() + const reattached = await reattach(router, shell.sessionId, { + cwd: runtime.rootDir + }) + expect(reattached).toMatchObject({ id: shell.sessionId, isReattach: true }) + + // The whole journey: not the same id, the same *process*. PID plus kernel + // start time, answered over the new connection by the shell itself. + expect(await shellIdentityThroughRouter(router, shell, 'AFTER_DAEMON_RESTART')).toEqual( + bootIdentity + ) + + // Nothing was created or adopted on the new generation. + expect(sessionOwnershipEvents(successor, shell.sessionId)).toEqual([]) + expect(sessionOwnershipEvents(preserved, shell.sessionId)).toContain('session-attached') + assertionsComplete = true + } finally { + await cleanup({ + runtime, + generations, + shells, + adapters, + retainDiagnostics: !assertionsComplete + }) + } +}) + +test('a stale daemon generation operation is refused and the live successor is neither killed nor replaced', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires the fixture argument before testInfo. +{}, testInfo: TestInfo) => { + test.setTimeout(180_000) + const runtime = await createDaemonGenerationRuntime(testInfo) + const generations: DaemonGeneration[] = [] + const shells: DaemonShellSession[] = [] + let adapters: DaemonPtyAdapter[] = [] + let assertionsComplete = false + + try { + const successor = await launchDaemonGeneration({ + runtime, + label: `generation-v${PROTOCOL_VERSION}`, + protocolVersion: PROTOCOL_VERSION + }) + const preserved = await launchDaemonGeneration({ + runtime, + label: `generation-v${PRESERVED_PROTOCOL_VERSION}`, + protocolVersion: PRESERVED_PROTOCOL_VERSION + }) + generations.push(successor, preserved) + + // Two live shells: one held by the preserved generation, one by the + // successor. Skew has to leave *both* alone. + const preservedShell = await spawnDaemonShellSession({ + runtime, + generation: preserved, + role: 'preserved-live' + }) + const successorShell = await spawnDaemonShellSession({ + runtime, + generation: successor, + role: 'successor-live' + }) + shells.push(preservedShell, successorShell) + + const bootIdentities = new Map() + for (const shell of shells) { + const recorder = recordSessionOutput(shell.adapter, shell.sessionId) + bootIdentities.set( + shell.sessionId, + await readShellProcessIdentity({ + phase: 'BOOT', + write: (data) => shell.adapter.write(shell.sessionId, data), + readOutput: recorder.text + }) + ) + recorder.stop() + await quitAppSideOf(shell) + } + + const restarted = restartedAppRouter(generations) + adapters = restarted.adapters + const { router } = restarted + const successorAdapter = adapters[0]! + await router.discoverLegacySessions() + + // Skew A — an operation aimed at the wrong generation. The successor has + // never seen this session; it must refuse rather than create a lookalike. + await expect(successorAdapter.attach(preservedShell.sessionId)).rejects.toThrow() + expect(sessionOwnershipEvents(successor, preservedShell.sessionId)).toEqual([]) + + // Skew B — an attach that carries an authoritative incarnation the owning + // generation cannot match. Production sends exactly this shape from + // `src/main/ipc/pty.ts` when runtime state pins the expected incarnation. + // It must fail closed, not fall back to "the only candidate I can see". + await expect( + reattach(router, preservedShell.sessionId, { + cwd: runtime.rootDir, + expectedIncarnationId: randomUUID() + }) + ).rejects.toThrow() + await expect( + reattach(router, successorShell.sessionId, { + cwd: runtime.rootDir, + expectedIncarnationId: randomUUID() + }) + ).rejects.toThrow() + + // Refused means refused: neither live shell was killed or replaced. The + // exact incarnation still reattaches and the original process answers. + for (const shell of shells) { + const reattached = await reattach(router, shell.sessionId, { + cwd: runtime.rootDir, + expectedIncarnationId: shell.incarnationId + }) + expect(reattached).toMatchObject({ + id: shell.sessionId, + isReattach: true + }) + expect(await shellIdentityThroughRouter(router, shell, 'AFTER_SKEW')).toEqual( + bootIdentities.get(shell.sessionId) + ) + } + + // The preserved generation's session never touched the successor, and the + // successor's own session never migrated to the preserved generation. + expect(sessionOwnershipEvents(successor, preservedShell.sessionId)).toEqual([]) + expect(sessionOwnershipEvents(preserved, successorShell.sessionId)).toEqual([]) + assertionsComplete = true + } finally { + await cleanup({ + runtime, + generations, + shells, + adapters, + retainDiagnostics: !assertionsComplete + }) + } +}) diff --git a/tests/e2e/fixtures/daemon-generation-legacy-close-client.ts b/tests/e2e/fixtures/daemon-generation-legacy-close-client.ts index b9bbb621597..730ebbeffc9 100644 --- a/tests/e2e/fixtures/daemon-generation-legacy-close-client.ts +++ b/tests/e2e/fixtures/daemon-generation-legacy-close-client.ts @@ -62,7 +62,7 @@ const OBSERVER = { function readConfig(): FixtureConfig { const configIndex = process.argv.indexOf('--config') - const configPath = configIndex >= 0 ? process.argv[configIndex + 1] : undefined + const configPath = configIndex !== -1 ? process.argv[configIndex + 1] : undefined if (!configPath) { throw new Error('Legacy close client requires --config ') } diff --git a/tests/e2e/fixtures/daemon-generation-reconnect-client.ts b/tests/e2e/fixtures/daemon-generation-reconnect-client.ts index 28c0a6686a7..6bd163cc474 100644 --- a/tests/e2e/fixtures/daemon-generation-reconnect-client.ts +++ b/tests/e2e/fixtures/daemon-generation-reconnect-client.ts @@ -41,7 +41,7 @@ const MAX_OUTPUT_CHARS = 32_768 function readConfig(): ClientConfig { const configIndex = process.argv.indexOf('--config') - const configPath = configIndex >= 0 ? process.argv[configIndex + 1] : undefined + const configPath = configIndex !== -1 ? process.argv[configIndex + 1] : undefined if (!configPath) { throw new Error('Reconnect client requires --config ') } diff --git a/tests/e2e/fixtures/visible-tui-scroll-fixture.cjs b/tests/e2e/fixtures/visible-tui-scroll-fixture.cjs index 3702ad21a9f..63b7683916a 100644 --- a/tests/e2e/fixtures/visible-tui-scroll-fixture.cjs +++ b/tests/e2e/fixtures/visible-tui-scroll-fixture.cjs @@ -12,7 +12,7 @@ const MOUSE_REPORT_PATTERN = new RegExp(`${ESC}\\[<(64|65);\\d+;\\d+M`, 'g') // at 120 reports/s) instead of minimal rows. const args = process.argv.slice(2) const logIndex = args.indexOf('--log') -const LOG_PATH = logIndex >= 0 ? args[logIndex + 1] : null +const LOG_PATH = logIndex !== -1 ? args[logIndex + 1] : null const HEAVY_FRAMES = args.includes('--heavy') let offset = 0 diff --git a/tests/e2e/git-history-tooltip-wrap.spec.ts b/tests/e2e/git-history-tooltip-wrap.spec.ts new file mode 100644 index 00000000000..6a8c4f5895b --- /dev/null +++ b/tests/e2e/git-history-tooltip-wrap.spec.ts @@ -0,0 +1,144 @@ +import { execFileSync } from 'node:child_process' +import { rmSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { expect, test } from './helpers/orca-app' +import { waitForSessionReady } from './helpers/store' +import { openSourceControlForWorktree } from './helpers/worktree-registration' + +const subject = 'brew-install: source shared brew context before resolving prefixes' +const reportedLine = 'Sources bin/lib/brew-context.sh, mirroring the brew-install update:' +const conventionalLine = 'Keep this conventional commit-message body line intact through column 72' +const unbrokenLine = `https://example.com/${'commit-message-segment-'.repeat(8)}` +const commitMessage = `${subject} + +${reportedLine} +${conventionalLine} +${unbrokenLine} +the resolved prefix list now feeds both the cask audit and the formula +path checks, so a missing context aborts before any network call runs. + +Verified by running the full tap audit locally with both prefixes set.` + +function createCommitWorktree(repoPath: string): { branchName: string; worktreePath: string } { + const suffix = `${Date.now()}-${Math.random().toString(16).slice(2)}` + const branchName = `e2e-tooltip-wrap-${suffix}` + const worktreePath = path.join(os.tmpdir(), branchName) + execFileSync('git', ['worktree', 'add', worktreePath, '-b', branchName], { + cwd: repoPath, + stdio: 'pipe' + }) + return { branchName, worktreePath } +} + +async function cleanupCommitWorktree( + repoPath: string, + worktreePath: string, + branchName: string +): Promise { + try { + execFileSync('git', ['worktree', 'remove', '--force', worktreePath], { + cwd: repoPath, + stdio: 'pipe' + }) + } catch { + rmSync(worktreePath, { recursive: true, force: true }) + execFileSync('git', ['worktree', 'prune'], { cwd: repoPath, stdio: 'pipe' }) + } + execFileSync('git', ['branch', '-D', branchName], { cwd: repoPath, stdio: 'pipe' }) +} + +test('keeps conventional commit-message lines intact in the history tooltip', async ({ + orcaPage, + testRepoPath, + registerPostElectronShutdownCleanup +}) => { + const fixture = createCommitWorktree(testRepoPath) + registerPostElectronShutdownCleanup(() => + cleanupCommitWorktree(testRepoPath, fixture.worktreePath, fixture.branchName) + ) + execFileSync('git', ['commit', '--allow-empty', '--file', '-'], { + cwd: fixture.worktreePath, + input: commitMessage, + stdio: ['pipe', 'pipe', 'pipe'] + }) + + await orcaPage.setViewportSize({ width: 1440, height: 900 }) + await waitForSessionReady(orcaPage) + await openSourceControlForWorktree(orcaPage, testRepoPath, fixture.worktreePath) + + const commitsToggle = orcaPage.getByRole('button', { name: /Commits/ }) + await expect(commitsToggle).toBeVisible() + await commitsToggle.click() + + const row = orcaPage.getByTestId('git-history-row').filter({ hasText: subject }) + await expect(row).toBeVisible({ timeout: 10_000 }) + const trigger = row.locator('[data-slot="tooltip-trigger"]').filter({ hasText: subject }) + await trigger.hover({ position: { x: 20, y: 10 } }) + await trigger.hover({ position: { x: 40, y: 10 } }) + + const tooltip = orcaPage + .locator('[data-slot="tooltip-content"]') + .filter({ hasText: reportedLine }) + await expect(tooltip).toBeVisible() + await expect(tooltip).toContainText(commitMessage) + await orcaPage.evaluate(async () => { + await document.fonts.ready + }) + + const layout = await tooltip.evaluate( + (element, targetLines) => { + const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT) + let textNode: Text | null = null + while (walker.nextNode()) { + const candidate = walker.currentNode as Text + if (targetLines.every((line) => candidate.data.includes(line))) { + textNode = candidate + break + } + } + if (!textNode) { + throw new Error('Commit message text node was not found in the tooltip') + } + + const visualLineCounts = targetLines.map((targetLine) => { + const start = textNode.data.indexOf(targetLine) + const range = document.createRange() + range.setStart(textNode, start) + range.setEnd(textNode, start + targetLine.length) + const rectTops = Array.from(range.getClientRects()) + .filter((rect) => rect.width > 0.5) + .map((rect) => rect.top) + const visualLineTops = rectTops.reduce((tops, top) => { + if (!tops.some((existing) => Math.abs(existing - top) < 2)) { + tops.push(top) + } + return tops + }, []) + return visualLineTops.length + }) + + const style = getComputedStyle(element) + const tooltipRect = element.getBoundingClientRect() + return { + visualLineCounts, + tooltipLeft: tooltipRect.left, + tooltipRight: tooltipRect.right, + tooltipWidth: tooltipRect.width, + viewportWidth: window.innerWidth, + overflowContained: element.scrollWidth <= element.clientWidth, + textWrap: style.textWrap, + whiteSpace: style.whiteSpace + } + }, + [reportedLine, conventionalLine] + ) + + expect(layout.whiteSpace).toBe('pre-wrap') + expect(layout.tooltipWidth).toBeGreaterThan(0) + expect(layout.tooltipLeft).toBeGreaterThanOrEqual(0) + expect(layout.tooltipRight).toBeLessThanOrEqual(layout.viewportWidth) + expect(layout.visualLineCounts).toEqual([1, 1]) + expect(layout.overflowContained).toBe(true) + expect(layout.textWrap).toBe('wrap') +}) diff --git a/tests/e2e/golden-posix-fresh-startup.spec.ts b/tests/e2e/golden-posix-fresh-startup.spec.ts new file mode 100644 index 00000000000..ba30f550498 --- /dev/null +++ b/tests/e2e/golden-posix-fresh-startup.spec.ts @@ -0,0 +1,15 @@ +import { expect, test } from './helpers/orca-app' + +test.skip(process.platform === 'win32', 'POSIX fresh-startup golden; Windows has its own suite') + +test.describe('POSIX fresh startup golden', () => { + test.use({ dismissOnboarding: false, seedTestRepo: false }) + + test('fresh profile reaches onboarding normally @posix-profile-index-golden', async ({ + orcaPage + }) => { + await expect(orcaPage.getByRole('heading', { name: /Pick your default agent/i })).toBeVisible({ + timeout: 30_000 + }) + }) +}) diff --git a/tests/e2e/golden-posix-profile-index-fsync.spec.ts b/tests/e2e/golden-posix-profile-index-fsync.spec.ts new file mode 100644 index 00000000000..d3d34d6743d --- /dev/null +++ b/tests/e2e/golden-posix-profile-index-fsync.spec.ts @@ -0,0 +1,45 @@ +import { readFileSync, rmSync, statSync } from 'node:fs' +import path from 'node:path' +import { expect, test } from './helpers/orca-app' + +test.use({ seedTestRepo: false }) +test.skip(process.platform === 'win32', 'Restrictive-umask fsync regression is POSIX-only') + +test('recreates a fresh profile index on disk with a restrictive umask @posix-profile-index-golden', async ({ + electronApp, + orcaPage +}) => { + const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) + const indexPath = path.join(userDataDir, 'orca-profile-index.json') + // Why: the index tmp file is written with 0o666 & ~umask, so a umask that clears + // owner-write is what made the pre-fix fsync open(path, 'r+') fail with EACCES. + const originalUmask = await electronApp.evaluate(() => process.umask(0o200)) + + try { + rmSync(indexPath, { force: true }) + rmSync(`${indexPath}.bak`, { force: true }) + // Why: orcaProfiles:list reads the index from disk on every call and rebuilds + // it when missing, so this drives the real create + fsync + rename path. + const listed = await orcaPage.evaluate(async () => { + const result = await window.api.orcaProfiles.list() + window.__store!.getState().openSettingsPage() + return result + }) + expect(listed.profiles.length).toBeGreaterThan(0) + + // The rebuilt index must be on disk and complete — a cached in-memory list is + // not proof that the restrictive-umask write survived fsync. + const persisted = JSON.parse(readFileSync(indexPath, 'utf-8')) + expect(persisted.activeProfileId).toBe(listed.activeProfileId) + expect(persisted.profiles.map((profile: { id: string }) => profile.id)).toEqual( + listed.profiles.map((profile) => profile.id) + ) + // Owner-write cleared proves the file was created under the restrictive umask + // rather than left over from startup's normal-umask write. + expect(statSync(indexPath).mode & 0o200).toBe(0) + } finally { + await electronApp.evaluate((_electron, umask) => process.umask(umask), originalUmask) + } + + await expect(orcaPage.getByPlaceholder('Search settings')).toBeVisible() +}) diff --git a/tests/e2e/golden-windows-fresh-startup.spec.ts b/tests/e2e/golden-windows-fresh-startup.spec.ts new file mode 100644 index 00000000000..f153f765dcd --- /dev/null +++ b/tests/e2e/golden-windows-fresh-startup.spec.ts @@ -0,0 +1,12 @@ +import { expect, test } from './helpers/orca-app' + +test.use({ dismissOnboarding: false, seedTestRepo: false }) +test.skip(process.platform !== 'win32', 'Fresh-profile fsync regression is Windows-only') + +test('fresh Windows profile reaches onboarding @windows-fresh-startup-golden', async ({ + orcaPage +}) => { + await expect(orcaPage.getByRole('heading', { name: /Pick your default agent/i })).toBeVisible({ + timeout: 30_000 + }) +}) diff --git a/tests/e2e/helpers/completed-worker-retirement-fixture.ts b/tests/e2e/helpers/completed-worker-retirement-fixture.ts index d1211234258..564f52e2f5f 100644 --- a/tests/e2e/helpers/completed-worker-retirement-fixture.ts +++ b/tests/e2e/helpers/completed-worker-retirement-fixture.ts @@ -86,7 +86,7 @@ export function readCompletedWorkerLedger(): LifecycleEvent[] { } const contents = readFileSync(lifecycleLedgerPath, 'utf8') const lastCompleteLine = contents.lastIndexOf('\n') - if (lastCompleteLine < 0) { + if (lastCompleteLine === -1) { return [] } return contents diff --git a/tests/e2e/helpers/daemon-shell-process-identity.ts b/tests/e2e/helpers/daemon-shell-process-identity.ts new file mode 100644 index 00000000000..c0177508c1d --- /dev/null +++ b/tests/e2e/helpers/daemon-shell-process-identity.ts @@ -0,0 +1,151 @@ +import { randomUUID } from 'node:crypto' +import { DaemonPtyAdapter } from '../../../src/main/daemon/daemon-pty-adapter' +import type { IPtyProvider } from '../../../src/main/providers/pty-provider-contract' +import { DAEMON_GENERATION_WORKTREE_ID } from '../fixtures/daemon-generation-fixture-contract' +import { + recordProcessIdentity, + recordProcessTree, + terminateRecordedTree, + waitForCondition, + type RecordedProcessIdentity +} from './daemon-generation-processes' +import type { DaemonGeneration, DaemonGenerationRuntime } from './daemon-generation-safety-fixtures' + +const MAX_CAPTURED_CHARS = 65_536 +const PROBE_WIDTH_COLS = 200 +const PROBE_HEIGHT_ROWS = 30 + +export type DaemonShellSession = { + generation: DaemonGeneration + sessionId: string + adapter: DaemonPtyAdapter + /** The PID the daemon reported for the PTY leader at spawn time. */ + spawnPid: number + rootIdentity: RecordedProcessIdentity + treeIdentities: RecordedProcessIdentity[] + incarnationId: string | undefined + output(): string +} + +/** Buffers one session's stream off any provider that fans out `onData`. */ +export function recordSessionOutput( + provider: Pick, + sessionId: string +): { text(): string; stop(): void } { + let text = '' + const unsubscribe = provider.onData((event) => { + if (event.id === sessionId) { + text = `${text}${event.data}`.slice(-MAX_CAPTURED_CHARS) + } + }) + return { text: () => text, stop: unsubscribe } +} + +/** + * A real login shell under the daemon — not a fixture script. Journey 2 has to + * compare the *shell* the user is typing into across the restart boundary, so + * the PTY leader must be the shell itself. + */ +export async function spawnDaemonShellSession(options: { + runtime: DaemonGenerationRuntime + generation: DaemonGeneration + role: string + worktreeId?: string +}): Promise { + const { runtime, generation, role, worktreeId = DAEMON_GENERATION_WORKTREE_ID } = options + // Why the durable prefix: daemon inventory infers ownership from it, so a bare + // id would resolve to unknown for reasons unrelated to what is under test. + const sessionId = `${worktreeId}@@orca-j2-${generation.label}-${role}-${randomUUID().slice(0, 8)}` + const adapter = new DaemonPtyAdapter({ + socketPath: generation.socketPath, + tokenPath: generation.tokenPath, + protocolVersion: generation.protocolVersion + }) + const recorder = recordSessionOutput(adapter, sessionId) + const result = await adapter.spawn({ + sessionId, + isNewSession: true, + cols: PROBE_WIDTH_COLS, + rows: PROBE_HEIGHT_ROWS, + cwd: runtime.rootDir, + ...(process.platform === 'win32' ? { shellOverride: 'powershell.exe' } : {}) + }) + if (!result.pid) { + throw new Error(`${generation.label}-${role} shell did not expose its PTY leader PID`) + } + const rootIdentity = await recordProcessIdentity(result.pid) + return { + generation, + sessionId, + adapter, + spawnPid: result.pid, + rootIdentity, + treeIdentities: await recordProcessTree(rootIdentity), + incarnationId: result.incarnationId, + output: recorder.text + } +} + +/** Disposable fixture teardown: exact-identity kills only, never a bare PID. */ +export async function disposeDaemonShellSessions( + shells: readonly DaemonShellSession[] +): Promise { + for (const shell of shells) { + shell.adapter.dispose() + } + if (shells.length > 0) { + await terminateRecordedTree(shells.flatMap((shell) => shell.treeIdentities)) + } +} + +/** + * Ask the live shell for its own PID over the production write path, then read + * the kernel's start time for that PID. + * + * Both halves are load-bearing. The write path proves *this* connection reaches + * a shell that is still executing; the kernel start time proves the PID was not + * recycled by a replacement shell. A same-id/new-process respawn passes every + * weaker check and fails this one. + */ +export async function readShellProcessIdentity(options: { + phase: string + write: (data: string) => void + readOutput: () => string + timeoutMs?: number +}): Promise { + const { phase, write, readOutput, timeoutMs = 30_000 } = options + // Why a per-phase nonce: reattach replays scrollback, so an earlier phase's + // answer is sitting in the stream and would otherwise satisfy this probe. + const marker = `ORCA_J2_SHELL_PID_${phase}_${randomUUID().replaceAll('-', '')}` + // Why match the *expanded* value: the echoed command line carries the literal + // `$$`/`$PID`, so only the shell's own reply contains digits. + const reported = new RegExp(`${marker}=(\\d+)`) + const command = process.platform === 'win32' ? `echo ${marker}=$PID\r` : `echo ${marker}=$$\r` + + let pid: number | null = null + const deadline = Date.now() + timeoutMs + // Why re-issue: a freshly spawned shell may still be sourcing its rc files and + // will discard the first line. Repeats are idempotent for `echo`. + while (Date.now() <= deadline && pid === null) { + write(command) + try { + await waitForCondition( + `${phase} shell PID reply`, + () => { + const match = reported.exec(readOutput()) + pid = match ? Number(match[1]) : null + return pid !== null + }, + 3_000 + ) + } catch { + // Fall through and re-issue until the outer deadline. + } + } + if (pid === null) { + throw new Error( + `Shell never reported its PID for phase ${phase}. Tail: ${readOutput().slice(-500)}` + ) + } + return await recordProcessIdentity(pid) +} diff --git a/tests/e2e/helpers/docker-ssh-host-probe-observations.ts b/tests/e2e/helpers/docker-ssh-host-probe-observations.ts new file mode 100644 index 00000000000..e972b082e01 --- /dev/null +++ b/tests/e2e/helpers/docker-ssh-host-probe-observations.ts @@ -0,0 +1,102 @@ +/** + * "Did anything dial this host?" — measured on the host, not in a log line the + * app controls. + * + * Three independent signals, because each one alone can miss a probe: + * - `acceptedAuths` is cumulative (sshd's own auth log), so a connection that + * opens and closes between two samples still shows up; + * - `sshdSessions` catches a connection that is still open; + * - `connectBridges` catches Orca's `relay.js --connect` transport even if the + * sshd session were somehow invisible. + * + * `docker exec` does not go through sshd, so this helper's own probes never + * contaminate the counters they read. + */ +import { spawnSync } from 'node:child_process' +import { + execDockerSshRelayTargetCommand, + type DockerSshRelayTarget +} from './docker-ssh-relay-target' + +export type DockerSshHostProbeObservation = { + /** Cumulative count of completed public-key authentications since boot. */ + acceptedAuths: number + /** Live `sshd: root@...` sessions right now. */ + sshdSessions: number + /** Live `relay.js --connect` transport bridges right now. */ + connectBridges: number + /** `kind pid cmdline` for each of the above, so a failure names the process. */ + transportProcesses: string[] +} + +// Why argv[0] and not the joined cmdline: this probe runs as `bash -lc