diff --git a/.github/workflows/daemon-relocation-spike.yml b/.github/workflows/daemon-relocation-spike.yml new file mode 100644 index 000000000..319580dc2 --- /dev/null +++ b/.github/workflows/daemon-relocation-spike.yml @@ -0,0 +1,97 @@ +name: Daemon Relocation Spike + +# Why: Phase 1 of the Windows update-survival work relocates the terminal +# daemon's file closure out of the install dir so it survives an update. Before +# implementing it in the app, this spike finds the MINIMAL set of packaged files +# that a copied Orca.exe (run as node) needs to start the daemon and drive a +# ConPTY session from a relocated directory, holding no install-dir file locks. +# Runs from the feature branch via push (workflow_dispatch only works on the +# default branch); main is never touched. + +on: + push: + branches: + - Jinwoo-H/windows-update-survival + paths: + - 'tools/daemon-relocation-spike/**' + - '.github/workflows/daemon-relocation-spike.yml' + workflow_dispatch: {} + +permissions: + contents: read + +concurrency: + group: daemon-relocation-spike-${{ github.ref }} + cancel-in-progress: true + +jobs: + spike: + name: relocation file-set spike + runs-on: windows-2022 + timeout-minutes: 40 + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # This job only reads the repo to build/run the spike; it never pushes. + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Why: cache the unpacked build keyed on the inputs that affect it, so + # spike-script-only edits skip the ~15 min electron-builder build. + - name: Cache unpacked build + id: cache-unpacked + uses: actions/cache@v4 + with: + path: dist/win-unpacked + key: win-unpacked-${{ hashFiles('src/**', 'config/**', 'package.json', 'pnpm-lock.yaml') }} + + - name: Build unpacked app + if: steps.cache-unpacked.outputs.cache-hit != 'true' + run: pnpm run build:unpack + + - name: Run relocation spike (all tiers) + shell: pwsh + run: | + New-Item -ItemType Directory -Force artifacts | Out-Null + $log = "artifacts/spike-output.log" + $tiers = @('full', 'no-gpu', 'minimal') + $any = $false + foreach ($tier in $tiers) { + "===== TIER: $tier =====" | Tee-Object -FilePath $log -Append + $work = Join-Path $env:RUNNER_TEMP "spike-$tier" + # --keep-work-dir so the per-tier daemon stdout/stderr logs survive + # for the artifact upload (the spike otherwise removes work-dir), + # which is what diagnoses a tier that fails to reach ready. + node tools/daemon-relocation-spike/spike.mjs ` + --app-dir dist/win-unpacked ` + --work-dir "$work" ` + --tier $tier ` + --keep-work-dir 2>&1 | Tee-Object -FilePath $log -Append + if ($LASTEXITCODE -eq 0) { $any = $true } + } + if (-not $any) { throw "No tier passed the relocation spike" } + + - name: Upload spike output + if: always() + uses: actions/upload-artifact@v7 + with: + name: daemon-relocation-spike-output + path: | + artifacts/spike-output.log + ${{ runner.temp }}/spike-*/**/*.log + retention-days: 7 + if-no-files-found: warn diff --git a/.github/workflows/win-update-e2e.yml b/.github/workflows/win-update-e2e.yml new file mode 100644 index 000000000..21c788256 --- /dev/null +++ b/.github/workflows/win-update-e2e.yml @@ -0,0 +1,145 @@ +name: Windows Update-Survival E2E + +# Why: proves what happens to terminal sessions across a real Windows app update +# by installing one released version, updating to another, and asserting on the +# packaged artifacts (daemon survival, terminal interactivity, zero console +# flashes). This MUST run on a disposable CI Windows: electron-builder's oneClick +# installer uninstalls the registry-registered copy of the app before every +# install, so running the harness on a machine with a real Orca install would +# delete it. A fresh runner has no Orca registered, so it is the only safe home +# for install-based testing. Manual dispatch only. + +# Why: workflow_dispatch only works once a workflow is on the default branch. +# To exercise this from the unmerged feature branch WITHOUT touching main, a +# push trigger scoped to that exact branch runs the workflow from the branch's +# own tree. The paths filter keeps it to harness/workflow edits so ordinary +# commits don't spend 30 min of Windows runner time. Push runs have no inputs, +# so every parameter falls back to a default below. +on: + push: + branches: + - Jinwoo-H/windows-update-survival + paths: + - 'tools/win-update-e2e/**' + - '.github/workflows/win-update-e2e.yml' + workflow_dispatch: + inputs: + from_tag: + description: Release tag to install first (e.g. v1.4.124-rc.8) + required: true + type: string + to_tag: + description: Release tag to update to (e.g. v1.4.124-rc.9) + required: true + type: string + expect: + description: Expected outcome profile + required: true + type: choice + default: cold-restore + options: + - cold-restore + - survival + asset_pattern: + description: Installer asset glob + required: false + type: string + default: '*windows-setup.exe' + soak_seconds: + description: Post-relaunch console-window watch duration + required: false + type: string + default: '60' + +permissions: + contents: read + +# Why: cancel a superseded run when iterating — a new push to the branch makes +# the in-flight Windows job obsolete, so free the runner immediately. +concurrency: + group: win-update-e2e-${{ github.ref }} + cancel-in-progress: true + +jobs: + update-e2e: + name: update ${{ inputs.from_tag || 'v1.4.124-rc.8' }} -> ${{ inputs.to_tag || 'v1.4.124-rc.9' }} (${{ inputs.expect || 'cold-restore' }}) + runs-on: windows-2022 + timeout-minutes: 30 + env: + FROM_TAG: ${{ inputs.from_tag || 'v1.4.124-rc.8' }} + TO_TAG: ${{ inputs.to_tag || 'v1.4.124-rc.9' }} + EXPECT: ${{ inputs.expect || 'cold-restore' }} + ASSET_PATTERN: ${{ inputs.asset_pattern || '*windows-setup.exe' }} + SOAK_SECONDS: ${{ inputs.soak_seconds || '60' }} + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # This job only reads the repo and downloads a release; it never pushes. + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + # Why: the harness only needs its runtime deps (the Playwright Electron + # driver); it drives already-built installer artifacts, so no app build. + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Why: fail fast with a readable message if a tag has no matching Windows + # installer, rather than deep inside the harness. + - name: Download installers + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: pwsh + run: | + New-Item -ItemType Directory -Force artifacts/from | Out-Null + New-Item -ItemType Directory -Force artifacts/to | Out-Null + gh release download "$env:FROM_TAG" --repo "${{ github.repository }}" --pattern "$env:ASSET_PATTERN" --dir artifacts/from + gh release download "$env:TO_TAG" --repo "${{ github.repository }}" --pattern "$env:ASSET_PATTERN" --dir artifacts/to + $from = Get-ChildItem artifacts/from -Filter *.exe | Select-Object -First 1 + $to = Get-ChildItem artifacts/to -Filter *.exe | Select-Object -First 1 + if (-not $from) { throw "No installer matching '$env:ASSET_PATTERN' in $env:FROM_TAG" } + if (-not $to) { throw "No installer matching '$env:ASSET_PATTERN' in $env:TO_TAG" } + "FROM_EXE=$($from.FullName)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + "TO_EXE=$($to.FullName)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + + # Why: no --install-dir here. A CI runner has no real Orca registered, so + # the harness installs to the default per-user location and owns it — the + # isolated-install machinery exists only to (imperfectly) protect a real + # developer install, which does not apply on a throwaway runner. + - name: Run update-survival harness + id: harness + shell: pwsh + env: + # Why: on a driving failure the harness dumps a screenshot + DOM state + # here so the actual post-onboarding UI is visible in the artifacts. + ORCA_E2E_DIAG_DIR: artifacts/diag + run: | + $log = "artifacts/harness-output.log" + node tools/win-update-e2e/run.mjs ` + --from "$env:FROM_EXE" ` + --to "$env:TO_EXE" ` + --expect "$env:EXPECT" ` + --soak-seconds "$env:SOAK_SECONDS" 2>&1 | Tee-Object -FilePath $log + exit $LASTEXITCODE + + - name: Upload harness output + if: always() + uses: actions/upload-artifact@v7 + with: + name: win-update-e2e-output + # Why: log + diagnostics only, never the multi-hundred-MB installers. + path: | + artifacts/harness-output.log + artifacts/diag/** + retention-days: 7 + if-no-files-found: warn diff --git a/.github/workflows/win-update-survival-e2e.yml b/.github/workflows/win-update-survival-e2e.yml new file mode 100644 index 000000000..f5e7cb093 --- /dev/null +++ b/.github/workflows/win-update-survival-e2e.yml @@ -0,0 +1,116 @@ +name: Windows Update-Survival E2E (branch build) + +# Why: proves the Phase 1 daemon-host relocation actually makes terminal +# sessions SURVIVE a Windows update. Builds an (unsigned) installer FROM THIS +# BRANCH, then runs the win-update-e2e harness with --expect survival: install, +# open a terminal, silently update over it, relaunch, and assert the daemon PID +# is unchanged and the pre-update terminal is still interactive with no console +# flashing. Runs from the feature branch via push (workflow_dispatch only works +# on the default branch); main is never touched. A CI runner is the only safe +# place to install/update — see the relocation post-mortem. + +on: + push: + branches: + - Jinwoo-H/windows-update-survival + paths: + - 'src/main/daemon/**' + - 'src/main/pty/**' + - 'tools/win-update-e2e/**' + - 'config/electron-builder.config.cjs' + - '.github/workflows/win-update-survival-e2e.yml' + workflow_dispatch: + inputs: + expect: + description: Expected outcome profile + required: true + type: choice + default: survival + options: + - survival + - cold-restore + +permissions: + contents: read + +concurrency: + group: win-update-survival-e2e-${{ github.ref }} + cancel-in-progress: true + +jobs: + survival: + name: survival (branch build over itself) + runs-on: windows-2022 + timeout-minutes: 50 + env: + EXPECT: ${{ inputs.expect || 'survival' }} + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # This job only builds and runs the harness locally; it never pushes. + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Why: cache the built installer keyed on the inputs that affect it, so a + # harness-only edit skips the ~20 min electron-builder build. The daemon + # relocation code lives under src/, so changing it correctly rebuilds. + - name: Cache branch installer + id: cache-installer + uses: actions/cache@v4 + with: + path: dist/orca-windows-setup.exe + key: branch-installer-${{ hashFiles('src/**', 'config/**', 'package.json', 'pnpm-lock.yaml') }} + + - name: Build Windows installer (unsigned) + if: steps.cache-installer.outputs.cache-hit != 'true' + run: | + node config/scripts/ensure-native-runtime.mjs --runtime=electron + pnpm run build:desktop + pnpm exec electron-builder --config config/electron-builder.config.cjs --win --publish never + + # Why: install the branch build, open a terminal, update the SAME build + # over it, and assert the relocated daemon survives. Same build on both + # sides isolates the survival mechanism (NSIS kill sweep + userData daemon + # + adoption) from cross-version staleness policy. No --install-dir: a CI + # runner has no real Orca to protect. + - name: Run survival harness + id: harness + shell: pwsh + env: + ORCA_E2E_DIAG_DIR: artifacts/diag + run: | + New-Item -ItemType Directory -Force artifacts | Out-Null + $exe = "dist/orca-windows-setup.exe" + if (-not (Test-Path $exe)) { throw "Installer not found at $exe" } + $log = "artifacts/survival-output.log" + node tools/win-update-e2e/run.mjs ` + --from "$exe" ` + --to "$exe" ` + --expect "$env:EXPECT" ` + --soak-seconds 60 2>&1 | Tee-Object -FilePath $log + exit $LASTEXITCODE + + - name: Upload survival output + if: always() + uses: actions/upload-artifact@v7 + with: + name: win-update-survival-output + path: | + artifacts/survival-output.log + artifacts/diag/** + retention-days: 7 + if-no-files-found: warn diff --git a/README.md b/README.md index 8e9bc05d3..9d712389d 100644 --- a/README.md +++ b/README.md @@ -238,9 +238,10 @@ Pair with your desktop app to monitor and steer your agents from your phone. - **Discord:** Join the community on **[Discord](https://discord.gg/fzjDKHxv8Q)**. - **Twitter / X:** Follow **[@orca_build](https://x.com/orca_build)** for updates and announcements. -- **WeChat:** Scan the QR code to join the community. +- **WeChat:** Scan the QR code to join the community. If the first group is full, use the backup group. WeChat QR code for the Orca community + Backup WeChat QR code for the Orca community - **Feedback & Ideas:** We ship fast. Missing something? [Request a new feature](https://github.com/stablyai/orca/issues). - **Privacy:** See the [privacy & telemetry docs](https://www.onorca.dev/docs/telemetry) for what anonymous usage data Orca collects and how to opt out. diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index 9e482825a..a5a8042de 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -106,6 +106,7 @@ module.exports = { 'out/main/win32-utils.js', 'out/main/daemon-entry.js', 'out/main/computer-sidecar.js', + 'out/main/parcel-watcher-process-entry.js', 'out/main/chunks/**', 'resources/**', 'node_modules/ws/**', @@ -173,7 +174,11 @@ module.exports = { artifactName: 'orca-windows-setup.${ext}', shortcutName: '${productName}', uninstallDisplayName: '${productName}', - createDesktopShortcut: 'always' + createDesktopShortcut: 'always', + // Why: on a real uninstall, stop and remove the relocated terminal daemon + // (which lives outside the install dir under LOCALAPPDATA by design). Guarded + // by ${isUpdated} inside so it never runs during an update's uninstallOldVersion. + include: resolve(__dirname, 'nsis', 'daemon-host-uninstall.nsh') }, mac: { icon: 'resources/build/icon.icns', diff --git a/config/nsis/daemon-host-uninstall.nsh b/config/nsis/daemon-host-uninstall.nsh new file mode 100644 index 000000000..dc3a497ce --- /dev/null +++ b/config/nsis/daemon-host-uninstall.nsh @@ -0,0 +1,23 @@ +; Clean up the relocated terminal daemon on a REAL uninstall. +; +; Why: the daemon host is deliberately copied to a distinct image name +; (orca-terminal-daemon.exe) under %LOCALAPPDATA%\Orca\daemon-host so that app +; UPDATES cannot kill it — that relocation is what keeps terminals alive across +; updates. The same design means a normal uninstall's process sweep and file +; removal both miss it, leaving an orphaned daemon plus its runtime copy behind. +; +; The ${isUpdated} guard is essential: electron-builder runs this uninstaller as +; part of uninstallOldVersion on EVERY update, and killing the daemon there would +; defeat the whole feature. Only clean up on a genuine uninstall. +; +; The image name and the LOCALAPPDATA folder name must stay in sync with +; DAEMON_HOST_EXE_NAME and LOCAL_HOST_ROOT_NAME in +; src/main/daemon/daemon-host-relocation.ts. +!macro customUnInstall + ${ifNot} ${isUpdated} + nsExec::Exec 'taskkill /F /IM orca-terminal-daemon.exe' + ; Give the OS a moment to release the image lock before removing the tree. + Sleep 500 + RMDir /r "$LOCALAPPDATA\Orca\daemon-host" + ${endIf} +!macroend diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 1975f41c7..73162aee6 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1463,6 +1463,144 @@ ], "demotionRule": "Cannot promote if standard-key behavior is inferred without PTY byte evidence." }, + { + "id": "terminal-input.agent-prompt-injection", + "title": "Orchestration agent prompts arrive as bracketed paste before submit", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-input", + "layer": "runtime-contract-and-cli-repro", + "surfaces": [ + "terminal input", + "agent prompt injection", + "orchestration dispatch", + "PTY writes", + "bracketed paste" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon", + "ssh", + "remote-runtime" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [ + "local" + ], + "coverageNotes": "Local macOS evidence covers the runtime PTY write contract and a live dev-runtime CLI repro. SSH, daemon, remote-runtime, Linux, and Windows remain provider/platform gaps; the product path stays provider-owned and does not add local filesystem or process assumptions.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/7226" + ], + "invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and send Enter only after the paste frame completes.", + "oracle": "Runtime tests assert the exact PTY write sequence and failure cleanup; orchestration tests assert dispatch/coordinator use the agent prompt path; the live CLI harness dispatches a 32KB task to a fake Codex-like TUI and requires marker present, bracketed paste present, zero unframed line breaks, and submit observed.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-prompt-injection.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/runtime/orchestration/coordinator.test.ts", + "node tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000" + ], + "testFiles": [ + "src/shared/agent-prompt-injection.test.ts", + "src/main/runtime/orca-runtime.test.ts", + "src/main/runtime/rpc/methods/orchestration.test.ts", + "src/main/runtime/orchestration/coordinator.test.ts", + "tools/repro-orchestration-long-prompt.mjs" + ], + "assertionRefs": [ + { + "file": "src/shared/agent-prompt-injection.test.ts", + "assertions": [ + "agent prompts are always framed as bracketed paste", + "submit stays separate from the paste frame", + "embedded ESC bytes are made inert before framing", + "chunk reconstruction preserves the paste frame" + ] + }, + { + "file": "src/main/runtime/orca-runtime.test.ts", + "assertions": [ + "runtime writes bracketed paste before a delayed submit", + "large prompt frames are chunked and reconstructed before submit", + "partial prompt write failure closes the paste frame and does not submit" + ] + }, + { + "file": "src/main/runtime/rpc/methods/orchestration.test.ts", + "assertions": [ + "orchestration.dispatch uses the agent prompt path for injected preambles", + "raw terminal.send is not called for injected task prompts", + "failed prompt injection rolls back the active dispatch" + ] + }, + { + "file": "src/main/runtime/orchestration/coordinator.test.ts", + "assertions": [ + "coordinator dispatch failures from prompt injection circuit-break through the DB", + "silent-skip paths do not attempt prompt injection" + ] + }, + { + "file": "tools/repro-orchestration-long-prompt.mjs", + "assertions": [ + "fake Codex-like worker observes submit after long orchestration dispatch", + "32KB task marker survives before submit", + "prompt bytes include a bracketed-paste frame with zero unframed line breaks" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-07", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-prompt-injection.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/runtime/orchestration/coordinator.test.ts", + "result": "passed", + "durationSeconds": 7.4, + "summary": "4 test files passed, 697 tests passed; covers framing, runtime PTY writes, orchestration RPC dispatch, and coordinator dispatch behavior." + }, + { + "date": "2026-07-07", + "runner": "local", + "platform": "macos", + "command": "node tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000", + "result": "passed", + "durationSeconds": 2.2, + "summary": "Live dev-runtime repro passed: expectedSpecBytes=32830, hasSubmit=true, rawContainsMarker=true, hasBracketedPasteFrame=true, unframedLineBreaks=0, contractOk=true." + } + ], + "runtimeBudget": { + "p95Seconds": 30, + "scope": "runtime contract tests plus optional local dev-runtime CLI repro" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "First local macOS evidence only; needs repeated dev-runtime harness runs and provider matrix evidence before promotion." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "The live harness reproduced the unsafe raw multiline contract before the fix and passes after the fix; intentional-break evidence is local only and not yet in CI." + }, + "performanceBudget": { + "required": true, + "evidence": "Agent prompt dispatch remains O(prompt bytes), uses the existing 16KB terminal input chunking and one existing 500ms submit delay, and adds no polling, provider listing, subprocess churn, hidden-pane wakeups, or renderer work." + }, + "promotionCriteria": [ + "Run the live harness in soak with a self-starting dev runtime or provider-contract fixture.", + "Add daemon, SSH, remote-runtime, Linux, and Windows evidence or mark narrower provider scope.", + "Capture stable red/green intentional-break evidence in CI before blocking promotion." + ], + "knownGaps": [ + "Live harness command currently expects an already-running dev runtime and generated out/bin/orca-dev wrapper.", + "No Windows ConPTY, Linux PTY, SSH, daemon, or remote-runtime live evidence yet.", + "Push-on-idle orchestration message banners remain outside this dispatch-prompt gate." + ], + "demotionRule": "Demote or quarantine if the live harness flakes without a product bug or harness bug filed to the terminal-input owner." + }, { "id": "terminal-render.windows-cjk-repaint", "title": "Windows ConPTY wide glyphs and cursor rewrites repaint without stale cells", diff --git a/config/scripts/electron-builder-config.test.mjs b/config/scripts/electron-builder-config.test.mjs index 3f318219e..46298b376 100644 --- a/config/scripts/electron-builder-config.test.mjs +++ b/config/scripts/electron-builder-config.test.mjs @@ -69,6 +69,14 @@ describe('electron-builder config', () => { ) }) + // Why: without the unpacked entry the watcher client silently falls back to + // in-process @parcel/watcher, reintroducing the #7547 main-process crash. + it('unpacks the forked parcel-watcher process entry', () => { + expect(electronBuilderConfig.asarUnpack).toEqual( + expect.arrayContaining(['out/main/parcel-watcher-process-entry.js']) + ) + }) + it('uses the multi-size icon source for Linux packages', () => { expect(electronBuilderConfig.linux.icon).toBe('resources/build/icon.icns') }) diff --git a/config/scripts/serve-headless-fresh-profile-pairing.mjs b/config/scripts/serve-headless-fresh-profile-pairing.mjs new file mode 100755 index 000000000..6d4f7ac86 --- /dev/null +++ b/config/scripts/serve-headless-fresh-profile-pairing.mjs @@ -0,0 +1,326 @@ +#!/usr/bin/env node + +import { spawn, spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { hostname, tmpdir } from 'node:os' +import path from 'node:path' +import { createInterface } from 'node:readline' + +const scriptDir = import.meta.dirname +const repoRoot = path.resolve(scriptDir, '..', '..') +const orcaDevScript = path.join(scriptDir, 'orca-dev.mjs') +const ensureNativeRuntimeScript = path.join(scriptDir, 'ensure-native-runtime.mjs') +const fixedProfileDir = process.env.ORCA_HEADLESS_PAIRING_PROFILE_DIR +const parsed = parseArgs(process.argv.slice(2)) + +if (parsed.help) { + printHelp() + process.exit(0) +} + +if (hasForwardedServeFlag(parsed.serveArgs, 'no-pairing')) { + console.error('serve-headless-fresh-profile-pairing: --no-pairing cannot print a pairing code.') + process.exit(2) +} +if (hasForwardedServeFlag(parsed.serveArgs, 'recipe-json')) { + console.error( + 'serve-headless-fresh-profile-pairing: --recipe-json detaches the server and cannot use an ephemeral profile safely.' + ) + process.exit(2) +} + +const serveArgs = withDefaultPairingAddress(parsed.serveArgs) + +ensureElectronRuntime() + +const profileDir = + fixedProfileDir ?? mkdtempSync(path.join(tmpdir(), 'orca-headless-pairing-profile-')) +const ownsProfileDir = !fixedProfileDir +mkdirSync(profileDir, { recursive: true }) + +let cleanedUp = false +let child = null +let sawPairingUrl = false +let stopAttempts = 0 +// Why: temp dev worktrees do not have a root-owned chrome-sandbox; this script +// is only for local headless testing, not packaged production. +const childEnv = { + ...process.env, + ORCA_DEV_USER_DATA_PATH: profileDir, + ...(process.platform === 'linux' + ? { ELECTRON_DISABLE_SANDBOX: process.env.ELECTRON_DISABLE_SANDBOX ?? '1' } + : {}) +} + +console.error(`[headless-pairing] userData=${profileDir}`) +console.error(`[headless-pairing] starting: orca-dev serve --json${formatForwardedArgs(serveArgs)}`) + +child = spawn(process.execPath, [orcaDevScript, 'serve', '--json', ...serveArgs], { + cwd: repoRoot, + detached: process.platform !== 'win32', + env: childEnv, + stdio: ['inherit', 'pipe', 'inherit'] +}) + +const stdoutLines = createInterface({ input: child.stdout }) +stdoutLines.on('line', (line) => { + if (!printReadyLine(line)) { + console.log(line) + } +}) + +child.once('error', (error) => { + console.error(`[headless-pairing] failed to start server: ${error.message}`) + cleanupProfile() + process.exitCode = 1 +}) + +child.once('exit', (code, signal) => { + stdoutLines.close() + if (!sawPairingUrl && code !== 0) { + console.error('[headless-pairing] server exited before printing a pairing URL.') + } + cleanupProfile() + if (typeof code === 'number') { + process.exitCode = code + return + } + process.exitCode = signal ? 1 : 0 +}) + +process.on('SIGINT', () => stopChild('SIGINT')) +process.on('SIGTERM', () => stopChild('SIGTERM')) + +/** + * Parses wrapper flags and forwards everything else to `orca serve`. + */ +function parseArgs(args) { + const serveArgs = [] + let keepProfile = false + let help = false + for (const arg of args) { + if (arg === '--keep') { + keepProfile = true + continue + } + if (arg === '-h' || arg === '--help') { + help = true + continue + } + serveArgs.push(arg) + } + return { help, keepProfile, serveArgs } +} + +/** + * Prints script usage without touching the dev profile or starting the server. + */ +function printHelp() { + console.log(`Usage: node config/scripts/serve-headless-fresh-profile-pairing.mjs [--keep] [orca serve flags] + +Starts orca-dev serve --json with a fresh isolated userData profile, ensures Electron's dev runtime is usable, and prints the pairing URL. + +Wrapper flags: + --keep Keep the fresh profile after the server exits. + -h, --help Show this help. + +Forwarded examples: + node config/scripts/serve-headless-fresh-profile-pairing.mjs --port 6768 + node config/scripts/serve-headless-fresh-profile-pairing.mjs --pairing-address 100.64.1.20 + node config/scripts/serve-headless-fresh-profile-pairing.mjs --mobile-pairing + +Environment: + ORCA_HEADLESS_PAIRING_ADDRESS= Override the auto pairing address. + ORCA_HEADLESS_PAIRING_PROFILE_DIR=/path/to/profile Use a fixed profile directory. +`) +} + +/** + * Adds a reachable pairing address unless the caller provided one explicitly. + */ +function withDefaultPairingAddress(args) { + if (hasPairingAddress(args)) { + return args + } + const address = resolveDefaultPairingAddress() + if (!address) { + return args + } + console.error(`[headless-pairing] pairingAddress=${address} (auto)`) + return [...args, '--pairing-address', address] +} + +/** + * Checks both supported CLI forms for an explicit pairing address. + */ +function hasPairingAddress(args) { + return hasForwardedServeFlag(args, 'pairing-address') +} + +/** + * Checks both exact and `--flag=value` forms for a forwarded serve flag. + */ +function hasForwardedServeFlag(args, name) { + const flag = `--${name}` + return args.some((arg) => arg === flag || arg.startsWith(`${flag}=`)) +} + +/** + * Prefers an override, then Tailscale, then the OS hostname over loopback. + */ +function resolveDefaultPairingAddress() { + const configured = process.env.ORCA_HEADLESS_PAIRING_ADDRESS?.trim() + if (configured) { + return configured + } + const tailscaleAddress = readTailscaleAddress() + if (tailscaleAddress) { + return tailscaleAddress + } + const host = hostname().trim() + return host && host !== 'localhost' ? host : null +} + +/** + * Reads the first Tailscale IPv4 address when Tailscale is installed. + */ +function readTailscaleAddress() { + const result = spawnSync('tailscale', ['ip', '-4'], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'] + }) + if (result.error || result.status !== 0) { + return null + } + return ( + result.stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .find(Boolean) ?? null + ) +} + +/** + * Formats forwarded arguments for the startup log. + */ +function formatForwardedArgs(args) { + if (args.length === 0) { + return '' + } + return ` ${args.map(formatShellArg).join(' ')}` +} + +/** + * Quotes a shell-ish argument for display only. + */ +function formatShellArg(value) { + if (/^[\w./:=@+-]+$/.test(value)) { + return value + } + return JSON.stringify(value) +} + +/** + * Runs the same Electron runtime preflight used by dev/start package scripts. + */ +function ensureElectronRuntime() { + console.error('[headless-pairing] ensuring Electron runtime...') + const result = spawnSync(process.execPath, [ensureNativeRuntimeScript, '--runtime=electron'], { + cwd: repoRoot, + stdio: 'inherit' + }) + if (result.error) { + console.error(`[headless-pairing] Electron runtime preflight failed: ${result.error.message}`) + process.exit(1) + } + if (result.status !== 0) { + process.exit(result.status ?? 1) + } +} + +/** + * Rewrites the CLI JSON readiness line into the pairing URL testers need. + */ +function printReadyLine(line) { + let payload + try { + payload = JSON.parse(line) + } catch { + return false + } + if (!payload || payload.type !== 'orca_server_ready') { + return false + } + console.log(`Orca server ready: ${payload.endpoint ?? 'websocket unavailable'}`) + if (payload.pairing?.endpoint) { + console.log(`Pairing endpoint: ${payload.pairing.endpoint}`) + } + if (payload.pairing?.webClientUrl) { + console.log(`Web client URL: ${payload.pairing.webClientUrl}`) + } + if (payload.pairing?.url) { + sawPairingUrl = true + console.log(`Pairing URL: ${payload.pairing.url}`) + console.error('[headless-pairing] server is running; press Ctrl+C to stop.') + return true + } + console.log('Pairing URL: unavailable') + return true +} + +/** + * Stops the foreground server; repeated signals force its process tree down. + */ +function stopChild(signal) { + if (!child || child.killed) { + return + } + stopAttempts += 1 + const targetSignal = stopAttempts > 1 ? 'SIGKILL' : signal + if (process.platform === 'win32' && child.pid) { + // Why: child.kill() only targets orca-dev on Windows; taskkill walks the + // CLI/Electron descendants so the fresh profile is not left locked. + const killer = spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { + stdio: 'ignore', + windowsHide: true + }) + killer.on('error', () => child?.kill(targetSignal)) + return + } + if (process.platform !== 'win32' && child.pid) { + // Why: orca-dev synchronously owns the CLI child, which owns Electron; kill + // the spawned process group so programmatic shutdown does not orphan serve. + try { + process.kill(-child.pid, targetSignal) + return + } catch { + // Fall back to the direct child below if the process group already exited. + } + } + child.kill(targetSignal) +} + +/** + * Removes only the ephemeral profile directory this script created. + */ +function cleanupProfile() { + if (cleanedUp) { + return + } + cleanedUp = true + if (parsed.keepProfile || !ownsProfileDir) { + console.error(`[headless-pairing] kept ${profileDir}`) + return + } + if (!existsSync(profileDir) || !profileDir.includes('orca-headless-pairing-profile-')) { + console.error(`[headless-pairing] skipped cleanup for unexpected profile path: ${profileDir}`) + return + } + try { + rmSync(profileDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }) + console.error(`[headless-pairing] removed ${profileDir}`) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.error(`[headless-pairing] skipped cleanup for ${profileDir}: ${message}`) + } +} diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index 4afaca929..67a50e6b5 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 3.9m + + downloads: 4.0m @@ -15,7 +15,7 @@ downloads downloads - 3.9m - 3.9m + 4.0m + 4.0m diff --git a/docs/assets/wechat-qr-backup.jpg b/docs/assets/wechat-qr-backup.jpg new file mode 100644 index 000000000..a6392babb Binary files /dev/null and b/docs/assets/wechat-qr-backup.jpg differ diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md index e1403aed2..6ebc3a03d 100644 --- a/docs/readme/README.es.md +++ b/docs/readme/README.es.md @@ -36,7 +36,7 @@ Supervisa y dirige a tus agentes desde el teléfono — recibe una notificación cuando un agente termine y envía instrucciones de seguimiento desde cualquier lugar. -[App Store de iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [APK para Android](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) +[App Store de iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [APK para Android](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ yay -S stably-orca-bin Vincúlala con tu app de escritorio para supervisar y dirigir a tus agentes desde el teléfono. - **iOS:** [Descargar desde App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) -- **Android:** [Descargar el APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [Descargar el APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) --- diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md index 22e461eb6..3d1c04693 100644 --- a/docs/readme/README.ja.md +++ b/docs/readme/README.ja.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.22/app-release.apk) · [ドキュメント →](https://www.onorca.dev/docs/mobile) +[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.24/app-release.apk) · [ドキュメント →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ 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.22/app-release.apk) +- **Android:** [APK をダウンロード](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) --- diff --git a/docs/readme/README.ko.md b/docs/readme/README.ko.md index b2fc48571..00a409242 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.22/app-release.apk) · [문서 →](https://www.onorca.dev/docs/mobile) +[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.24/app-release.apk) · [문서 →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ 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.22/app-release.apk) +- **Android:** [APK 다운로드](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) --- diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md index 3ba8d351b..bb28affe5 100644 --- a/docs/readme/README.pt.md +++ b/docs/readme/README.pt.md @@ -36,7 +36,7 @@ Monitore e conduza seus agentes pelo celular — receba uma notificação quando um agente terminar e envie instruções de acompanhamento de qualquer lugar. -[App Store para iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [APK Android 0.0.22](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) +[App Store para iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [APK Android 0.0.24](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) @@ -230,7 +230,7 @@ yay -S stably-orca-bin Conecte ao app desktop para monitorar e conduzir seus agentes pelo celular. - **iOS:** [Baixar na App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) ou [entrar no TestFlight](https://testflight.apple.com/join/YjeGMQBA) -- **Android:** [Baixar APK 0.0.22](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [Baixar APK 0.0.24](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) --- diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index d17ae0a8d..d8aa12b42 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.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.22/app-release.apk) · [文档 →](https://www.onorca.dev/docs/mobile) +[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.24/app-release.apk) · [文档 →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ 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.22/app-release.apk) +- **Android:** [下载 APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) --- diff --git a/electron.vite.config.ts b/electron.vite.config.ts index ca69fc8a7..b308601ee 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -182,6 +182,9 @@ export default defineConfig({ 'stt-worker': resolve('src/main/speech/stt-worker.ts'), 'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'), 'file-watcher-worker': resolve('src/main/runtime/file-watcher-worker.ts'), + // Why: forked with ELECTRON_RUN_AS_NODE so @parcel/watcher faults + // can't take down the main process (issue #7547). + 'parcel-watcher-process-entry': resolve('src/main/ipc/parcel-watcher-process-entry.ts'), // Why: electron-vite cleans out/main in dev. The dev CLI imports // this path for `orca agent hooks ...`, so it must survive rebuilds. 'agent-hooks/managed-agent-hook-controls': resolve( diff --git a/mobile/app.json b/mobile/app.json index b50147f04..568e7d676 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -2,7 +2,7 @@ "expo": { "name": "Orca", "slug": "orca-mobile", - "version": "0.0.24", + "version": "0.0.25", "orientation": "default", "icon": "./assets/icon.png", "userInterfaceStyle": "automatic", diff --git a/package.json b/package.json index 524ccf7b2..a29dbf6ac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca", - "version": "1.4.127-rc.0", + "version": "1.4.129-rc.1", "description": "Next-gen IDE for parallel agentic development", "homepage": "https://github.com/stablyai/orca", "author": "stablyai", @@ -82,6 +82,7 @@ "test:e2e:terminal-perf:summarize": "node config/scripts/summarize-terminal-perf-report.mjs", "test:e2e:terminal-perf:html-report": "node config/scripts/generate-terminal-perf-html-report.mjs", "test:e2e:ssh-docker-perf": "node config/scripts/run-ssh-docker-perf-e2e.mjs", + "win-update-e2e": "node tools/win-update-e2e/run.mjs", "test:e2e:ssh-codex-artifacts-repro": "node config/scripts/run-ssh-codex-artifacts-repro-e2e.mjs", "test:e2e:headful": "pnpm run ensure:electron-runtime && npx playwright test --config tests/playwright.config.ts --project electron-headful", "test:e2e:computer": "vitest run --config tests/e2e/vitest.config.ts", diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 12d4a64ee..0ee5498bf 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -434,6 +434,38 @@ describe('orca cli worktree awareness', () => { expect(logSpy).toHaveBeenCalledTimes(1) }) + it('resolves the invocation cwd from ORCA_CLI_CWD when no cwd is passed', async () => { + // Why: the SSH relay bridge runs the CLI on the Orca host with the remote + // shell's cwd carried in ORCA_CLI_CWD (#7716); cwd-based selectors must + // resolve against it, not the host process cwd. + process.env.ORCA_CLI_CWD = '/tmp/repo/feature/src' + try { + queueFixtures( + callMock, + worktreeListFixture([ + buildWorktree('/tmp/repo', 'main'), + buildWorktree('/tmp/repo/feature', 'feature/foo') + ]), + okFixture('req_1', { + worktree: { + id: 'repo::/tmp/repo/feature', + branch: 'feature/foo', + path: '/tmp/repo/feature' + } + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['worktree', 'current', '--json']) + + expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.show', { + worktree: 'id:repo::/tmp/repo/feature' + }) + } finally { + delete process.env.ORCA_CLI_CWD + } + }) + it.skipIf(process.platform === 'win32')( 'prepares and starts Claude Agent Teams in the current Orca terminal', async () => { diff --git a/src/cli/index.ts b/src/cli/index.ts index e2934812f..e9c128590 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -25,7 +25,19 @@ function shouldIgnoreRemoteSelection(commandPath: string[]): boolean { ) } -export async function main(argv = process.argv.slice(2), cwd = process.cwd()): Promise { +// Why: the SSH relay bridge executes this CLI on the Orca host while the +// caller's shell cwd lives on the remote machine (which cannot be chdir'd +// into). ORCA_CLI_CWD carries that remote cwd so cwd-based selectors like +// `--worktree active` resolve against the caller's directory. +function resolveInvocationCwd(): string { + const override = process.env.ORCA_CLI_CWD + return typeof override === 'string' && override.length > 0 ? override : process.cwd() +} + +export async function main( + argv = process.argv.slice(2), + cwd = resolveInvocationCwd() +): Promise { if (argv[0] === 'agent-teams-tmux') { await runAgentTeamsTmuxShim(argv.slice(1)) 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 8a85128cd..550af50bc 100644 --- a/src/main/agent-hooks/remote-hook-service-installers.test.ts +++ b/src/main/agent-hooks/remote-hook-service-installers.test.ts @@ -8,6 +8,7 @@ vi.mock('electron', () => ({ })) import { CodexHookService } from '../codex/hook-service' +import { DroidHookService } from '../droid/hook-service' import { CursorHookService } from '../cursor/hook-service' import { CommandCodeHookService } from '../command-code/hook-service' import { GeminiHookService } from '../gemini/hook-service' @@ -20,6 +21,24 @@ import { HermesHookService } from '../hermes/hook-service' import { DevinHookService } from '../devin/hook-service' import { KimiHookService } from '../kimi/hook-service' import { openClaudeHookService } from '../openclaude/hook-service' +import { ampHookService } from '../amp/hook-service' +import { antigravityHookService } from '../antigravity/hook-service' +import { claudeHookService } from '../claude/hook-service' +import { codexHookService } from '../codex/hook-service' +import { copilotHookService } from '../copilot/hook-service' +import { cursorHookService } from '../cursor/hook-service' +import { droidHookService } from '../droid/hook-service' +import { commandCodeHookService } from '../command-code/hook-service' +import { geminiHookService } from '../gemini/hook-service' +import { devinHookService } from '../devin/hook-service' +import { grokHookService } from '../grok/hook-service' +import { hermesHookService } from '../hermes/hook-service' +import { kimiHookService } from '../kimi/hook-service' +import { MANAGED_AGENT_HOOK_INSTALLERS } from './managed-agent-hook-controls' +import { + installRemoteManagedAgentHooks, + REMOTE_MANAGED_HOOK_INSTALLER_AGENTS +} from './remote-managed-hook-installers' type FakeFs = { files: Map @@ -166,6 +185,10 @@ describe('remote hook service installers', () => { { path: '/home/dev/.orca/agent-hooks/devin-hook.sh', install: (sftp: SFTPWrapper) => new DevinHookService().installRemote(sftp, '/home/dev') + }, + { + path: '/home/dev/.orca/agent-hooks/droid-hook.sh', + install: (sftp: SFTPWrapper) => new DroidHookService().installRemote(sftp, '/home/dev') } ] @@ -582,6 +605,107 @@ describe('remote hook service installers', () => { expect(fs.modes.get('/home/dev/.orca/agent-hooks/copilot-hook.sh')).toBe(0o755) }) + // Why: Droid (and Copilot) each shipped a working installRemote but were never + // registered in REMOTE_MANAGED_HOOK_INSTALLERS, so their status silently never + // appeared over SSH (issue #7253). Guard the whole bug class, not one agent: + // every locally-managed hook service that implements installRemote MUST be + // wired into the remote installer. + it('registers every managed agent that implements installRemote in the remote installer (issue #7253)', () => { + const servicesByAgent = new Map([ + ['claude', claudeHookService], + ['openclaude', openClaudeHookService], + ['codex', codexHookService], + ['gemini', geminiHookService], + ['antigravity', antigravityHookService], + ['amp', ampHookService], + ['cursor', cursorHookService], + ['droid', droidHookService], + ['command-code', commandCodeHookService], + ['grok', grokHookService], + ['copilot', copilotHookService], + ['hermes', hermesHookService], + ['devin', devinHookService], + ['kimi', kimiHookService] + ]) + + // Guard against a service silently missing from the map above as new agents land. + for (const [agent] of MANAGED_AGENT_HOOK_INSTALLERS) { + expect(servicesByAgent.has(agent)).toBe(true) + } + + const registered = new Set(REMOTE_MANAGED_HOOK_INSTALLER_AGENTS) + const missing: string[] = [] + for (const [agent, service] of servicesByAgent) { + if (typeof service.installRemote === 'function' && !registered.has(agent)) { + missing.push(agent) + } + } + expect(missing).toEqual([]) + }) + + 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 byAgent = new Map(results.map((r) => [r.agent, r.state])) + expect(byAgent.get('droid')).toBe('installed') + expect(byAgent.get('copilot')).toBe('installed') + }) + + it('installs remote Droid hooks into Factory settings.json (issue #7253)', async () => { + const { sftp, fs } = createFakeSftp() + + const status = await new DroidHookService().installRemote(sftp, '/home/dev') + + expect(status.state).toBe('installed') + expect(status.configPath).toBe('/home/dev/.factory/settings.json') + const config = JSON.parse(fs.files.get('/home/dev/.factory/settings.json')!) as { + hooks: Record + } + for (const eventName of [ + 'SessionStart', + 'UserPromptSubmit', + 'Stop', + 'SubagentStop', + 'PreToolUse', + 'PostToolUse', + 'PermissionRequest', + 'Notification' + ]) { + const definition = config.hooks[eventName]?.[0] + const command = definition?.hooks?.[0]?.command + expect(command).toContain('/home/dev/.orca/agent-hooks/droid-hook.sh') + expect(command).toMatch(/^if \[ -x /) + } + // Tool/permission events carry a `*` matcher; lifecycle events do not. + expect(config.hooks.PreToolUse?.[0]?.matcher).toBe('*') + expect(config.hooks.PostToolUse?.[0]?.matcher).toBe('*') + expect(config.hooks.PermissionRequest?.[0]?.matcher).toBe('*') + expect(config.hooks.Stop?.[0]?.matcher).toBeUndefined() + const script = fs.files.get('/home/dev/.orca/agent-hooks/droid-hook.sh') + expect(script).toContain('#!/bin/sh') + expect(script).toContain('/hook/droid') + expect(fs.modes.get('/home/dev/.orca/agent-hooks/droid-hook.sh')).toBe(0o755) + }) + + it('does not overwrite a malformed remote Factory settings.json', async () => { + const original = '{"hooks": }' + const { sftp, fs } = createFakeSftp({ + '/home/dev/.factory/settings.json': original + }) + + const status = await new DroidHookService().installRemote(sftp, '/home/dev') + + expect(status).toMatchObject({ + agent: 'droid', + state: 'error', + configPath: '/home/dev/.factory/settings.json', + managedHooksPresent: false, + detail: 'Could not parse remote Factory settings.json' + }) + expect(fs.files.get('/home/dev/.factory/settings.json')).toBe(original) + expect(fs.files.get('/home/dev/.orca/agent-hooks/droid-hook.sh')).toBeUndefined() + }) + it('installs remote Hermes plugin files and enables the plugin', async () => { const { sftp, fs } = createFakeSftp() diff --git a/src/main/agent-hooks/remote-managed-hook-installers.ts b/src/main/agent-hooks/remote-managed-hook-installers.ts index 7913b8635..e68ec2a8d 100644 --- a/src/main/agent-hooks/remote-managed-hook-installers.ts +++ b/src/main/agent-hooks/remote-managed-hook-installers.ts @@ -7,7 +7,9 @@ import { geminiHookService } from '../gemini/hook-service' import { antigravityHookService } from '../antigravity/hook-service' import { cursorHookService } from '../cursor/hook-service' import { commandCodeHookService } from '../command-code/hook-service' +import { copilotHookService } from '../copilot/hook-service' import { devinHookService } from '../devin/hook-service' +import { droidHookService } from '../droid/hook-service' import { grokHookService } from '../grok/hook-service' import { hermesHookService } from '../hermes/hook-service' import { kimiHookService } from '../kimi/hook-service' @@ -27,12 +29,20 @@ const REMOTE_MANAGED_HOOK_INSTALLERS: readonly RemoteManagedHookInstaller[] = [ ['amp', (sftp, remoteHome) => ampHookService.installRemote(sftp, remoteHome)], ['cursor', (sftp, remoteHome) => cursorHookService.installRemote(sftp, remoteHome)], ['command-code', (sftp, remoteHome) => commandCodeHookService.installRemote(sftp, remoteHome)], + ['copilot', (sftp, remoteHome) => copilotHookService.installRemote(sftp, remoteHome)], ['grok', (sftp, remoteHome) => grokHookService.installRemote(sftp, remoteHome)], + ['droid', (sftp, remoteHome) => droidHookService.installRemote(sftp, remoteHome)], ['hermes', (sftp, remoteHome) => hermesHookService.installRemote(sftp, remoteHome)], ['devin', (sftp, remoteHome) => devinHookService.installRemote(sftp, remoteHome)], ['kimi', (sftp, remoteHome) => kimiHookService.installRemote(sftp, remoteHome)] ] +/** Agents wired into the remote (SSH) hook installer. Exported so an invariant + * test can assert every locally-managed agent that implements `installRemote` + * is registered here — the omission that hid Droid/Copilot status over SSH. */ +export const REMOTE_MANAGED_HOOK_INSTALLER_AGENTS: readonly AgentHookInstallStatus['agent'][] = + REMOTE_MANAGED_HOOK_INSTALLERS.map(([agent]) => agent) + export async function installRemoteManagedAgentHooks( sftp: SFTPWrapper, remoteHome: string diff --git a/src/main/ai-vault/runtime-session-scanner.test.ts b/src/main/ai-vault/runtime-session-scanner.test.ts new file mode 100644 index 000000000..ffb2a1c39 --- /dev/null +++ b/src/main/ai-vault/runtime-session-scanner.test.ts @@ -0,0 +1,144 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AiVaultListResult, AiVaultSession } from '../../shared/ai-vault-types' + +const mocks = vi.hoisted(() => ({ + callRuntimeEnvironment: vi.fn(), + listEnvironments: vi.fn() +})) + +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: mocks.listEnvironments +})) + +vi.mock('../ipc/runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: mocks.callRuntimeEnvironment +})) + +const { getSavedRuntimeAiVaultHostInfos, scanRuntimeAiVaultSessions } = + await import('./runtime-session-scanner') + +beforeEach(() => { + vi.clearAllMocks() + mocks.listEnvironments.mockReturnValue([]) + mocks.callRuntimeEnvironment.mockResolvedValue({ + ok: true, + result: result([session('runtime:env-1', 'session-1')]) + }) +}) + +describe('runtime AI Vault session scanner', () => { + it('lists saved runtime environments as runtime execution hosts', () => { + mocks.listEnvironments.mockReturnValue([ + { id: 'env-1', name: 'Server 1' }, + { id: 'env-2', name: 'Server 2' } + ]) + + expect(getSavedRuntimeAiVaultHostInfos('/user-data')).toEqual([ + { environmentId: 'env-1', executionHostId: 'runtime:env-1' }, + { environmentId: 'env-2', executionHostId: 'runtime:env-2' } + ]) + }) + + it('forwards scan options to the runtime transport', async () => { + await scanRuntimeAiVaultSessions( + '/user-data', + 'env-1', + { + limit: 25, + force: true, + scopePaths: ['/srv/app'] + }, + { timeoutMs: 3000 } + ) + + expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith( + '/user-data', + 'env-1', + 'aiVault.listSessions', + { + limit: 25, + force: true, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:env-1' + }, + 3000 + ) + }) + + it('stamps sessions and issues returned for a different execution host', async () => { + mocks.callRuntimeEnvironment.mockResolvedValueOnce({ + ok: true, + result: result( + [session('local', 'session-1')], + [ + { + executionHostId: 'ssh:dev-box', + agent: 'codex', + path: '/sessions/session-1.jsonl', + message: 'could not parse session' + } + ] + ) + }) + + const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) + + expect(scanResult.sessions).toEqual([ + expect.objectContaining({ + id: 'runtime:env-1:codex:session-1:/sessions/session-1.jsonl', + executionHostId: 'runtime:env-1' + }) + ]) + expect(scanResult.issues).toEqual([ + expect.objectContaining({ + executionHostId: 'runtime:env-1', + agent: 'codex', + path: '/sessions/session-1.jsonl' + }) + ]) + }) + + it('stamps accepted sessions with the requested runtime host', async () => { + const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) + + expect(scanResult.sessions).toEqual([ + expect.objectContaining({ + id: 'runtime:env-1:codex:session-1:/sessions/session-1.jsonl', + executionHostId: 'runtime:env-1' + }) + ]) + }) +}) + +function result( + sessions: AiVaultSession[], + issues: AiVaultListResult['issues'] = [] +): AiVaultListResult { + return { sessions, issues, scannedAt: '2026-07-04T00:00:00.000Z' } +} + +function session( + executionHostId: AiVaultSession['executionHostId'], + sessionId: string +): AiVaultSession { + return { + id: `${executionHostId}:codex:${sessionId}:/sessions/${sessionId}.jsonl`, + executionHostId, + executionHostPlatform: 'linux', + agent: 'codex', + sessionId, + title: sessionId, + cwd: '/srv/app', + branch: null, + model: null, + filePath: `/sessions/${sessionId}.jsonl`, + codexHome: null, + createdAt: null, + updatedAt: '2026-07-04T03:00:00.000Z', + modifiedAt: '2026-07-04T00:00:00.000Z', + messageCount: 1, + totalTokens: 0, + previewMessages: [], + resumeCommand: `codex resume ${sessionId}` + } +} diff --git a/src/main/ai-vault/runtime-session-scanner.ts b/src/main/ai-vault/runtime-session-scanner.ts new file mode 100644 index 000000000..7a7008922 --- /dev/null +++ b/src/main/ai-vault/runtime-session-scanner.ts @@ -0,0 +1,176 @@ +import { z } from 'zod' +import { + AI_VAULT_AGENTS, + type AiVaultListArgs, + type AiVaultListResult, + type AiVaultSession +} from '../../shared/ai-vault-types' +import { normalizeExecutionHostId, toRuntimeExecutionHostId } from '../../shared/execution-host' +import { listEnvironments } from '../../shared/runtime-environment-store' +import { callRuntimeEnvironment } from '../ipc/runtime-environment-transport-routing' + +export type RuntimeAiVaultHostInfo = { + environmentId: string + executionHostId: `runtime:${string}` +} + +export type RuntimeAiVaultScanOptions = { + timeoutMs?: number +} + +const nodePlatformSchema = z.enum([ + 'aix', + 'android', + 'darwin', + 'freebsd', + 'haiku', + 'linux', + 'openbsd', + 'sunos', + 'win32', + 'cygwin', + 'netbsd' +] satisfies NodeJS.Platform[]) + +const aiVaultSessionPreviewMessageSchema = z.object({ + role: z.enum(['user', 'assistant', 'system', 'tool', 'unknown']), + text: z.string(), + timestamp: z.string().nullable() +}) + +const executionHostIdSchema = z.string().transform((value, ctx) => { + const normalized = normalizeExecutionHostId(value) + if (normalized) { + return normalized + } + ctx.addIssue({ + code: 'custom', + message: 'Invalid execution host id' + }) + return z.NEVER +}) + +const aiVaultListResultSchema = z.object({ + sessions: z.array( + z.object({ + id: z.string(), + executionHostId: executionHostIdSchema, + executionHostPlatform: nodePlatformSchema.nullable().optional(), + agent: z.enum(AI_VAULT_AGENTS), + sessionId: z.string(), + title: z.string(), + cwd: z.string().nullable(), + branch: z.string().nullable(), + model: z.string().nullable(), + filePath: z.string(), + codexHome: z.string().nullable(), + createdAt: z.string().nullable(), + updatedAt: z.string().nullable(), + modifiedAt: z.string(), + messageCount: z.number(), + totalTokens: z.number(), + previewMessages: z.array(aiVaultSessionPreviewMessageSchema), + resumeCommand: z.string() + }) + ), + issues: z.array( + z.object({ + executionHostId: executionHostIdSchema.optional(), + agent: z.enum(AI_VAULT_AGENTS), + path: z.string(), + message: z.string() + }) + ), + scannedAt: z.string() +}) + +export function getSavedRuntimeAiVaultHostInfos( + userDataPath: string +): readonly RuntimeAiVaultHostInfo[] { + return listEnvironments(userDataPath).map((environment) => ({ + environmentId: environment.id, + executionHostId: toRuntimeExecutionHostId(environment.id) + })) +} + +export async function scanRuntimeAiVaultSessions( + userDataPath: string, + environmentId: string, + args: AiVaultListArgs, + options: RuntimeAiVaultScanOptions = {} +): Promise { + const executionHostId = toRuntimeExecutionHostId(environmentId) + const response = await callRuntimeEnvironment( + userDataPath, + environmentId, + 'aiVault.listSessions', + { + limit: args.limit, + force: args.force, + scopePaths: args.scopePaths, + executionHostId + }, + options.timeoutMs + ) + if (response.ok === true) { + const parsed = aiVaultListResultSchema.safeParse(response.result) + if (parsed.success) { + return withRuntimeExecutionHost(parsed.data, executionHostId) + } + return runtimeScanIssueResult({ + executionHostId, + environmentId, + message: `Invalid aiVault.listSessions response: ${ + parsed.error.issues[0]?.message ?? 'unexpected result shape' + }` + }) + } + return runtimeScanIssueResult({ + executionHostId, + environmentId, + message: response.error.message + }) +} + +function withRuntimeExecutionHost( + result: AiVaultListResult, + executionHostId: `runtime:${string}` +): AiVaultListResult { + return { + sessions: result.sessions.map((session) => retagRuntimeSession(session, executionHostId)), + issues: result.issues.map((issue) => ({ ...issue, executionHostId })), + scannedAt: result.scannedAt + } +} + +function retagRuntimeSession( + session: AiVaultSession, + executionHostId: `runtime:${string}` +): AiVaultSession { + // The paired server is the transport, but the parent owns which concrete + // runtime host was scanned; never trust returned host ids across the boundary. + return { + ...session, + executionHostId, + id: `${executionHostId}:${session.agent}:${session.sessionId}:${session.filePath}` + } +} + +function runtimeScanIssueResult(args: { + executionHostId: `runtime:${string}` + environmentId: string + message: string +}): AiVaultListResult { + return { + sessions: [], + issues: [ + { + executionHostId: args.executionHostId, + agent: 'codex', + path: args.environmentId, + message: args.message + } + ], + scannedAt: new Date().toISOString() + } +} diff --git a/src/main/ai-vault/session-list-results.ts b/src/main/ai-vault/session-list-results.ts new file mode 100644 index 000000000..ea21dc590 --- /dev/null +++ b/src/main/ai-vault/session-list-results.ts @@ -0,0 +1,48 @@ +import type { + AiVaultListResult, + AiVaultScanIssue, + AiVaultSession +} from '../../shared/ai-vault-types' +import type { ExecutionHostId } from '../../shared/execution-host' +import { sessionSortTime } from './session-scanner-accumulator' + +export function aiVaultScanIssueResult(args: { + executionHostId?: ExecutionHostId + path: string + message: string +}): AiVaultListResult { + return { + sessions: [], + issues: [ + { + ...(args.executionHostId ? { executionHostId: args.executionHostId } : {}), + agent: 'codex', + path: args.path, + message: args.message + } + ], + scannedAt: new Date().toISOString() + } +} + +export function mergeAiVaultListResults( + results: readonly AiVaultListResult[], + rawLimit: number | undefined +): AiVaultListResult { + const limit = rawLimit && rawLimit > 0 ? Math.floor(rawLimit) : 1000 + const byId = new Map() + const issues: AiVaultScanIssue[] = [] + for (const result of results) { + for (const session of result.sessions) { + byId.set(session.id, session) + } + issues.push(...result.issues) + } + return { + sessions: [...byId.values()] + .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) + .slice(0, limit), + issues, + scannedAt: new Date().toISOString() + } +} diff --git a/src/main/daemon/daemon-entry.test.ts b/src/main/daemon/daemon-entry.test.ts index f2ac7a7ad..e24f1c8b3 100644 --- a/src/main/daemon/daemon-entry.test.ts +++ b/src/main/daemon/daemon-entry.test.ts @@ -29,4 +29,29 @@ describe('daemon-entry parseArgs', () => { it('throws with no args', () => { expect(() => parseArgs([])).toThrow('Usage:') }) + + it('omits logFilePath when --log-file is absent (adopted old daemons)', () => { + const result = parseArgs(['--socket', '/tmp/t.sock', '--token', '/tmp/t.token']) + expect(result).not.toHaveProperty('logFilePath') + }) + + it('parses --log-file when present', () => { + const result = parseArgs([ + '--socket', + '/tmp/t.sock', + '--token', + '/tmp/t.token', + '--log-file', + '/tmp/daemon.log' + ]) + expect(result).toEqual({ + socketPath: '/tmp/t.sock', + tokenPath: '/tmp/t.token', + logFilePath: '/tmp/daemon.log' + }) + }) + + it('still requires --socket and --token when --log-file is given', () => { + expect(() => parseArgs(['--log-file', '/tmp/daemon.log'])).toThrow('Usage:') + }) }) diff --git a/src/main/daemon/daemon-entry.ts b/src/main/daemon/daemon-entry.ts index 184037455..99118ef4b 100644 --- a/src/main/daemon/daemon-entry.ts +++ b/src/main/daemon/daemon-entry.ts @@ -10,10 +10,20 @@ import { startDaemon, type DaemonHandle } from './daemon-main' import { createPtySubprocess } from './pty-subprocess' import { warmWindowsConptyOnce } from './windows-conpty-warmup' import { warmPwshAvailabilityCache } from '../pwsh' +import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log' +import { PROTOCOL_VERSION } from './types' -export function parseArgs(argv: string[]): { socketPath: string; tokenPath: string } { +export type ParsedDaemonArgs = { + socketPath: string + tokenPath: string + /** Optional — absent for adopted old daemons and tests, which log nothing. */ + logFilePath?: string +} + +export function parseArgs(argv: string[]): ParsedDaemonArgs { let socketPath = '' let tokenPath = '' + let logFilePath = '' for (let i = 0; i < argv.length; i++) { if (argv[i] === '--socket' && argv[i + 1]) { @@ -22,18 +32,24 @@ export function parseArgs(argv: string[]): { socketPath: string; tokenPath: stri } else if (argv[i] === '--token' && argv[i + 1]) { tokenPath = argv[i + 1] i++ + } else if (argv[i] === '--log-file' && argv[i + 1]) { + logFilePath = argv[i + 1] + i++ } } if (!socketPath || !tokenPath) { - throw new Error('Usage: daemon-entry --socket --token ') + throw new Error('Usage: daemon-entry --socket --token [--log-file ]') } - return { socketPath, tokenPath } + return logFilePath ? { socketPath, tokenPath, logFilePath } : { socketPath, tokenPath } } async function main(): Promise { - const { socketPath, tokenPath } = parseArgs(process.argv.slice(2)) + const { socketPath, tokenPath, logFilePath } = parseArgs(process.argv.slice(2)) + // Fail-open: a broken log path must never block daemon startup. + const daemonLog = logFilePath ? createDaemonFileLog(logFilePath) : createNoopDaemonFileLog() + daemonLog.log('startup', { protocolVersion: PROTOCOL_VERSION, socketPath }) void warmPwshAvailabilityCache() // Why: node-pty can throw a C++ Napi::Error that escapes all JS try/catch @@ -55,29 +71,54 @@ async function main(): Promise { msg.includes('EBADF') || msg.includes('ENXIO')) if (isNativeError) { + daemonLog.log('uncaught-exception-suppressed', { name: err?.name, message: msg }) console.error('[daemon] Native PTY exception (suppressed):', err) return } + daemonLog.log('uncaught-exception-fatal', { name: err?.name, message: msg }) console.error('[daemon] Uncaught exception (fatal):', err) throw err }) let daemon: DaemonHandle | null = null + let shuttingDown = false + // Bound the wait so a wedged native shutdown can't leave the daemon running + // forever on SIGTERM/SIGINT (it would then survive a real quit, not just updates). + const SHUTDOWN_TIMEOUT_MS = 5000 - const shutdown = async (): Promise => { - if (daemon) { - await daemon.shutdown() - daemon = null + const shutdown = async (reason: string): Promise => { + // SIGTERM and SIGINT can both fire; guard against a double daemon.shutdown(). + if (shuttingDown) { + return + } + shuttingDown = true + daemonLog.log('shutdown', { reason }) + try { + if (daemon) { + await Promise.race([ + daemon.shutdown(), + new Promise((_, reject) => + setTimeout(() => reject(new Error('shutdown timeout')), SHUTDOWN_TIMEOUT_MS) + ) + ]) + daemon = null + } + } catch (err) { + // Never let a rejected shutdown() escape as an unhandled rejection and skip exit. + daemonLog.log('shutdown-error', { message: (err as Error)?.message }) + } finally { + daemonLog.close() + process.exit(0) } - process.exit(0) } - process.on('SIGTERM', () => void shutdown()) - process.on('SIGINT', () => void shutdown()) + process.on('SIGTERM', () => void shutdown('SIGTERM')) + process.on('SIGINT', () => void shutdown('SIGINT')) daemon = await startDaemon({ socketPath, tokenPath, + log: daemonLog, spawnSubprocess: (opts) => createPtySubprocess(opts) }) @@ -87,6 +128,7 @@ async function main(): Promise { // daemon self-reports it here for the pid file's pid-recycling guard. process.send({ type: 'ready', startedAtMs: Date.now() - process.uptime() * 1000 }) } + daemonLog.log('ready') warmWindowsConptyOnce() } diff --git a/src/main/daemon/daemon-file-log.test.ts b/src/main/daemon/daemon-file-log.test.ts new file mode 100644 index 000000000..90677b9da --- /dev/null +++ b/src/main/daemon/daemon-file-log.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log' + +let dir: string + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'daemon-file-log-')) +}) +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +function readLines(filePath: string): Record[] { + return readFileSync(filePath, 'utf8') + .split('\n') + .filter((l) => l.length > 0) + .map((l) => JSON.parse(l) as Record) +} + +describe('createDaemonFileLog', () => { + it('appends NDJSON lines with src/ts/pid/event and terse details', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath) + log.log('startup', { protocolVersion: 18 }) + log.log('session-created', { sessionId: 'abc', pid: 42 }) + + const lines = readLines(filePath) + expect(lines).toHaveLength(2) + expect(lines[0]).toMatchObject({ src: 'daemon', event: 'startup', protocolVersion: 18 }) + expect(typeof lines[0].ts).toBe('string') + expect(lines[0].pid).toBe(process.pid) + expect(lines[1]).toMatchObject({ event: 'session-created', sessionId: 'abc', pid: 42 }) + }) + + it('rotates at the byte cap and keeps only the configured rotated files', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath, { maxBytes: 150, maxRotatedFiles: 2 }) + for (let i = 0; i < 40; i++) { + log.log('tick', { i }) + } + + expect(existsSync(filePath)).toBe(true) + expect(existsSync(`${filePath}.1`)).toBe(true) + expect(existsSync(`${filePath}.2`)).toBe(true) + // Only 2 rotated files are retained — the oldest is dropped, not kept. + expect(existsSync(`${filePath}.3`)).toBe(false) + + // The active file holds the most recent line. + const active = readLines(filePath) + expect(active.at(-1)).toMatchObject({ event: 'tick', i: 39 }) + }) + + it('is fail-open when the log directory cannot be created', () => { + // Make the parent a file so mkdir of the logs subdir fails (ENOTDIR). + const blocker = join(dir, 'blocker') + writeFileSync(blocker, 'x') + const filePath = join(blocker, 'logs', 'daemon.log') + + const log = createDaemonFileLog(filePath) + expect(() => log.log('startup')).not.toThrow() + expect(() => log.close()).not.toThrow() + expect(existsSync(filePath)).toBe(false) + }) + + it('never throws from log() even for non-serializable details', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath) + const circular: Record = {} + circular.self = circular + expect(() => log.log('weird', circular)).not.toThrow() + // The bad line is dropped; a later good line still lands. + log.log('ok') + const lines = readLines(filePath) + expect(lines.map((l) => l.event)).toEqual(['ok']) + }) + + it('close() writes a terminal marker and stops further writes', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath) + log.log('startup') + log.close() + log.log('after-close') + + const events = readLines(filePath).map((l) => l.event) + expect(events).toEqual(['startup', 'daemon-log-closed']) + }) +}) + +describe('createNoopDaemonFileLog', () => { + it('accepts log/close calls without touching the filesystem', () => { + const log = createNoopDaemonFileLog() + expect(() => { + log.log('startup', { x: 1 }) + log.close() + }).not.toThrow() + }) +}) diff --git a/src/main/daemon/daemon-file-log.ts b/src/main/daemon/daemon-file-log.ts new file mode 100644 index 000000000..01090aedf --- /dev/null +++ b/src/main/daemon/daemon-file-log.ts @@ -0,0 +1,137 @@ +// Append-only NDJSON logger for the detached daemon process. The daemon runs +// out-of-process with stdio 'ignore', so console output goes nowhere; this +// writes lifecycle events to a rotated file under the app's logs directory so +// they land in diagnostic bundles (windows-terminal-update-survival-plan.md +// §Phase 0). Never log terminal input/output content or tokens. +// +// Two hard constraints: +// 1. FAIL-OPEN. Any error (EACCES, ENOSPC, bad path) disables logging and is +// swallowed — logging must never throw into daemon lifecycle logic or +// affect startup/shutdown. +// 2. Best-effort durability. Each line is a single synchronous appendFileSync +// so a process death mid-write can lose at most the last (partial) line; +// NDJSON readers skip a truncated trailing line. + +import { appendFileSync, existsSync, mkdirSync, renameSync, statSync, unlinkSync } from 'node:fs' +import { dirname } from 'node:path' + +const DEFAULT_MAX_BYTES = 5 * 1024 * 1024 // 5 MB +const DEFAULT_MAX_ROTATED_FILES = 2 // daemon.log + daemon.log.1 + daemon.log.2 +const PRIVATE_FILE_MODE = 0o600 + +/** Total files in the rotated daemon-log family (active + rotated). The bundle + * collector passes this to `listRotatedFiles` so it reads every rotated file. */ +export const DAEMON_LOG_MAX_FILES = DEFAULT_MAX_ROTATED_FILES + 1 + +export type DaemonFileLog = { + /** Append one lifecycle event. Terse fields only — never user data. */ + log(event: string, details?: Record): void + /** Best-effort marker that no further writes are expected. */ + close(): void +} + +export type DaemonFileLogOptions = { + readonly maxBytes?: number + readonly maxRotatedFiles?: number +} + +/** No-op logger used when the daemon was launched without `--log-file` (adopted + * old daemons, tests). Keeps every call site unconditional. */ +export function createNoopDaemonFileLog(): DaemonFileLog { + return { + log() {}, + close() {} + } +} + +export function createDaemonFileLog( + filePath: string, + opts: DaemonFileLogOptions = {} +): DaemonFileLog { + const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES + const maxRotatedFiles = opts.maxRotatedFiles ?? DEFAULT_MAX_ROTATED_FILES + + let disabled = false + let currentBytes = 0 + + function disable(): void { + disabled = true + } + + try { + mkdirSync(dirname(filePath), { recursive: true }) + currentBytes = existsSync(filePath) ? statSync(filePath).size : 0 + } catch { + // Unwritable path — stay fail-open; the first log() no-ops via `disabled`. + disable() + } + + // Cascade rename base → .1 → .2, dropping the oldest, then reset the active + // file. Any failure disables logging rather than risking a partial-rotation + // loop that keeps throwing on every subsequent line. + function rotate(): void { + // With no rotated slots there is nothing to cascade; return without the + // `currentBytes = 0` reset below, which would otherwise falsely report the + // still-growing active file as empty and defeat the overflow check forever. + if (maxRotatedFiles < 1) { + return + } + try { + for (let i = maxRotatedFiles; i >= 1; i--) { + const src = i === 1 ? filePath : `${filePath}.${i - 1}` + const dst = `${filePath}.${i}` + if (!existsSync(src)) { + continue + } + if (existsSync(dst)) { + unlinkSync(dst) + } + renameSync(src, dst) + } + currentBytes = 0 + } catch { + disable() + } + } + + function log(event: string, details: Record = {}): void { + if (disabled) { + return + } + let line: string + try { + line = `${JSON.stringify({ + src: 'daemon', + ts: new Date().toISOString(), + pid: process.pid, + event, + ...details + })}\n` + } catch { + // Non-serializable detail (circular ref) — drop the line, never crash. + return + } + const lineBytes = Buffer.byteLength(line, 'utf8') + if (currentBytes > 0 && currentBytes + lineBytes > maxBytes) { + rotate() + if (disabled) { + return + } + } + try { + appendFileSync(filePath, line, { mode: PRIVATE_FILE_MODE }) + currentBytes += lineBytes + } catch { + disable() + } + } + + return { + log, + close(): void { + // Best-effort marker; append is synchronous so there is nothing to flush. + log('daemon-log-closed') + disabled = true + } + } +} diff --git a/src/main/daemon/daemon-host-relocation.test.ts b/src/main/daemon/daemon-host-relocation.test.ts new file mode 100644 index 000000000..1d3ab98db --- /dev/null +++ b/src/main/daemon/daemon-host-relocation.test.ts @@ -0,0 +1,270 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync +} from 'node:fs' +import os from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// Mutable Electron app stub, hoisted so the vi.mock factory closes over it. +const { electronApp } = vi.hoisted(() => ({ + electronApp: { + isPackaged: true, + userDataPath: '', + version: '9.9.9', + getPath: (): string => electronApp.userDataPath, + getVersion: (): string => electronApp.version + } +})) + +vi.mock('electron', () => ({ app: electronApp })) + +import { + buildDaemonHostManifest, + collectPinnedDaemonVersions, + getRelocatedDaemonHost, + materializeRelocatedDaemonHost, + pruneOldDaemonHosts +} from './daemon-host-relocation' + +let tempDir: string +let installDir: string +let userDataDir: string +let localAppDataDir: string +const originalPlatform = process.platform +const originalExecPath = process.execPath +const originalResourcesPath = process.resourcesPath +const originalLocalAppData = process.env.LOCALAPPDATA + +function setProcessProp(key: string, value: unknown): void { + Object.defineProperty(process, key, { value, configurable: true, writable: true }) +} + +// Build a win-unpacked fixture: exe + blobs + DLLs at root, daemon bundle and +// node-pty under resources, mirroring the packaged layout the copy expects. +function buildInstallFixture(root: string): void { + mkdirSync(root, { recursive: true }) + writeFileSync(join(root, 'Orca.exe'), 'exe-bytes') + for (const name of ['icudtl.dat', 'snapshot_blob.bin', 'v8_context_snapshot.bin']) { + writeFileSync(join(root, name), name) + } + writeFileSync(join(root, 'ffmpeg.dll'), 'dll') + writeFileSync(join(root, 'libEGL.dll'), 'dll') + const mainDir = join(root, 'resources', 'app.asar.unpacked', 'out', 'main') + mkdirSync(join(mainDir, 'chunks'), { recursive: true }) + writeFileSync(join(mainDir, 'daemon-entry.js'), 'entry') + writeFileSync(join(mainDir, 'chunks', 'a.js'), 'chunk') + writeFileSync(join(root, 'resources', 'app.asar.unpacked', 'out', 'package.json'), '{}') + const nativeDir = join(root, 'resources', 'node_modules', 'node-pty', 'build', 'Release') + mkdirSync(nativeDir, { recursive: true }) + writeFileSync(join(nativeDir, 'conpty.node'), 'native') + writeFileSync(join(nativeDir, 'conpty.pdb'), 'debug-symbols') + mkdirSync(join(nativeDir, 'conpty'), { recursive: true }) + writeFileSync(join(nativeDir, 'conpty', 'conpty.dll'), 'conpty-dll') + // Both win32 prebuilds exist in the packaged tree (build-time prune keeps the + // `win32-` prefix); the copy filter keeps the host arch's and drops the other. + const prebuildsRoot = join(root, 'resources', 'node_modules', 'node-pty', 'prebuilds') + for (const arch of ['win32-x64', 'win32-arm64']) { + mkdirSync(join(prebuildsRoot, arch), { recursive: true }) + writeFileSync(join(prebuildsRoot, arch, 'pty.node'), `${arch}-prebuild`) + } +} + +// The win32 prebuild dir the running host arch loads vs. the one that is pruned. +const HOST_PREBUILD = `win32-${process.arch}` +const OTHER_PREBUILD = HOST_PREBUILD === 'win32-arm64' ? 'win32-x64' : 'win32-arm64' + +beforeEach(() => { + tempDir = mkdtempSync(join(os.tmpdir(), 'daemon-host-relocation-')) + installDir = join(tempDir, 'app') + userDataDir = join(tempDir, 'userData') + mkdirSync(userDataDir, { recursive: true }) + localAppDataDir = join(tempDir, 'localAppData') + mkdirSync(localAppDataDir, { recursive: true }) + process.env.LOCALAPPDATA = localAppDataDir + buildInstallFixture(installDir) + electronApp.isPackaged = true + electronApp.userDataPath = userDataDir + electronApp.version = '9.9.9' + setProcessProp('platform', 'win32') + setProcessProp('execPath', join(installDir, 'Orca.exe')) + setProcessProp('resourcesPath', join(installDir, 'resources')) +}) + +afterEach(() => { + setProcessProp('platform', originalPlatform) + setProcessProp('execPath', originalExecPath) + setProcessProp('resourcesPath', originalResourcesPath) + if (originalLocalAppData === undefined) { + delete process.env.LOCALAPPDATA + } else { + process.env.LOCALAPPDATA = originalLocalAppData + } + try { + rmSync(tempDir, { recursive: true, force: true }) + } catch { + // Best-effort + } +}) + +describe('buildDaemonHostManifest', () => { + it('mirrors the win-unpacked layout: exe + data blobs + resources tree, no GPU DLLs', () => { + const appDir = 'C:\\app' + const ops = buildDaemonHostManifest({ + appDir, + execPath: 'C:\\app\\Orca.exe', + resourcesPath: 'C:\\app\\resources', + entrySourcePath: 'C:\\app\\resources\\app.asar.unpacked\\out\\main\\daemon-entry.js', + entryRelPath: 'resources/app.asar.unpacked/out/main/daemon-entry.js' + }) + const byDest = new Map(ops.map((op) => [op.destRel, op])) + // The host exe is renamed to a distinct image name (NOT the source basename) + // so the NSIS updater's name-based `taskkill /IM Orca.exe` can't kill it. + expect(byDest.get('orca-terminal-daemon.exe')?.kind).toBe('file') + expect(byDest.has('Orca.exe')).toBe(false) + const exeOp = ops.find((op) => op.sourcePath === 'C:\\app\\Orca.exe') + expect(exeOp?.destRel).not.toBe('Orca.exe') + // V8/ICU data blobs are read by the Electron bootstrap and kept. + expect(byDest.has('icudtl.dat')).toBe(true) + // GPU/graphics DLLs are never loaded by the windowless host, so not copied. + expect(byDest.has('ffmpeg.dll')).toBe(false) + expect(byDest.has('libEGL.dll')).toBe(false) + // Daemon bundle + node-pty mirrored at their real resources-relative paths. + expect(byDest.get('resources/app.asar.unpacked/out/main/daemon-entry.js')?.kind).toBe('file') + expect(byDest.get('resources/app.asar.unpacked/out/main/chunks')?.kind).toBe('dir') + // node-pty is copied with a filter dropping .pdb + non-host-arch prebuilds. + const nodePtyOp = byDest.get('resources/node_modules/node-pty') + expect(nodePtyOp?.kind).toBe('dir') + expect(nodePtyOp?.filter?.('node-pty/build/Release/conpty.node')).toBe(true) + expect(nodePtyOp?.filter?.('node-pty/build/Release/conpty.pdb')).toBe(false) + expect(nodePtyOp?.filter?.(`node-pty/prebuilds/${HOST_PREBUILD}/pty.node`)).toBe(true) + expect(nodePtyOp?.filter?.(`node-pty/prebuilds/${OTHER_PREBUILD}/pty.node`)).toBe(false) + }) +}) + +describe('materializeRelocatedDaemonHost', () => { + it('copies the tree, writes the marker, and returns mirrored fork paths', () => { + const result = materializeRelocatedDaemonHost() + expect(result).not.toBeNull() + const dest = join(localAppDataDir, 'Orca', 'daemon-host', '9.9.9') + expect(result?.execPath).toBe(join(dest, 'orca-terminal-daemon.exe')) + expect(result?.entryPath).toBe( + join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'daemon-entry.js') + ) + expect(existsSync(result!.execPath)).toBe(true) + expect(existsSync(result!.entryPath)).toBe(true) + // node-pty native + conpty runtime copied at the require-resolvable path. + expect( + existsSync( + join(dest, 'resources', 'node_modules', 'node-pty', 'build', 'Release', 'conpty.node') + ) + ).toBe(true) + expect( + existsSync(join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'chunks', 'a.js')) + ).toBe(true) + // Trim: GPU DLLs, .pdb debug symbols, and non-host-arch prebuilds excluded; + // the host arch's prebuild is retained so node-pty resolves its native addon. + expect(existsSync(join(dest, 'ffmpeg.dll'))).toBe(false) + expect(existsSync(join(dest, 'libEGL.dll'))).toBe(false) + expect( + existsSync( + join(dest, 'resources', 'node_modules', 'node-pty', 'build', 'Release', 'conpty.pdb') + ) + ).toBe(false) + const prebuildsDest = join(dest, 'resources', 'node_modules', 'node-pty', 'prebuilds') + expect(existsSync(join(prebuildsDest, HOST_PREBUILD, 'pty.node'))).toBe(true) + expect(existsSync(join(prebuildsDest, OTHER_PREBUILD, 'pty.node'))).toBe(false) + // Marker records the version + entry rel path, written into the published dir. + const marker = JSON.parse(readFileSync(join(dest, '.materialized.json'), 'utf8')) + expect(marker.version).toBe('9.9.9') + expect(marker.entryRelPath).toBe('resources/app.asar.unpacked/out/main/daemon-entry.js') + }) + + it('is idempotent: a valid marker short-circuits without recopying', () => { + materializeRelocatedDaemonHost() + const dest = join(localAppDataDir, 'Orca', 'daemon-host', '9.9.9') + // A recopy would rm the dest; a sentinel inside it must survive the 2nd call. + const sentinel = join(dest, 'sentinel.txt') + writeFileSync(sentinel, 'keep') + const result = materializeRelocatedDaemonHost() + expect(result?.execPath).toBe(join(dest, 'orca-terminal-daemon.exe')) + expect(existsSync(sentinel)).toBe(true) + }) + + it('fails open on a missing required input, leaving no dest or staging dir', () => { + rmSync(join(installDir, 'resources', 'node_modules', 'node-pty'), { + recursive: true, + force: true + }) + const result = materializeRelocatedDaemonHost() + expect(result).toBeNull() + const hostRoot = join(localAppDataDir, 'Orca', 'daemon-host') + // Neither the published dest nor any leftover staging dir remains. + const remaining = existsSync(hostRoot) ? readdirSync(hostRoot) : [] + expect(remaining).toEqual([]) + }) + + it('returns null off win32', () => { + setProcessProp('platform', 'darwin') + expect(materializeRelocatedDaemonHost()).toBeNull() + expect(existsSync(join(localAppDataDir, 'Orca', 'daemon-host'))).toBe(false) + }) +}) + +describe('getRelocatedDaemonHost', () => { + it('returns null when the marker version does not match the current version', () => { + const dest = join(localAppDataDir, 'Orca', 'daemon-host', '9.9.9') + mkdirSync(dirname(join(dest, 'x')), { recursive: true }) + writeFileSync(join(dest, 'Orca.exe'), 'exe') + mkdirSync(join(dest, 'resources', 'app.asar.unpacked', 'out', 'main'), { recursive: true }) + writeFileSync( + join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'daemon-entry.js'), + 'e' + ) + writeFileSync( + join(dest, '.materialized.json'), + JSON.stringify({ + version: '8.8.8', + completedAt: '', + entryRelPath: 'resources/app.asar.unpacked/out/main/daemon-entry.js' + }) + ) + expect(getRelocatedDaemonHost()).toBeNull() + }) +}) + +describe('pruneOldDaemonHosts', () => { + it('removes unpinned non-current version dirs, keeping current and pinned', () => { + const root = join(localAppDataDir, 'Orca', 'daemon-host') + for (const v of ['9.9.9', '1.0.0', '2.0.0']) { + mkdirSync(join(root, v), { recursive: true }) + } + pruneOldDaemonHosts(new Set(['2.0.0'])) + expect(existsSync(join(root, '9.9.9'))).toBe(true) + expect(existsSync(join(root, '2.0.0'))).toBe(true) + expect(existsSync(join(root, '1.0.0'))).toBe(false) + }) +}) + +describe('collectPinnedDaemonVersions', () => { + it('pins the app version of a live daemon pid file and skips dead ones', () => { + const runtimeDir = join(userDataDir, 'daemon') + mkdirSync(runtimeDir, { recursive: true }) + writeFileSync( + join(runtimeDir, 'daemon-v4.pid'), + JSON.stringify({ pid: process.pid, startedAtMs: null, appVersion: '7.0.0' }) + ) + writeFileSync( + join(runtimeDir, 'daemon-v3.pid'), + JSON.stringify({ pid: 2147483646, startedAtMs: null, appVersion: '6.0.0' }) + ) + const pinned = collectPinnedDaemonVersions(runtimeDir) + expect(pinned.has('7.0.0')).toBe(true) + expect(pinned.has('6.0.0')).toBe(false) + }) +}) diff --git a/src/main/daemon/daemon-host-relocation.ts b/src/main/daemon/daemon-host-relocation.ts new file mode 100644 index 000000000..ac674fdd2 --- /dev/null +++ b/src/main/daemon/daemon-host-relocation.ts @@ -0,0 +1,398 @@ +import { randomBytes } from 'node:crypto' +import { + cpSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + renameSync, + rmSync, + writeFileSync +} from 'node:fs' +import { dirname, join, win32 as winPath } from 'node:path' +import { app } from 'electron' +import { parseDaemonPidFile, startTimeMatches } from './daemon-health' + +/** + * Relocates the terminal daemon's process image out of the app install + * directory into userData so it survives Windows auto-updates. + * + * Why: the daemon is forked as plain Node via ELECTRON_RUN_AS_NODE, so its + * image is the install-dir Orca.exe and its loaded modules (node-pty native, + * ConPTY runtime) map from the install dir. On update, electron-builder's NSIS + * installer deletes the old install and force-closes every process whose image + * lives under it — killing the daemon and every live terminal it owns. Copying + * the daemon's whole file closure to a version-keyed userData dir and forking + * from that copy takes its image + loaded modules out of the installer's reach. + * + * The copy keeps the ELECTRON binary run as node (not stock node.exe): a copy + * of Orca.exe (renamed to a distinct image name) is byte-identical, so + * run-as-node behavior — no console flashing, asar-correct — matches the in-dir + * fork exactly. The win-unpacked layout is mirrored verbatim so + * require('node-pty') and node-pty's native loader resolve the relocated tree + * identically to the packaged app. + * + * Fail-open everywhere: any failure returns null and the caller forks the + * install-dir host — the pre-relocation behavior, byte-identical off win32. + */ + +export type RelocatedDaemonHost = { + /** The relocated host exe to fork the daemon from (run as node). */ + execPath: string + /** The copied daemon-entry.js, mirrored under the relocated resources tree. */ + entryPath: string +} + +const HOST_SUBDIR = 'daemon-host' +const MARKER_NAME = '.materialized.json' + +// The relocated host is machine-specific runtime (~260MB). It must live under +// LOCAL appData, not the roaming userData dir, so a roaming profile or OneDrive +// Known-Folder-Move never syncs it (slow login/logout, sync bloat). This folder +// name is shared verbatim with the NSIS uninstall cleanup +// (config/nsis/daemon-host-uninstall.nsh), which removes +// %LOCALAPPDATA%\\daemon-host — keep the two in sync. +const LOCAL_HOST_ROOT_NAME = 'Orca' + +// The relocated host exe is a copy of Orca.exe renamed to a distinct image +// name. The NSIS updater's name-based kill (`taskkill /IM Orca.exe`) matches by +// image name, so a distinct name spares the daemon from that branch, while the +// userData path (outside $INSTDIR) spares it from the path-based branch. +const DAEMON_HOST_EXE_NAME = 'orca-terminal-daemon.exe' + +// V8 snapshots + ICU data the Electron bootstrap reads even under +// ELECTRON_RUN_AS_NODE; siblings of Orca.exe in win-unpacked. +const RUNTIME_DATA_FILES = ['icudtl.dat', 'snapshot_blob.bin', 'v8_context_snapshot.bin'] + +type CopyOp = { + sourcePath: string + /** Destination path relative to the host root, posix-separated. */ + destRel: string + kind: 'file' | 'dir' + /** When true, a missing source is skipped rather than failing the copy. */ + optional?: boolean + /** Per-source-path predicate for dir copies: return false to skip a path. */ + filter?: (sourcePath: string) => boolean +} + +type DaemonHostSources = { + appDir: string + execPath: string + resourcesPath: string + entrySourcePath: string + entryRelPath: string +} + +type MaterializeMarker = { + version: string + completedAt: string + entryRelPath: string +} + +// Uses win32 path semantics so Windows layout paths (drive letters, `\`) +// decompose correctly regardless of host OS — needed for cross-platform unit +// tests; production runs this on win32 only. +function toPosixRelative(fromDir: string, absPath: string): string { + return winPath.relative(fromDir, absPath).split(winPath.sep).join('/') +} + +function destPath(root: string, destRel: string): string { + return join(root, ...destRel.split('/')) +} + +// Mirror getDaemonEntryPath()'s resolution order (unpacked root first, then +// out/main) so the copied entry is the exact file the in-dir fork would run. +function resolveEntrySourcePath(resourcesPath: string): string { + const unpackedRoot = join(resourcesPath, 'app.asar.unpacked') + const direct = join(unpackedRoot, 'daemon-entry.js') + if (existsSync(direct)) { + return direct + } + return join(unpackedRoot, 'out', 'main', 'daemon-entry.js') +} + +// Discover the relocation inputs from the live packaged process, or null when +// relocation does not apply (non-win32, dev, or missing resourcesPath). +function collectDaemonHostSources(): DaemonHostSources | null { + if (process.platform !== 'win32' || !app.isPackaged) { + return null + } + const resourcesPath = process.resourcesPath + if (typeof resourcesPath !== 'string' || resourcesPath.length === 0) { + return null + } + const execPath = process.execPath + const appDir = winPath.dirname(execPath) + const entrySourcePath = resolveEntrySourcePath(resourcesPath) + return { + appDir, + execPath, + resourcesPath, + entrySourcePath, + entryRelPath: toPosixRelative(appDir, entrySourcePath) + } +} + +// node-pty ships debug symbols (.pdb) and a win32 prebuild dir per CPU arch; the +// run-as-node daemon loads neither the symbols nor any non-host-arch prebuild +// (verified against the live daemon's loaded module list), so they are filtered +// out of the copy — the bulk of node-pty's on-disk size. Keyed on the host arch +// rather than dropping arm64 outright so a future Windows-arm64 build keeps the +// `win32-arm64` prebuild it actually needs and prunes `win32-x64` instead. +const HOST_WIN_PREBUILD_DIR = `win32-${process.arch}`.toLowerCase() +function isRuntimeNodePtyPath(sourcePath: string): boolean { + const p = sourcePath.toLowerCase() + if (p.endsWith('.pdb')) { + return false + } + // Keep only the host arch's win32 prebuild; drop any other win32- dir. + const prebuild = p.match(/prebuilds[\\/](win32-[^\\/]+)/) + return !prebuild || prebuild[1] === HOST_WIN_PREBUILD_DIR +} + +/** + * The ordered copy plan. Every destRel mirrors the source's win-unpacked + * relative path so require() and node-pty's native loader resolve the mirror + * identically to the packaged app. Pure over its inputs so tests can assert the + * layout without a real build. + */ +export function buildDaemonHostManifest(sources: DaemonHostSources): CopyOp[] { + const { appDir, execPath, resourcesPath, entrySourcePath, entryRelPath } = sources + const ops: CopyOp[] = [] + + // Electron host binary + V8/ICU data blobs at the dest root. The exe is + // renamed to a distinct image name so the NSIS updater's name-based + // `taskkill /IM Orca.exe` can't match it; the blobs beside it are read by the + // Electron bootstrap by fixed name. Top-level DLLs are deliberately NOT copied + // — they are all GPU/graphics/media (swiftshader, vulkan, d3d, dxcompiler, + // ffmpeg) that a windowless run-as-node host never loads (verified empirically + // against the live daemon's module list), so copying them only wastes ~48MB. + ops.push({ sourcePath: execPath, destRel: DAEMON_HOST_EXE_NAME, kind: 'file' }) + for (const name of RUNTIME_DATA_FILES) { + ops.push({ sourcePath: join(appDir, name), destRel: name, kind: 'file', optional: true }) + } + + // Daemon bundle: entry + its sibling chunks/ + the unpacked out/package.json + // (CJS/ESM loader resolution), mirrored verbatim. + ops.push({ sourcePath: entrySourcePath, destRel: entryRelPath, kind: 'file' }) + const chunksDir = join(winPath.dirname(entrySourcePath), 'chunks') + ops.push({ + sourcePath: chunksDir, + destRel: toPosixRelative(appDir, chunksDir), + kind: 'dir', + optional: true + }) + const pkgJson = join(resourcesPath, 'app.asar.unpacked', 'out', 'package.json') + ops.push({ + sourcePath: pkgJson, + destRel: toPosixRelative(appDir, pkgJson), + kind: 'file', + optional: true + }) + + // node-pty package tree (native conpty.node + conpty/ runtime dir). It is a + // sibling of app.asar.unpacked; require('node-pty') resolves it by walking up + // from the mirrored daemon-entry dir to resources/node_modules. Filtered to + // drop .pdb debug symbols and other-arch prebuilds the host never loads. + const nodePtyDir = join(resourcesPath, 'node_modules', 'node-pty') + ops.push({ + sourcePath: nodePtyDir, + destRel: toPosixRelative(appDir, nodePtyDir), + kind: 'dir', + filter: isRuntimeNodePtyPath + }) + + return ops +} + +function executeManifest(ops: CopyOp[], stagingRoot: string): void { + for (const op of ops) { + if (!existsSync(op.sourcePath)) { + if (op.optional) { + continue + } + throw new Error(`daemon-host relocation: missing required input ${op.sourcePath}`) + } + const dest = destPath(stagingRoot, op.destRel) + mkdirSync(dirname(dest), { recursive: true }) + const { filter } = op + // Dereference symlinks so the copy holds no link back into the install dir. + cpSync(op.sourcePath, dest, { + recursive: op.kind === 'dir', + dereference: true, + force: true, + ...(filter ? { filter: (src: string) => filter(src) } : {}) + }) + } +} + +function readMarker(dir: string): MaterializeMarker | null { + try { + const parsed = JSON.parse( + readFileSync(join(dir, MARKER_NAME), 'utf8') + ) as Partial + if (typeof parsed.version === 'string' && typeof parsed.entryRelPath === 'string') { + return { + version: parsed.version, + completedAt: typeof parsed.completedAt === 'string' ? parsed.completedAt : '', + entryRelPath: parsed.entryRelPath + } + } + } catch { + // Missing/corrupt marker — treat as not materialized. + } + return null +} + +function hostRootDir(): string { + // Prefer LOCAL appData (see LOCAL_HOST_ROOT_NAME). Fall back to userData only + // if LOCALAPPDATA is somehow unset — a no-op off win32, where relocation never + // runs anyway; on win32 packaged the env var is always present. + const localAppData = process.env.LOCALAPPDATA + const base = + typeof localAppData === 'string' && localAppData.length > 0 + ? join(localAppData, LOCAL_HOST_ROOT_NAME) + : app.getPath('userData') + return join(base, HOST_SUBDIR) +} + +/** + * Cheap idempotency check: the relocated host for the current version, or null. + * Valid only when the marker matches this version AND the exe + entry exist, so + * a partial or stale copy never reports ready. + */ +export function getRelocatedDaemonHost(): RelocatedDaemonHost | null { + const sources = collectDaemonHostSources() + if (!sources) { + return null + } + const version = app.getVersion() + const dest = join(hostRootDir(), version) + const marker = readMarker(dest) + if (!marker || marker.version !== version) { + return null + } + const execPath = join(dest, DAEMON_HOST_EXE_NAME) + const entryPath = destPath(dest, marker.entryRelPath) + if (!existsSync(execPath) || !existsSync(entryPath)) { + return null + } + return { execPath, entryPath } +} + +/** + * Ensure the current version's daemon host is materialized under + * userData/daemon-host/, returning its fork paths or null (fail-open). + * Idempotent: a valid marker for this version short-circuits without recopying. + * The copy stages into a temp sibling and is published by atomic rename, so a + * crash mid-copy never leaves a half-populated dest. + */ +export function materializeRelocatedDaemonHost(): RelocatedDaemonHost | null { + const existing = getRelocatedDaemonHost() + if (existing) { + return existing + } + const sources = collectDaemonHostSources() + if (!sources) { + return null + } + const version = app.getVersion() + const root = hostRootDir() + const dest = join(root, version) + const staging = join(root, `${version}.staging-${randomBytes(6).toString('hex')}`) + try { + mkdirSync(root, { recursive: true }) + rmSync(staging, { recursive: true, force: true }) + executeManifest(buildDaemonHostManifest(sources), staging) + // Marker written LAST: an interrupted copy leaves a marker-less staging dir + // that the next launch discards, never a dest the cheap check trusts. + const marker: MaterializeMarker = { + version, + completedAt: new Date().toISOString(), + entryRelPath: sources.entryRelPath + } + writeFileSync(join(staging, MARKER_NAME), JSON.stringify(marker)) + // Replace any stale/partial dest, then publish the staging dir atomically. + rmSync(dest, { recursive: true, force: true }) + renameSync(staging, dest) + } catch { + try { + rmSync(staging, { recursive: true, force: true }) + } catch { + // Best-effort staging cleanup. + } + return null + } + return getRelocatedDaemonHost() +} + +function isDaemonPidAlive(pid: number, startedAtMs: number | null): boolean { + try { + process.kill(pid, 0) + } catch { + return false + } + return startTimeMatches(pid, startedAtMs) +} + +/** + * App versions still pinned by a live daemon, read from the daemon-v.pid + * files under `runtimeDir`. A surviving daemon runs from its version's host dir, + * so its dir must never be reclaimed while the process is alive. On win32 the + * start-time check cannot verify, so a matching pid pins conservatively. + */ +export function collectPinnedDaemonVersions(runtimeDir: string): Set { + const pinned = new Set() + let entries + try { + entries = readdirSync(runtimeDir, { withFileTypes: true }) + } catch { + return pinned + } + for (const entry of entries) { + if (!entry.isFile() || !/^daemon-v\d+\.pid$/.test(entry.name)) { + continue + } + let parsed + try { + parsed = parseDaemonPidFile(readFileSync(join(runtimeDir, entry.name), 'utf8')) + } catch { + continue + } + // appVersion null => a pre-relocation daemon forked from the install dir, + // which pins no host dir here. + if (parsed && parsed.appVersion !== null && isDaemonPidAlive(parsed.pid, parsed.startedAtMs)) { + pinned.add(parsed.appVersion) + } + } + return pinned +} + +/** + * Reclaim daemon-host/ dirs whose ver is neither the current version nor + * pinned by a live daemon. Best-effort — never throws; a still-locked or + * concurrently-staging dir is simply retried on a future launch. + */ +export function pruneOldDaemonHosts(pinnedVersions: ReadonlySet): void { + if (process.platform !== 'win32' || !app.isPackaged) { + return + } + const version = app.getVersion() + const root = hostRootDir() + let entries + try { + entries = readdirSync(root, { withFileTypes: true }) + } catch { + return + } + for (const entry of entries) { + if (!entry.isDirectory() || entry.name === version || pinnedVersions.has(entry.name)) { + continue + } + try { + rmSync(join(root, entry.name), { recursive: true, force: true }) + } catch { + // Still locked or already gone — retry on a future launch. + } + } +} diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts index 2afbe8778..345a87d65 100644 --- a/src/main/daemon/daemon-init.test.ts +++ b/src/main/daemon/daemon-init.test.ts @@ -1023,7 +1023,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ cwd: '/fake/userData', detached: true }) ) }) @@ -1149,7 +1156,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ cwd: '/fake/userData', detached: true }) ) }) @@ -1266,7 +1280,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) @@ -1723,7 +1744,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) @@ -1808,7 +1836,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index d4d016bec..51c5246f6 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -37,6 +37,11 @@ import { killStaleDaemon, parseDaemonPidFile } from './daemon-health' +import { + collectPinnedDaemonVersions, + materializeRelocatedDaemonHost, + pruneOldDaemonHosts +} from './daemon-host-relocation' import { DegradedDaemonPtyProvider } from './degraded-daemon-pty-provider' import { getLocalPtyProvider, @@ -45,6 +50,7 @@ import { rebindLocalProviderListeners } from '../ipc/pty' import { isStartupDiagnosticsEnabled, logStartupDiagnostic } from '../startup/startup-diagnostics' +import { getDaemonLogFilePath } from '../observability/logs-directory' import { confirmSeededClaudeLivePtys, hasSeededUnconfirmedClaudePtys @@ -94,6 +100,18 @@ function getDaemonEntryPath(): string { return join(basePath, 'out', 'main', 'daemon-entry.js') } +// Why: the detached daemon writes lifecycle events to a rotated file so field +// failures are diagnosable from a bundle. Honor the same hard privacy switch +// the local trace sink honors (ORCA_DIAGNOSTICS_DISABLED); absence of the arg +// is fully supported, so gating it off is safe and adoption-neutral. +function daemonLogArgs(): string[] { + const disabled = (process.env.ORCA_DIAGNOSTICS_DISABLED ?? '').trim().toLowerCase() + if (disabled === '1' || disabled === 'true') { + return [] + } + return ['--log-file', getDaemonLogFilePath()] +} + // Why: before spawning a new daemon, check if an existing one is alive by // attempting a TCP connection to the socket. If it connects, the daemon // survived from a previous app session — reuse it instead of spawning. @@ -277,27 +295,43 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { await killStaleDaemon(runtimeDir, socketPath, tokenPath) const userDataPath = app.getPath('userData') - const child = fork(entryPath, ['--socket', socketPath, '--token', tokenPath], { - // Why: detached daemons can outlive dev worktrees. Starting from - // userData keeps process.cwd() valid after a repo/worktree is deleted. - cwd: userDataPath, - // Why: detached + unref lets the daemon outlive the Electron process. - // stdio 'ignore' prevents the child from holding the parent's stdout - // open, which would prevent Electron from exiting cleanly. - detached: true, - stdio: ['ignore', 'ignore', 'ignore', 'ipc'], - // Why: ELECTRON_RUN_AS_NODE makes the forked process run as a plain - // Node.js process instead of an Electron renderer/main process. Without - // it, Electron's GPU/display initialization can interfere with native - // module operations like node-pty's posix_spawn of the spawn-helper. - env: { - ...process.env, - ELECTRON_RUN_AS_NODE: '1', - // Why: the detached daemon is plain Node and cannot call Electron's - // app.getPath(), but shell-ready rcfiles must live outside swept tmp. - ORCA_USER_DATA_PATH: userDataPath + // Why: on win32 packaged, fork from a copy of the Electron runtime staged + // in userData so the daemon's image + loaded modules escape the install dir + // the NSIS updater deletes and force-closes. Staged here (not at app start) + // so the one-time copy stays off the first-paint path and is skipped on + // launches that adopt a live daemon. Fail-open: null → in-dir host, below. + const relocatedHost = materializeRelocatedDaemonHost() + // Fork the relocated entry when available; otherwise the install-dir entry. + const forkEntryPath = relocatedHost ? relocatedHost.entryPath : entryPath + const child = fork( + forkEntryPath, + ['--socket', socketPath, '--token', tokenPath, ...daemonLogArgs()], + { + // Why: detached daemons can outlive dev worktrees. Starting from + // userData keeps process.cwd() valid after a repo/worktree is deleted. + cwd: userDataPath, + // Why: detached + unref lets the daemon outlive the Electron process. + // stdio 'ignore' prevents the child from holding the parent's stdout + // open, which would prevent Electron from exiting cleanly. + detached: true, + stdio: ['ignore', 'ignore', 'ignore', 'ipc'], + // Why: run the relocated Orca.exe copy instead of the install-dir one. + // It is byte-identical, so run-as-node behavior is unchanged; only the + // image path moves out of the updater's kill zone. + ...(relocatedHost ? { execPath: relocatedHost.execPath } : {}), + // Why: ELECTRON_RUN_AS_NODE makes the forked process run as a plain + // Node.js process instead of an Electron renderer/main process. Without + // it, Electron's GPU/display initialization can interfere with native + // module operations like node-pty's posix_spawn of the spawn-helper. + env: { + ...process.env, + ELECTRON_RUN_AS_NODE: '1', + // Why: the detached daemon is plain Node and cannot call Electron's + // app.getPath(), but shell-ready rcfiles must live outside swept tmp. + ORCA_USER_DATA_PATH: userDataPath + } } - }) + ) // Wait for the daemon to signal readiness via IPC await new Promise((resolve, reject) => { @@ -419,6 +453,10 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise // throws, a stale spawner would prevent shutdownDaemon() from cleaning up // correctly on retry. const info = await newSpawner.ensureRunning() + // Reclaim superseded daemon-host copies on EVERY launch, not just on a fresh + // spawn: surviving daemons make spawns rare, so a spawn-only sweep would let + // old-version copies accumulate. Current + live-daemon-pinned versions stay. + pruneOldDaemonHosts(collectPinnedDaemonVersions(runtimeDir)) const launchMode = newSpawner.getHandle()?.mode logDaemonMilestone('daemon-current-ready') if (signal?.aborted) { diff --git a/src/main/daemon/daemon-main.ts b/src/main/daemon/daemon-main.ts index 63078067c..82f4dad7b 100644 --- a/src/main/daemon/daemon-main.ts +++ b/src/main/daemon/daemon-main.ts @@ -1,9 +1,11 @@ import { DaemonServer, type DaemonServerOptions } from './daemon-server' +import type { DaemonFileLog } from './daemon-file-log' export type DaemonStartOptions = { socketPath: string tokenPath: string spawnSubprocess: DaemonServerOptions['spawnSubprocess'] + log?: DaemonFileLog } export type DaemonHandle = { @@ -14,7 +16,8 @@ export async function startDaemon(opts: DaemonStartOptions): Promise Promise + log?: DaemonFileLog spawnSubprocess: (opts: { sessionId: string cols: number @@ -57,6 +59,7 @@ export class DaemonServer { private socketPath: string private tokenPath: string private ptySpawnHealthCheck: () => Promise + private log: DaemonFileLog private clients = new Map() private streamDataBatcher = new DaemonStreamDataBatcher( @@ -115,6 +118,7 @@ export class DaemonServer { })), backgroundedSessionIdSuffixes: this.transientFactRelay.backgroundedSessionIdSuffixes() })) + this.log = opts.log ?? createNoopDaemonFileLog() } async start(): Promise { @@ -190,23 +194,30 @@ export class DaemonServer { ): void { const hello = msg as HelloMessage if (hello.type !== 'hello') { + this.log.log('client-hello-rejected', { reason: 'expected-hello' }) socket.write(encodeNdjson({ type: 'hello', ok: false, error: 'Expected hello' })) socket.destroy() return } if (hello.version !== PROTOCOL_VERSION) { + this.log.log('client-hello-rejected', { + reason: 'protocol-mismatch', + clientVersion: hello.version + }) socket.write(encodeNdjson({ type: 'hello', ok: false, error: 'Protocol version mismatch' })) socket.destroy() return } if (hello.token !== this.token) { + this.log.log('client-hello-rejected', { reason: 'invalid-token', role: hello.role }) socket.write(encodeNdjson({ type: 'hello', ok: false, error: 'Invalid token' })) socket.destroy() return } + this.log.log('client-hello-accepted', { role: hello.role, clientId: hello.clientId }) socket.write(encodeNdjson({ type: 'hello', ok: true })) if (hello.role === 'control') { @@ -355,6 +366,7 @@ export class DaemonServer { onExit: (code) => { // Why: exit tears down renderer handlers; flush final output first // so the last few milliseconds of PTY data are not stranded. + this.log.log('session-exited', { sessionId: p.sessionId, code }) this.streamDataBatcher.flush(clientId) recordDaemonStreamBacklogEvent('sessionExit', { sessionIdSuffix: p.sessionId.slice(-10) @@ -387,6 +399,10 @@ export class DaemonServer { payload: { background: true } }) } + this.log.log(result.isNew ? 'session-created' : 'session-attached', { + sessionId: p.sessionId, + pid: result.pid + }) return { isNew: result.isNew, snapshot: result.snapshot, @@ -474,6 +490,10 @@ export class DaemonServer { case 'kill': this.lastInputAtBySessionId.delete(request.payload.sessionId) + this.log.log('session-killed', { + sessionId: request.payload.sessionId, + immediate: request.payload.immediate === true + }) this.host.kill(request.payload.sessionId, { immediate: request.payload.immediate }) return {} @@ -484,6 +504,7 @@ export class DaemonServer { case 'detach': // Note: detach token handling is simplified here — full implementation // would track tokens per client + this.log.log('session-detached', { sessionId: request.payload.sessionId }) return {} case 'getCwd': @@ -540,6 +561,10 @@ export class DaemonServer { return { healthy: true } case 'shutdown': + this.log.log('shutdown', { + reason: 'rpc', + killSessions: request.payload.killSessions === true + }) if (request.payload.killSessions) { this.host.dispose() } diff --git a/src/main/daemon/headless-emulator.ts b/src/main/daemon/headless-emulator.ts index 8f12d5968..e2a0654e3 100644 --- a/src/main/daemon/headless-emulator.ts +++ b/src/main/daemon/headless-emulator.ts @@ -62,6 +62,11 @@ const CONPTY_DA1_RESPONSE = '\x1b[?61;4c' export class HeadlessEmulator { private terminal: Terminal private serializer: SerializeAddon + // Why: our restructure owns cwd/title via TerminalOscCwdTitleScanner and the + // DECSET mouse modes via TerminalMouseModeMirror (functionally identical to + // main's inline cwd/lastTitle/oscScanTail + TerminalPrivateModeTracker, which + // only tracks the same mouse modes). restoredOscLinks/disposed/partialEscapeTail + // are declared below. private oscText: TerminalOscCwdTitleScanner private mouseModes = new TerminalMouseModeMirror() private readonly pathFlavor?: 'posix' | 'win32' @@ -330,7 +335,13 @@ export class HeadlessEmulator { cols: this.terminal.cols, rows: this.terminal.rows, scrollbackLines: this.terminal.buffer.normal.length - this.terminal.rows, - lastTitle: this.oscText.lastTitle ?? undefined + lastTitle: this.oscText.lastTitle ?? undefined, + // Why: written LAST by the restorer (after any reset) so the next live + // chunk completes this dangling sequence instead of rendering it literally + // (Bug E / #7329). Its bytes are already counted by the snapshot seq. + ...(this.partialEscapeTail.length > 0 + ? { pendingEscapeTailAnsi: this.partialEscapeTail } + : {}) } if (this.partialEscapeTail.length > 0) { // Why a separate field, not part of snapshotAnsi: consumers write their diff --git a/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts new file mode 100644 index 000000000..34a0e095e --- /dev/null +++ b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from 'vitest' +import { Terminal } from '@xterm/headless' +import { HeadlessEmulator } from './headless-emulator' + +// Repro for #7329: "remote server + terminal" — typing gets escape sequences +// injected/wrapped around it and follow-up commands are corrupted. +// +// The remote-server path serializes terminal state on the daemon via +// HeadlessEmulator.getSnapshot() (SerializeAddon + buildRehydrateSequences) and +// replays it into the renderer xterm, then applies POST_REPLAY_REATTACH_RESET. +// This test drives the REAL daemon serializer and a REAL renderer-side xterm to +// see what the user's terminal ends up looking like after a subscribe/reattach. + +const RESET_TERMINAL_CURSOR_STYLE = '\x1b[0 q' +const RESET_KITTY_KEYBOARD_PROTOCOL = '\x1b[<99u\x1b[=0u' +// Verbatim from layout-serialization.ts (the reattach path the remote onSnapshot uses). +const POST_REPLAY_REATTACH_RESET = `${RESET_TERMINAL_CURSOR_STYLE}${RESET_KITTY_KEYBOARD_PROTOCOL}\x1b[?25h\x1b[?1004l` + +function writeXterm(term: Terminal, data: string): Promise { + return new Promise((resolve) => term.write(data, resolve)) +} + +async function emulatorWrite(emu: HeadlessEmulator, data: string): Promise { + await emu.write(data) +} + +/** Replay a daemon snapshot into a renderer xterm exactly like the remote + * onSnapshot → replayDataCallback path: clear, write rehydrate+snapshot, + * then the reattach mode reset. */ +async function replayRemoteSnapshot( + term: Terminal, + snapshot: { rehydrateSequences: string; snapshotAnsi: string; pendingEscapeTailAnsi?: string } +): Promise { + await writeXterm(term, '\x1b[2J\x1b[3J\x1b[H') + await writeXterm(term, snapshot.rehydrateSequences + snapshot.snapshotAnsi) + await writeXterm(term, POST_REPLAY_REATTACH_RESET) + // The fix: the restorer writes the pending mid-escape tail LAST, after the + // reset (mirrors drainReplayDataQueue in pty-connection.ts). + if (snapshot.pendingEscapeTailAnsi) { + await writeXterm(term, snapshot.pendingEscapeTailAnsi) + } +} + +function renderVisible(term: Terminal): string { + const buf = term.buffer.active + const lines: string[] = [] + for (let y = 0; y < term.rows; y += 1) { + lines.push(buf.getLine(buf.viewportY + y)?.translateToString(true) ?? '') + } + return lines.join('\n').replace(/\s+$/g, '') +} + +describe('#7329 remote-server snapshot corruption', () => { + it('leaves bracketed-paste + mouse modes armed after a reattach snapshot', async () => { + const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + // A live remote shell that armed bracketed paste (bash 4.4+/readline + // default) and vt200+SGR mouse (a TUI the user just exited). + await emulatorWrite(emu, '\x1b[?2004h\x1b[?1000h\x1b[?1006h') + await emulatorWrite(emu, 'user@host:~$ ') + + const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) + // The daemon snapshot re-arms the modes it observed. + expect(snapshot.rehydrateSequences).toContain('\x1b[?2004h') + expect(snapshot.modes.bracketedPaste).toBe(true) + expect(snapshot.modes.mouseTracking).toBe(true) + + await replayRemoteSnapshot(term, snapshot) + + // After the remote reattach reset, the renderer xterm is STILL in + // bracketed-paste + mouse mode — even though POST_REPLAY_REATTACH_RESET + // ran. Cold restore's POST_REPLAY_MODE_RESET would have cleared these. + expect(term.modes.bracketedPasteMode).toBe(true) // leak + expect(term.modes.mouseTrackingMode).not.toBe('none') // leak + } finally { + emu.dispose() + term.dispose() + } + }) + + it('drops a mid-escape tail so continuation bytes render literally after reattach', async () => { + const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + // A remote PTY read that ends mid-escape: the shell was about to paint a + // colored prompt but the read boundary split the SGR sequence. The next + // read carries the continuation. The daemon serializes BETWEEN the two + // reads (e.g. the client subscribes/reattaches right then). + await emulatorWrite(emu, 'first line\r\n') + await emulatorWrite(emu, '\x1b[3') // <-- partial SGR: "\x1b[38;5;...m" started + + const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) + // The serializer still cannot put the dangling "\x1b[3" in the screen ANSI + // (it lives in the parser)... + expect(snapshot.snapshotAnsi).not.toContain('\x1b[3') + // ...but the emulator now ships it as a separate pending-escape tail. + expect(snapshot.pendingEscapeTailAnsi).toBe('\x1b[3') + + await replayRemoteSnapshot(term, snapshot) + + // The continuation of the split escape arrives as the next live chunk. + await writeXterm(term, '8;5;196mred$ yes\r\n') + + const visible = renderVisible(term) + // FIXED: the tail was replayed after the reset, so the continuation + // "8;5;196m" completes the SGR escape and is consumed — not rendered + // literally. The visible text is just the prompt + typed command. + expect(visible).not.toContain('8;5;196m') + expect(visible).toContain('red$ yes') + } finally { + emu.dispose() + term.dispose() + } + }) + + it('does not eat the continuation byte when the tail and continuation are contiguous', async () => { + // The safety property the fix relies on (mirrors the snapshot-seq accounting + // in orca-runtime/getOutputAfterSnapshotSeq): the snapshot seq counts the + // tail bytes, so the FIRST live chunk after the snapshot is the exact + // continuation and completes the dangling sequence with no eaten byte. + const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + await emulatorWrite(emu, '\x1b[38;5;') // dangling: params so far + const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) + expect(snapshot.pendingEscapeTailAnsi).toBe('\x1b[38;5;') + await replayRemoteSnapshot(term, snapshot) + // Continuation completes the SGR then prints a visible token. + await writeXterm(term, '82mHELLO') + const visible = renderVisible(term) + // No byte of "82m" leaks; the token renders whole (color applied). + expect(visible).toBe('HELLO') + } finally { + emu.dispose() + term.dispose() + } + }) + + it('documents the residual edge: an idle-death tail eats the next output byte', async () => { + // KNOWN, ACCEPTED trade-off: if a mid-escape read is the LAST thing the + // process emits (it dies/idles and never sends the continuation), the tail + // sits armed in the parser and the NEXT unrelated output loses its first + // byte. This is strictly narrower than the bug it fixes (which garbled every + // real split escape), and pre-fix such a stream simply dropped the partial. + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + await writeXterm(term, 'prompt$ ') + await writeXterm(term, '\x1b[3') // armed tail, no continuation ever comes + await writeXterm(term, 'yes\r\n') // unrelated later output + // The 'y' is absorbed as a CSI parameter of the dangling sequence. + expect(renderVisible(term)).toBe('prompt$ es') + } finally { + term.dispose() + } + }) +}) diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts index 8c0a1f2ee..d16e62e81 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -24,8 +24,8 @@ export type TerminalSnapshot = { * parser is still holding (a PTY read ended mid-escape). Restorers must * write this LAST — after their own post-replay resets, immediately before * post-snapshot live chunks — so the continuation bytes complete it - * exactly as live (Bug E, notes/garble-fuzz-divergences.md). Its bytes are - * already counted by the snapshot seq. */ + * exactly as live (Bug E / #7329, notes/garble-fuzz-divergences.md). Its + * bytes are already counted by the snapshot seq. */ pendingEscapeTailAnsi?: string /** Scrollback portion only (rows above the visible viewport). Write this * to preserve history without interfering with TUI repaints. */ diff --git a/src/main/droid/hook-service.ts b/src/main/droid/hook-service.ts index 920e07998..946f5ac88 100644 --- a/src/main/droid/hook-service.ts +++ b/src/main/droid/hook-service.ts @@ -1,5 +1,6 @@ import { homedir } from 'node:os' import { join } from 'node:path' +import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { buildManagedCommandHook, @@ -12,8 +13,14 @@ import { wrapWindowsHookCommand, writeHooksJson, writeManagedScript, - type HookDefinition + type HookDefinition, + type HooksConfig } from '../agent-hooks/installer-utils' +import { + readHooksJsonRemote, + writeHooksJsonRemote, + writeManagedScriptRemote +} from '../agent-hooks/installer-utils-remote' // Why: SessionStart is installed (not just listened for) so that resuming a // droid session via `droid --resume` resets the per-pane prompt/tool caches @@ -64,8 +71,8 @@ function getManagedCommand(scriptPath: string): string { : wrapPosixHookCommand(scriptPath) } -function getManagedScript(): string { - if (process.platform === 'win32') { +function getManagedScript(target: 'local' | 'posix' = 'local'): string { + if (target === 'local' && process.platform === 'win32') { return [ '@echo off', 'setlocal', @@ -111,6 +118,45 @@ function getManagedScript(): string { ].join('\n') } +// Why: local install() and installRemote() must produce byte-identical Factory +// settings.json hook trees; sharing this mutation is what keeps the SSH install +// from drifting off the local one (the exact class of bug that left Droid with +// no remote installer at all — issue #7253). +function buildInstalledDroidConfig( + config: HooksConfig, + command: string, + scriptFileName: string +): void { + const nextHooks = { ...config.hooks } + const isManagedCommand = createManagedCommandMatcher(scriptFileName) + const managedEvents = new Set(DROID_EVENTS.map((event) => event.eventName)) + + // Why: sweep managed entries out of events we no longer subscribe to. + for (const [eventName, definitions] of Object.entries(nextHooks)) { + if (managedEvents.has(eventName) || !Array.isArray(definitions)) { + continue + } + const cleaned = removeManagedCommands(definitions, isManagedCommand) + if (cleaned.length === 0) { + delete nextHooks[eventName] + } else { + nextHooks[eventName] = cleaned + } + } + + for (const event of DROID_EVENTS) { + const current = Array.isArray(nextHooks[event.eventName]) ? nextHooks[event.eventName] : [] + const cleaned = removeManagedCommands(current, isManagedCommand) + const definition: HookDefinition = { + ...event.definition, + hooks: [buildManagedCommandHook(command)] + } + nextHooks[event.eventName] = [...cleaned, definition] + } + + config.hooks = nextHooks +} + export class DroidHookService { getStatus(): AgentHookInstallStatus { const configPath = getConfigPath() @@ -189,43 +235,57 @@ export class DroidHookService { } } - const command = getManagedCommand(scriptPath) - const nextHooks = { ...config.hooks } - const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName()) - const managedEvents = new Set(DROID_EVENTS.map((event) => event.eventName)) - - // Why: sweep managed entries out of events we no longer subscribe to. - for (const [eventName, definitions] of Object.entries(nextHooks)) { - if (managedEvents.has(eventName)) { - continue - } - if (!Array.isArray(definitions)) { - continue - } - const cleaned = removeManagedCommands(definitions, isManagedCommand) - if (cleaned.length === 0) { - delete nextHooks[eventName] - } else { - nextHooks[eventName] = cleaned - } - } - - for (const event of DROID_EVENTS) { - const current = Array.isArray(nextHooks[event.eventName]) ? nextHooks[event.eventName] : [] - const cleaned = removeManagedCommands(current, isManagedCommand) - const definition: HookDefinition = { - ...event.definition, - hooks: [buildManagedCommandHook(command)] - } - nextHooks[event.eventName] = [...cleaned, definition] - } - - config.hooks = nextHooks + buildInstalledDroidConfig(config, getManagedCommand(scriptPath), getManagedScriptFileName()) writeManagedScript(scriptPath, getManagedScript()) writeHooksJson(configPath, config) return this.getStatus() } + // Why: SSH remotes run the Droid CLI on the remote host, so its hook config + // and managed script must be written into the remote ~/.factory + ~/.orca via + // SFTP. Without this, Droid never fires the managed hook over SSH and its + // status row is absent from the task tree (issue #7253). Mirrors the local + // install() but always emits POSIX script/paths — even from a Windows host. + async installRemote(sftp: SFTPWrapper, remoteHome: string): Promise { + const home = remoteHome.replace(/\/$/, '') + const remoteConfigPath = `${home}/.factory/settings.json` + const remoteScriptPath = `${home}/.orca/agent-hooks/droid-hook.sh` + try { + const config = await readHooksJsonRemote(sftp, remoteConfigPath) + if (!config) { + return { + agent: 'droid', + state: 'error', + configPath: remoteConfigPath, + managedHooksPresent: false, + detail: 'Could not parse remote Factory settings.json' + } + } + + buildInstalledDroidConfig(config, wrapPosixHookCommand(remoteScriptPath), 'droid-hook.sh') + // Why: script first, config last — a partial config write must never + // point Droid at a script that isn't on disk yet. + await writeManagedScriptRemote(sftp, remoteScriptPath, getManagedScript('posix')) + await writeHooksJsonRemote(sftp, remoteConfigPath, config) + + return { + agent: 'droid', + state: 'installed', + configPath: remoteConfigPath, + managedHooksPresent: true, + detail: null + } + } catch (err) { + return { + agent: 'droid', + state: 'error', + configPath: remoteConfigPath, + managedHooksPresent: false, + detail: err instanceof Error ? err.message : String(err) + } + } + } + remove(): AgentHookInstallStatus { const configPath = getConfigPath() const config = readHooksJson(configPath) diff --git a/src/main/index.ts b/src/main/index.ts index 8cde5a367..584d154fb 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -111,6 +111,7 @@ import { import { createMainWindow, loadMainWindow } from './window/createMainWindow' import { createSystemTray, destroySystemTray } from './tray/system-tray' import { focusExistingMainWindow } from './window/focus-existing-window' +import { notifyMainWindowBecameVisible } from './window/main-window-visibility' import { CodexAccountService } from './codex-accounts/service' import { CodexRuntimeHomeService } from './codex-accounts/runtime-home-service' import { @@ -151,6 +152,7 @@ import { AutomationService } from './automations/service' import { createHeadlessAutomationOutputSnapshotBuffer } from './automations/headless-dispatch' import { buildHeadlessAutomationWorktreeCreateArgs } from './automations/headless-workspace-create' import { AgentAwakeService } from './agent-awake-service' +import { registerSystemResumeBroadcast } from './system-resume-broadcast' import { getCrashBreadcrumbSnapshot, recordCoalescedCrashBreadcrumb, @@ -214,6 +216,7 @@ let starNag: StarNagService | null = null let agentAwakeService: AgentAwakeService | null = null let crashReports: CrashReportStore | null = null let unsubscribeAgentAwakeStatusChanges: (() => void) | null = null +let unsubscribeSystemResumeBroadcast: (() => void) | null = null let watcherShutdownPromise: Promise | null = null let watcherShutdownDone = false let automations: AutomationService | null = null @@ -986,6 +989,11 @@ function openMainWindow(): BrowserWindow { window.on('restore', resumeSyntheticTitleSpinnerTimer) window.on('hide', stopSyntheticTitleSpinnerTimer) window.on('minimize', stopSyntheticTitleSpinnerTimer) + // Why: visibility-gated main-process pollers (SSH port scanner) park while + // hidden and rely on this signal to resume; re-wired per window because + // macOS dock re-activation recreates the BrowserWindow. + window.on('show', notifyMainWindowBecameVisible) + window.on('restore', notifyMainWindowBecameVisible) agentHookServer.setListener( ({ paneKey, @@ -1665,6 +1673,7 @@ app.whenReady().then(async () => { // Why: browser sessions are used by desktop webviews and runtime profile // commands, so initialize them at app startup instead of a renderer IPC path. initializeBrowserSessionsForApp() + unsubscribeSystemResumeBroadcast = registerSystemResumeBroadcast() agentAwakeService = new AgentAwakeService() agentAwakeService.setEnabled(store.getSettings().keepComputerAwakeWhileAgentsRun) // Why: disk-hydrated status rows are UI continuity only. The service starts @@ -2196,6 +2205,8 @@ app.whenReady().then(async () => { app.on('before-quit', () => { isQuitting = true + unsubscribeSystemResumeBroadcast?.() + unsubscribeSystemResumeBroadcast = null unsubscribeAgentAwakeStatusChanges?.() unsubscribeAgentAwakeStatusChanges = null agentAwakeService?.dispose() diff --git a/src/main/ipc/ai-vault.test.ts b/src/main/ipc/ai-vault.test.ts index 9cc8060ee..0fae2259f 100644 --- a/src/main/ipc/ai-vault.test.ts +++ b/src/main/ipc/ai-vault.test.ts @@ -6,6 +6,7 @@ import { getRemoteHostPlatform } from '../ssh/ssh-remote-platform' const mocks = vi.hoisted(() => ({ scanAiVaultSessions: vi.fn(), scanRemoteAiVaultSessions: vi.fn(), + scanRuntimeAiVaultSessions: vi.fn(), getAiVaultWslHomeDirs: vi.fn(), getSshFilesystemProvider: vi.fn(), getActiveSshAiVaultHostInfo: vi.fn(), @@ -41,7 +42,7 @@ vi.mock('./ssh', () => ({ getActiveSshAiVaultHostInfos: mocks.getActiveSshAiVaultHostInfos })) -const { _internals } = await import('./ai-vault') +const { _internals, registerAiVaultHandlers } = await import('./ai-vault') const provider = {} as IFilesystemProvider @@ -52,6 +53,9 @@ beforeEach(() => { mocks.scanRemoteAiVaultSessions.mockResolvedValue( result([session('ssh:dev-box', 'remote-session')]) ) + mocks.scanRuntimeAiVaultSessions.mockResolvedValue( + result([session('runtime:remote-server', 'runtime-session')]) + ) mocks.getSshFilesystemProvider.mockReturnValue(provider) mocks.getActiveSshAiVaultHostInfo.mockReturnValue(hostInfo('dev-box')) mocks.getActiveSshAiVaultHostInfos.mockReturnValue([hostInfo('dev-box')]) @@ -96,6 +100,77 @@ describe('listAiVaultSessions host routing', () => { expect(result.sessions.map((entry) => entry.executionHostId)).toEqual(['ssh:dev-box', 'local']) }) + it('merges paired runtime servers for all hosts', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => [ + { + environmentId: 'remote-server', + executionHostId: 'runtime:remote-server' + } + ], + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + const result = await _internals.listAiVaultSessions({ executionHostScope: 'all' }) + + expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledWith( + 'remote-server', + { + executionHostScope: 'runtime:remote-server' + }, + expect.objectContaining({ timeoutMs: expect.any(Number) }) + ) + expect(result.sessions.map((entry) => entry.executionHostId)).toEqual([ + 'runtime:remote-server', + 'ssh:dev-box', + 'local' + ]) + }) + + it('keeps local and SSH results when runtime host discovery fails', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => { + throw new Error('runtime store is invalid') + }, + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + const result = await _internals.listAiVaultSessions({ executionHostScope: 'all' }) + + expect(mocks.scanAiVaultSessions).toHaveBeenCalledTimes(1) + expect(mocks.scanRemoteAiVaultSessions).toHaveBeenCalledTimes(1) + expect(mocks.scanRuntimeAiVaultSessions).not.toHaveBeenCalled() + expect(result.sessions.map((entry) => entry.executionHostId)).toEqual(['ssh:dev-box', 'local']) + expect(result.issues).toEqual([ + expect.objectContaining({ + agent: 'codex', + path: 'runtime environments', + message: 'runtime store is invalid' + }) + ]) + }) + + it('keeps direct runtime host scans on the normal runtime timeout', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => [], + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + await _internals.listAiVaultSessions({ + executionHostScope: 'runtime:remote-server', + force: true + }) + + expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledWith( + 'remote-server', + { + executionHostScope: 'runtime:remote-server', + force: true + }, + {} + ) + }) + it('returns a scan issue for a disconnected SSH target', async () => { mocks.getActiveSshAiVaultHostInfo.mockReturnValue(null) mocks.getSshFilesystemProvider.mockReturnValue(undefined) @@ -153,7 +228,11 @@ function session( codexHome: null, createdAt: null, updatedAt: - sessionId === 'remote-session' ? '2026-07-04T02:00:00.000Z' : '2026-07-04T01:00:00.000Z', + sessionId === 'runtime-session' + ? '2026-07-04T03:00:00.000Z' + : sessionId === 'remote-session' + ? '2026-07-04T02:00:00.000Z' + : '2026-07-04T01:00:00.000Z', modifiedAt: '2026-07-04T00:00:00.000Z', messageCount: 1, totalTokens: 0, diff --git a/src/main/ipc/ai-vault.ts b/src/main/ipc/ai-vault.ts index 4551379af..94a8de0c4 100644 --- a/src/main/ipc/ai-vault.ts +++ b/src/main/ipc/ai-vault.ts @@ -2,17 +2,14 @@ import { app, ipcMain } from 'electron' import { join } from 'node:path' import { scanRemoteAiVaultSessions } from '../ai-vault/remote-session-scanner' import { scanAiVaultSessions } from '../ai-vault/session-scanner' -import { sessionSortTime } from '../ai-vault/session-scanner-accumulator' +import { aiVaultScanIssueResult, mergeAiVaultListResults } from '../ai-vault/session-list-results' import { getWslHomeAsync, listWslDistrosAsync } from '../wsl' -import type { - AiVaultListArgs, - AiVaultListResult, - AiVaultScanIssue -} from '../../shared/ai-vault-types' +import type { AiVaultListArgs, AiVaultListResult } from '../../shared/ai-vault-types' import { LOCAL_EXECUTION_HOST_ID, normalizeExecutionHostScope, parseExecutionHostId, + toRuntimeExecutionHostId, toSshExecutionHostId, type ExecutionHostScope } from '../../shared/execution-host' @@ -23,9 +20,20 @@ import { import { getActiveSshAiVaultHostInfo, getActiveSshAiVaultHostInfos } from './ssh' const AI_VAULT_CACHE_TTL_MS = 15_000 +const AI_VAULT_ALL_HOST_RUNTIME_TIMEOUT_MS = 3_000 type AiVaultHandlerOptions = { getAdditionalCodexHomePaths?: () => readonly string[] + getActiveRuntimeAiVaultHostInfos?: () => readonly RuntimeAiVaultHostInfo[] + scanRuntimeAiVaultSessions?: ( + environmentId: string, + args: AiVaultListArgs, + options?: RuntimeAiVaultScanOptions + ) => Promise +} + +type RuntimeAiVaultScanOptions = { + timeoutMs?: number } type CachedAiVaultList = { @@ -34,6 +42,11 @@ type CachedAiVaultList = { expiresAt: number } +type RuntimeAiVaultHostInfo = { + environmentId: string + executionHostId: `runtime:${string}` +} + let cachedList: CachedAiVaultList | null = null let inflightList: Promise | null = null let inflightKey: string | null = null @@ -89,12 +102,20 @@ async function scanAiVaultSessionsByHostScope( } if (executionHostScope === 'all') { + const runtimeHosts = getActiveRuntimeAiVaultHostInfosResult() + const runtimeResults = runtimeHosts.issue ? [runtimeHosts.issue] : [] return mergeAiVaultListResults( await Promise.all([ scanLocalAiVaultSessions(args), ...getActiveSshAiVaultHostInfos().map((hostInfo) => scanSshAiVaultSessions(hostInfo.targetId, args) - ) + ), + ...runtimeHosts.hostInfos.map((hostInfo) => + scanRuntimeAiVaultSessions(hostInfo, args, { + timeoutMs: AI_VAULT_ALL_HOST_RUNTIME_TIMEOUT_MS + }) + ), + ...runtimeResults ]), args?.limit ) @@ -104,19 +125,88 @@ async function scanAiVaultSessionsByHostScope( if (parsed?.kind === 'ssh') { return scanSshAiVaultSessions(parsed.targetId, args) } - - return { - sessions: [], - issues: [ + if (parsed?.kind === 'runtime') { + return scanRuntimeAiVaultSessions( { - executionHostId: executionHostScope, - agent: 'codex', - path: executionHostScope, - message: 'Agent Session History is not available for this execution host.' - } - ], - scannedAt: new Date().toISOString() + environmentId: parsed.environmentId, + executionHostId: toRuntimeExecutionHostId(parsed.environmentId) + }, + args + ) } + + return aiVaultScanIssueResult({ + executionHostId: executionHostScope, + path: executionHostScope, + message: 'Agent Session History is not available for this execution host.' + }) +} + +function getActiveRuntimeAiVaultHostInfos(): readonly RuntimeAiVaultHostInfo[] { + return handlerOptions.getActiveRuntimeAiVaultHostInfos?.() ?? [] +} + +function getActiveRuntimeAiVaultHostInfosResult(): { + hostInfos: readonly RuntimeAiVaultHostInfo[] + issue?: AiVaultListResult +} { + try { + return { hostInfos: getActiveRuntimeAiVaultHostInfos() } + } catch (error) { + return { + hostInfos: [], + issue: runtimeHostDiscoveryIssueResult( + error instanceof Error ? error.message : 'Runtime hosts are unavailable.' + ) + } + } +} + +async function scanRuntimeAiVaultSessions( + hostInfo: RuntimeAiVaultHostInfo, + args?: AiVaultListArgs, + options: RuntimeAiVaultScanOptions = {} +): Promise { + const scanner = handlerOptions.scanRuntimeAiVaultSessions + if (!scanner) { + return runtimeScanIssueResult( + hostInfo, + 'Agent Session History is not available for this execution host.' + ) + } + const scanArgs: AiVaultListArgs = { executionHostScope: hostInfo.executionHostId } + if (args?.limit !== undefined) { + scanArgs.limit = args.limit + } + if (args?.force !== undefined) { + scanArgs.force = args.force + } + if (args?.scopePaths !== undefined) { + scanArgs.scopePaths = args.scopePaths + } + try { + return await scanner(hostInfo.environmentId, scanArgs, options) + } catch (error) { + return runtimeScanIssueResult( + hostInfo, + error instanceof Error ? error.message : 'Remote Orca server is unavailable.' + ) + } +} + +function runtimeScanIssueResult( + hostInfo: RuntimeAiVaultHostInfo, + message: string +): AiVaultListResult { + return aiVaultScanIssueResult({ + executionHostId: hostInfo.executionHostId, + path: hostInfo.environmentId, + message + }) +} + +function runtimeHostDiscoveryIssueResult(message: string): AiVaultListResult { + return aiVaultScanIssueResult({ path: 'runtime environments', message }) } async function scanLocalAiVaultSessions(args?: AiVaultListArgs): Promise { @@ -161,40 +251,11 @@ function sshScanIssueResult(args: { targetId: string message: string }): AiVaultListResult { - return { - sessions: [], - issues: [ - { - executionHostId: args.executionHostId, - agent: 'codex', - path: args.targetId, - message: args.message - } - ], - scannedAt: new Date().toISOString() - } -} - -function mergeAiVaultListResults( - results: readonly AiVaultListResult[], - rawLimit: number | undefined -): AiVaultListResult { - const limit = rawLimit && rawLimit > 0 ? Math.floor(rawLimit) : 1000 - const byId = new Map() - const issues: AiVaultScanIssue[] = [] - for (const result of results) { - for (const session of result.sessions) { - byId.set(session.id, session) - } - issues.push(...result.issues) - } - return { - sessions: [...byId.values()] - .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) - .slice(0, limit), - issues, - scannedAt: new Date().toISOString() - } + return aiVaultScanIssueResult({ + executionHostId: args.executionHostId, + path: args.targetId, + message: args.message + }) } export function registerAiVaultHandlers(options: AiVaultHandlerOptions = {}): void { diff --git a/src/main/ipc/app.test.ts b/src/main/ipc/app.test.ts index e1149d1b6..1eb9bbb17 100644 --- a/src/main/ipc/app.test.ts +++ b/src/main/ipc/app.test.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -5,7 +6,7 @@ const { appExitMock, appQuitMock, appRelaunchMock, - execFileMock, + spawnMock, destroySystemTrayMock, showOpenDialogMock, grantFloatingWorkspaceDirectoryMock @@ -14,16 +15,53 @@ const { appExitMock: vi.fn(), appQuitMock: vi.fn(), appRelaunchMock: vi.fn(), - execFileMock: vi.fn(), + spawnMock: vi.fn(), destroySystemTrayMock: vi.fn(), showOpenDialogMock: vi.fn(), grantFloatingWorkspaceDirectoryMock: vi.fn() })) vi.mock('node:child_process', () => ({ - execFile: execFileMock + spawn: spawnMock })) +// Fakes the detached `spawn` child: a stdout EventEmitter plus close/error +// events, so tests drive the async command lifecycle readCommandStdout expects. +function createFakeSpawnChild(options: { + stdout?: string + code?: number + error?: Error + pid?: number + hang?: boolean +}): EventEmitter & { pid: number; kill: ReturnType; stdout: EventEmitter } { + const { stdout, code = 0, error, pid = 4242, hang = false } = options + const child = new EventEmitter() as EventEmitter & { + pid: number + kill: ReturnType + stdout: EventEmitter & { setEncoding: ReturnType } + } + child.pid = pid + child.kill = vi.fn() + const stdoutStream = new EventEmitter() as EventEmitter & { + setEncoding: ReturnType + } + stdoutStream.setEncoding = vi.fn() + child.stdout = stdoutStream + if (!hang) { + queueMicrotask(() => { + if (error) { + child.emit('error', error) + return + } + if (stdout !== undefined) { + stdoutStream.emit('data', stdout) + } + child.emit('close', code) + }) + } + return child +} + vi.mock('electron', () => ({ app: { exit: appExitMock, @@ -63,6 +101,9 @@ import { registerAppHandlers } from './app' describe('registerAppHandlers', () => { const originalPlatform = process.platform + // Why: readCommandStdout process-group-kills on timeout; stub the real signal + // so a fake child pid can never target a live process group during tests. + let processKillSpy: ReturnType beforeEach(() => { vi.useFakeTimers() @@ -70,14 +111,16 @@ describe('registerAppHandlers', () => { appExitMock.mockReset() appQuitMock.mockReset() appRelaunchMock.mockReset() - execFileMock.mockReset() + spawnMock.mockReset() destroySystemTrayMock.mockReset() showOpenDialogMock.mockReset() grantFloatingWorkspaceDirectoryMock.mockReset() + processKillSpy = vi.spyOn(process, 'kill').mockReturnValue(true) Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) }) afterEach(() => { + processKillSpy.mockRestore() vi.useRealTimers() Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) }) @@ -177,10 +220,9 @@ describe('registerAppHandlers', () => { it('returns the selected macOS input mode before the keyboard layout fallback', async () => { Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) - execFileMock.mockImplementation((_command, _args, _options, callback) => { - callback( - null, - JSON.stringify([ + spawnMock.mockImplementation(() => + createFakeSpawnChild({ + stdout: JSON.stringify([ { 'Bundle ID': 'com.apple.PressAndHold', InputSourceKind: 'Non Keyboard Input Method' }, { 'Bundle ID': 'com.apple.inputmethod.SCIM', @@ -188,60 +230,96 @@ describe('registerAppHandlers', () => { InputSourceKind: 'Input Mode' } ]) - ) - return { kill: vi.fn() } - }) + }) + ) registerAppHandlers({} as never) await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( 'com.apple.inputmethod.SCIM.ITABC' ) - expect(execFileMock).toHaveBeenCalledTimes(1) - expect(execFileMock).toHaveBeenCalledWith( - '/usr/bin/plutil', - expect.arrayContaining(['AppleSelectedInputSources']), - expect.any(Object), - expect.any(Function) + expect(spawnMock).toHaveBeenCalledTimes(1) + // Why: macOS 15's `plutil -extract json` aborts on the input-source + // array, so the probe reads live cfprefsd via `defaults export` and dodges + // the bug with an xml1 extract before converting the clean subtree to JSON. + // Pin the exact pipeline (absolute paths, stdin markers) so dropping any + // stage silently regressing CJK detection to the fallback fails the test. + expect(spawnMock).toHaveBeenCalledWith( + '/bin/sh', + [ + '-c', + '/usr/bin/defaults export com.apple.HIToolbox - | ' + + '/usr/bin/plutil -extract AppleSelectedInputSources xml1 -o - - | ' + + '/usr/bin/plutil -convert json -o - -' + ], + expect.objectContaining({ detached: true, stdio: ['ignore', 'pipe', 'ignore'] }) ) }) it('falls back to the keyboard layout when no keyboard input mode is selected', async () => { Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) - execFileMock - .mockImplementationOnce((_command, _args, _options, callback) => { - callback( - null, - JSON.stringify([ + spawnMock + .mockImplementationOnce(() => + createFakeSpawnChild({ + stdout: JSON.stringify([ { 'Bundle ID': 'com.apple.PressAndHold', InputSourceKind: 'Non Keyboard Input Method' } ]) - ) - return { kill: vi.fn() } - }) - .mockImplementationOnce((_command, _args, _options, callback) => { - callback(null, 'com.apple.keylayout.ABC\n') - return { kill: vi.fn() } - }) + }) + ) + .mockImplementationOnce(() => createFakeSpawnChild({ stdout: 'com.apple.keylayout.ABC\n' })) registerAppHandlers({} as never) await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( 'com.apple.keylayout.ABC' ) - expect(execFileMock).toHaveBeenCalledTimes(2) - expect(execFileMock).toHaveBeenLastCalledWith( + expect(spawnMock).toHaveBeenCalledTimes(2) + expect(spawnMock).toHaveBeenLastCalledWith( '/usr/bin/defaults', ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], - expect.any(Object), - expect.any(Function) + expect.objectContaining({ detached: true }) ) }) + it('falls back to the keyboard layout when the selected input source probe exits non-zero', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + // Why: reproduces macOS 15's `plutil` abort — the pipeline exits non-zero, so + // the probe rejects on the `close` branch and the handler falls back. + spawnMock + .mockImplementationOnce(() => createFakeSpawnChild({ code: 1 })) + .mockImplementationOnce(() => createFakeSpawnChild({ stdout: 'com.apple.keylayout.ABC\n' })) + registerAppHandlers({} as never) + + await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( + 'com.apple.keylayout.ABC' + ) + expect(spawnMock).toHaveBeenCalledTimes(2) + expect(spawnMock).toHaveBeenLastCalledWith( + '/usr/bin/defaults', + ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], + expect.objectContaining({ detached: true }) + ) + }) + + it('falls back to the keyboard layout when the selected input source probe fails to spawn', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + // Why: a spawn-level failure (ENOENT/EACCES) emits 'error'; the handler must + // still fall back rather than reject out of the IPC call. + spawnMock + .mockImplementationOnce(() => createFakeSpawnChild({ error: new Error('spawn ENOENT') })) + .mockImplementationOnce(() => createFakeSpawnChild({ stdout: 'com.apple.keylayout.ABC\n' })) + registerAppHandlers({} as never) + + await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( + 'com.apple.keylayout.ABC' + ) + expect(spawnMock).toHaveBeenCalledTimes(2) + }) + it('falls back when macOS keyboard input source probes never report completion', async () => { Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) - const killMock = vi.fn() - execFileMock.mockImplementation(() => ({ kill: killMock })) + spawnMock.mockImplementation(() => createFakeSpawnChild({ pid: 4242, hang: true })) registerAppHandlers({} as never) const handler = handlers.get('app:getKeyboardInputSourceId') @@ -256,7 +334,10 @@ describe('registerAppHandlers', () => { expect(settled).toBe(true) await expect(resultPromise).resolves.toBeNull() - expect(killMock).toHaveBeenCalledTimes(2) + // Why: both wedged probes get a process-group SIGKILL (negative pid) so the + // shell and any orphaned `defaults`/`plutil` stages are reaped on timeout. + expect(processKillSpy).toHaveBeenCalledTimes(2) + expect(processKillSpy).toHaveBeenCalledWith(-4242, 'SIGKILL') }) it('picks an existing floating workspace directory without enabling native directory creation', async () => { diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index 276c3ba5f..2dc3c81f9 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -1,6 +1,5 @@ -import { execFile } from 'node:child_process' +import { spawn } from 'node:child_process' import { existsSync } from 'node:fs' -import { homedir } from 'node:os' import path from 'node:path' import { pathToFileURL } from 'node:url' import { app, BrowserWindow, dialog, ipcMain, type IpcMainInvokeEvent } from 'electron' @@ -24,12 +23,15 @@ import { isMarkdownDocumentName, markdownDocumentFromFilePath } from './markdown const KEYBOARD_INPUT_SOURCE_TIMEOUT_MS = 500 const MAC_HITOOLBOX_DOMAIN = 'com.apple.HIToolbox' -const MAC_HITOOLBOX_PREFERENCES_PATH = path.join( - homedir(), - 'Library', - 'Preferences', - `${MAC_HITOOLBOX_DOMAIN}.plist` -) +// Why: macOS 15's `plutil -extract json` aborts on the (pure-string) +// input-source array and the on-disk plist lags cfprefsd; read live prefs via +// `defaults export`, extract as xml1 (dodges the json bug), then convert to JSON. +// Absolute paths so a GUI-launched app's minimal PATH can't shadow the tools. +const MAC_SELECTED_INPUT_SOURCES_JSON_COMMAND = [ + `/usr/bin/defaults export ${MAC_HITOOLBOX_DOMAIN} -`, + '/usr/bin/plutil -extract AppleSelectedInputSources xml1 -o - -', + '/usr/bin/plutil -convert json -o - -' +].join(' | ') type RegisterAppHandlersOptions = { onBeforeRelaunch?: () => void | Promise @@ -118,13 +120,32 @@ function readCommandStdout( ): Promise { return new Promise((resolve, reject) => { let settled = false - let child: ReturnType | undefined + let child: ReturnType | undefined + + // Why: the probe runs a `/bin/sh -c` pipeline, so signaling only the shell + // orphans wedged `defaults`/`plutil` stages on a stuck cfprefsd. Spawning + // detached makes the child a process-group leader, so one negative-pid + // SIGKILL reaps the shell and every stage; child.kill() covers the fallback. + const killTree = (): void => { + if (!child?.pid) { + return + } + try { + process.kill(-child.pid, 'SIGKILL') + } catch { + child.kill() + } + } + + // Why: short timeout so a wedged macOS preference probe (corporate-managed + // config, sandbox policy, ...) never holds the handle indefinitely. This + // manual timer is the only timeout guard, so it owns the process-group kill. const timer = setTimeout(() => { if (settled) { return } settled = true - child?.kill() + killTree() reject(new Error(timeoutMessage)) }, KEYBOARD_INPUT_SOURCE_TIMEOUT_MS) @@ -137,24 +158,32 @@ function readCommandStdout( callback() } - // Why: execFile's timeout only signals `defaults`; if the callback - // never arrives, window-focus keyboard probes would remain pending. try { - child = execFile( - command, - args, - // Why: short timeout so a wedged macOS preference probe (corporate-managed - // config, sandbox policy, ...) never holds the handle indefinitely. - // Fall through to the fingerprint on timeout. - { encoding: 'utf8', timeout: KEYBOARD_INPUT_SOURCE_TIMEOUT_MS }, - (error, stdout) => { - if (error) { - settle(() => reject(error)) - return - } - settle(() => resolve(String(stdout ?? ''))) - } - ) + child = spawn(command, args, { detached: true, stdio: ['ignore', 'pipe', 'ignore'] }) + let stdout = '' + child.stdout?.setEncoding('utf8') + child.stdout?.on('data', (chunk: string) => { + stdout += chunk + }) + const failWith = (error: Error): void => { + killTree() + settle(() => reject(error)) + } + // Why: an unhandled Readable 'error' would crash the main process; treat a + // stdout read failure the same as a child spawn error. + child.stdout?.on('error', failWith) + child.on('error', failWith) + child.on('close', (code, signal) => { + settle(() => + code === 0 + ? resolve(stdout) + : reject( + new Error( + `${command} exited with ${signal ? `signal ${signal}` : `code ${code ?? 'unknown'}`}` + ) + ) + ) + }) } catch (error) { settle(() => reject(error)) } @@ -196,8 +225,8 @@ function readSelectedInputSourceIdFromJson(stdout: string): string | null { async function readSelectedKeyboardInputSourceId(): Promise { try { const stdout = await readCommandStdout( - '/usr/bin/plutil', - ['-extract', 'AppleSelectedInputSources', 'json', '-o', '-', MAC_HITOOLBOX_PREFERENCES_PATH], + '/bin/sh', + ['-c', MAC_SELECTED_INPUT_SOURCES_JSON_COMMAND], 'Selected keyboard input source probe timed out' ) return readSelectedInputSourceIdFromJson(stdout) diff --git a/src/main/ipc/filesystem-watcher.ts b/src/main/ipc/filesystem-watcher.ts index 51cbfbaef..56ab2aa29 100644 --- a/src/main/ipc/filesystem-watcher.ts +++ b/src/main/ipc/filesystem-watcher.ts @@ -13,6 +13,7 @@ import { createWslWatcher } from './filesystem-watcher-wsl' import type { WatchedRoot } from './filesystem-watcher-wsl' import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { MAX_BATCHED_WATCHER_EVENTS, queueWatcherEvents } from './filesystem-watcher-event-batch' +import { disposeWatcherProcess, subscribeViaWatcherProcess } from './parcel-watcher-process' // Why: high-churn directories are suppressed at the native watcher level so // events never leave the OS/daemon. This list is separate from the File // Explorer display filter (which only hides rows). Directories like `dist` @@ -278,10 +279,6 @@ function scheduleBatchFlush(rootKey: string, root: WatchedRoot): void { // ── Watcher creation ───────────────────────────────────────────────── async function createWatcher(rootKey: string, rootPath: string): Promise { - // Why: @parcel/watcher is a native module that may not load in all - // environments. Dynamic import keeps the require() lazy. - const watcher = await import('@parcel/watcher') - const root: WatchedRoot = { subscription: null!, listeners: new Map(), @@ -303,7 +300,11 @@ async function createWatcher(rootKey: string, rootPath: string): Promise { if (err) { @@ -334,7 +335,13 @@ async function createWatcher(rootKey: string, rootPath: string): Promise { + // The watcher process crashed and this root was resubscribed; events + // during the gap are lost, so hand the renderer an overflow refresh. + root.batch.overflowed = true + scheduleBatchFlush(rootKey, root) + } ) // Why: if the error callback already fired and cleaned up watchedRoots @@ -929,6 +936,10 @@ export async function closeAllWatchers(): Promise { } watchedRoots.clear() await Promise.allSettled(Array.from(pendingLocalUnsubscribes)) + // Why: with every local subscription released, drop the forked watcher + // process outright — process death frees any remaining native handles + // without running watcher.node's crash-prone async teardown in this process. + disposeWatcherProcess() // Why: remote watchers are tracked separately from local @parcel/watcher // subscriptions. Without cleaning them up here, their unwatch callbacks diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index 25894ffb7..072f8239d 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -2316,4 +2316,39 @@ describe('registerFilesystemHandlers', () => { excludePaths: ['/home/user/repo/worktrees/feature'] }) }) + + // Why #7721: without a cancel path, every workspace switch left the previous + // workspace's full-tree SSH scan running, stacking scans on the relay until + // interactive fs.readDir/fs.stat starved past their 30s timeout. + it('fs:cancelListFiles aborts an in-flight SSH listing by request token (#7721)', async () => { + let capturedSignal: AbortSignal | undefined + const listFilesMock = vi.fn( + (_rootPath: string, options: { signal?: AbortSignal }) => + new Promise((_resolve, reject) => { + capturedSignal = options.signal + options.signal?.addEventListener('abort', () => reject(new Error('listing cancelled')), { + once: true + }) + }) + ) + getSshFilesystemProviderMock.mockReturnValue({ listFiles: listFilesMock }) + + registerFilesystemHandlers(store as never) + + const pending = handlers.get('fs:listFiles')!(null, { + rootPath: '/home/user/repo', + connectionId: 'conn-1', + requestToken: 'token-1' + }) as Promise + + expect(capturedSignal?.aborted).toBe(false) + await handlers.get('fs:cancelListFiles')!(null, { requestToken: 'token-1' }) + expect(capturedSignal?.aborted).toBe(true) + await expect(pending).rejects.toThrow('listing cancelled') + + // Unknown or already-settled tokens are a no-op, not an error. + expect(() => + handlers.get('fs:cancelListFiles')!(null, { requestToken: 'unknown' }) + ).not.toThrow() + }) }) diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index 85c0ce56e..7e7006a37 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -1026,30 +1026,58 @@ export function registerFilesystemHandlers( ) // ─── List all files (for quick-open) ───────────────────── + // Why #7721: keyed by renderer-generated token so a workspace switch can + // abort the previous workspace's full-tree scan (SSH relays otherwise stack + // scans that starve interactive fs.readDir/fs.stat past their 30s timeout). + const listFilesCancellations = new Map() ipcMain.handle( 'fs:listFiles', async ( _event, - args: { rootPath: string; connectionId?: string; excludePaths?: string[] } - ): Promise => { - if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - // Why: when the SSH connection is not yet established (cold start) or - // temporarily disconnected, return [] so quick-open shows "No matching - // files" instead of an error banner. The file list will repopulate when - // the user re-opens quick-open after the connection is restored. - if (!provider) { - return [] - } - // Why: forward excludePaths through to the remote provider. - // Dropping it here would silently double-scan nested linked worktrees - // over SSH and contribute to timeout-induced partial results. - return provider.listFiles(args.rootPath, { excludePaths: args.excludePaths }) + args: { + rootPath: string + connectionId?: string + excludePaths?: string[] + requestToken?: string + } + ): Promise => { + const controller = args.requestToken ? new AbortController() : null + if (controller && args.requestToken) { + listFilesCancellations.set(args.requestToken, controller) + } + try { + if (args.connectionId) { + const provider = getSshFilesystemProvider(args.connectionId) + // Why: when the SSH connection is not yet established (cold start) or + // temporarily disconnected, return [] so quick-open shows "No matching + // files" instead of an error banner. The file list will repopulate when + // the user re-opens quick-open after the connection is restored. + if (!provider) { + return [] + } + // Why: forward excludePaths through to the remote provider. + // Dropping it here would silently double-scan nested linked worktrees + // over SSH and contribute to timeout-induced partial results. + return await provider.listFiles(args.rootPath, { + excludePaths: args.excludePaths, + signal: controller?.signal + }) + } + return await listQuickOpenFiles(args.rootPath, store, args.excludePaths) + } finally { + if (args.requestToken) { + listFilesCancellations.delete(args.requestToken) + } } - return listQuickOpenFiles(args.rootPath, store, args.excludePaths) } ) + ipcMain.handle('fs:cancelListFiles', (_event, args: { requestToken: string }): void => { + // Why: best-effort — the entry is gone once the listing settles, and + // local scans are fast enough to simply let them finish. + listFilesCancellations.get(args.requestToken)?.abort() + }) + // ─── Git operations ───────────────────────────────────── ipcMain.handle( 'git:status', diff --git a/src/main/ipc/parcel-watcher-process-entry.ts b/src/main/ipc/parcel-watcher-process-entry.ts new file mode 100644 index 000000000..03676721d --- /dev/null +++ b/src/main/ipc/parcel-watcher-process-entry.ts @@ -0,0 +1,194 @@ +// Forked (ELECTRON_RUN_AS_NODE) child that hosts all local @parcel/watcher +// subscriptions. Why: watcher.node has native teardown races that fail-fast +// the hosting process (issue #7547, 0xc0000409 on Windows; same class as +// #5377/#6635). Running the native module here turns a watcher fault into a +// contained child crash the host can recover from, instead of killing the app +// and every agent session in it. +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type * as ParcelWatcher from '@parcel/watcher' + +export type WatcherProcessEvent = { + type: 'create' | 'update' | 'delete' + path: string +} + +export type WatcherProcessSubscribeOptions = { + ignore?: string[] + backend?: string +} + +export type HostToWatcherMessage = + | { op: 'subscribe'; id: number; dir: string; opts: WatcherProcessSubscribeOptions } + | { op: 'unsubscribe'; id: number } + +export type WatcherToHostMessage = + | { op: 'subscribed'; id: number } + | { op: 'subscribe-failed'; id: number; message: string } + | { op: 'events'; id: number; events: WatcherProcessEvent[] } + | { op: 'watch-error'; id: number; message: string } + | { op: 'unsubscribed'; id: number } + +function errorMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err) +} + +// Canary self-check. Why: @parcel/watcher can wedge silently — a lock-order +// inversion between Debounce::notify (debounce mutex → watcher mutex) and +// Watcher teardown (watcher mutex → debounce mutex in ~Watcher) deadlocks the +// single process-wide debounce thread, after which every subscription still +// acks but no events are ever delivered. The canary watches a private temp +// dir and touches a file in it; consecutive missed deliveries mean event +// delivery is dead, so exit and let the host respawn a fresh process. +const CANARY_INTERVAL_MS = 10_000 +const CANARY_EVENT_TIMEOUT_MS = 5_000 +const CANARY_MAX_MISSES = 2 + +async function startCanary(hasLiveSubscriptions: () => boolean): Promise { + let canaryDir: string + let lastEventAt = 0 + try { + canaryDir = mkdtempSync(join(tmpdir(), 'orca-watcher-canary-')) + const watcher = await import('@parcel/watcher') + // Why: pin the Windows backend like the main subscriptions do, so the + // canary never probes for Watchman. + const opts = ( + process.platform === 'win32' ? { backend: 'windows' } : {} + ) as ParcelWatcher.Options + await watcher.subscribe( + canaryDir, + (err) => { + if (!err) { + lastEventAt = Date.now() + } + }, + opts + ) + } catch (err) { + process.stderr.write(`[parcel-watcher-process] canary unavailable: ${errorMessage(err)}\n`) + return + } + process.on('exit', () => { + try { + rmSync(canaryDir, { recursive: true, force: true }) + } catch { + // Temp dir cleanup is best-effort. + } + }) + + let misses = 0 + setInterval(() => { + // An idle watcher process can't wedge anything visible; only probe while + // roots are subscribed so an idle child doesn't restart pointlessly. + if (!hasLiveSubscriptions()) { + misses = 0 + return + } + const probedAt = Date.now() + try { + writeFileSync(join(canaryDir, 'canary.txt'), String(probedAt)) + } catch { + return + } + setTimeout(() => { + if (lastEventAt >= probedAt) { + misses = 0 + return + } + misses++ + if (misses >= CANARY_MAX_MISSES) { + process.stderr.write( + '[parcel-watcher-process] event delivery wedged (canary starved); restarting watcher process\n' + ) + process.exit(2) + } + }, CANARY_EVENT_TIMEOUT_MS) + }, CANARY_INTERVAL_MS) +} + +function main(): void { + const send = (message: WatcherToHostMessage): void => { + try { + process.send?.(message) + } catch { + // Host is gone; the disconnect handler below exits this process. + } + } + + // Subscribe promises are kept (not just subscriptions) so an unsubscribe + // that races a still-crawling subscribe awaits it instead of leaking the + // native handle — on Windows a leaked handle keeps the worktree dir locked. + const subscriptions = new Map>() + + const handleSubscribe = async ( + id: number, + dir: string, + opts: WatcherProcessSubscribeOptions + ): Promise => { + try { + const watcher = await import('@parcel/watcher') + const subscription = await watcher.subscribe( + dir, + (err, events) => { + if (err) { + send({ op: 'watch-error', id, message: errorMessage(err) }) + return + } + if (events.length > 0) { + send({ + op: 'events', + id, + events: events.map((event) => ({ type: event.type, path: event.path })) + }) + } + }, + opts as ParcelWatcher.Options + ) + send({ op: 'subscribed', id }) + return subscription + } catch (err) { + subscriptions.delete(id) + send({ op: 'subscribe-failed', id, message: errorMessage(err) }) + return null + } + } + + const handleUnsubscribe = async (id: number): Promise => { + const pending = subscriptions.get(id) + subscriptions.delete(id) + try { + const subscription = await pending + await subscription?.unsubscribe() + } catch (err) { + process.stderr.write( + `[parcel-watcher-process] unsubscribe ${id} failed: ${errorMessage(err)}\n` + ) + } + send({ op: 'unsubscribed', id }) + } + + process.on('message', (message: HostToWatcherMessage) => { + if (!message || typeof message !== 'object') { + return + } + if (message.op === 'subscribe') { + subscriptions.set(message.id, handleSubscribe(message.id, message.dir, message.opts)) + return + } + if (message.op === 'unsubscribe') { + void handleUnsubscribe(message.id) + } + }) + + void startCanary(() => subscriptions.size > 0) + + // Why: if the host dies (or kills us during shutdown), exit immediately — + // process death releases every native watcher handle without running the + // crash-prone napi teardown at all. + process.on('disconnect', () => { + process.exit(0) + }) +} + +main() diff --git a/src/main/ipc/parcel-watcher-process.test.ts b/src/main/ipc/parcel-watcher-process.test.ts new file mode 100644 index 000000000..cb5caf2ea --- /dev/null +++ b/src/main/ipc/parcel-watcher-process.test.ts @@ -0,0 +1,204 @@ +// Regression tests for issue #7547: local @parcel/watcher subscriptions run +// in a forked watcher process, and a native watcher crash must be contained — +// respawn, resubscribe, notify interruption — instead of killing the app. +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { forkMock, existsSyncMock, parcelSubscribeMock } = vi.hoisted(() => ({ + forkMock: vi.fn(), + existsSyncMock: vi.fn(), + parcelSubscribeMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ fork: forkMock })) +vi.mock('node:fs', () => ({ existsSync: existsSyncMock })) +vi.mock('@parcel/watcher', () => ({ subscribe: parcelSubscribeMock })) + +import { + disposeWatcherProcess, + resetWatcherProcessForTest, + subscribeViaWatcherProcess +} from './parcel-watcher-process' + +type SentMessage = { op: string; id: number; dir?: string } + +class FakeChild extends EventEmitter { + connected = true + sent: SentMessage[] = [] + stderr = new EventEmitter() + kill = vi.fn(() => { + this.connected = false + }) + send = vi.fn((message: SentMessage) => { + this.sent.push(message) + return true + }) +} + +function currentChild(): FakeChild { + const result = forkMock.mock.results.at(-1) + if (!result) { + throw new Error('fork was not called') + } + return result.value as FakeChild +} + +function ackSubscribe(child: FakeChild, index = -1): number { + const message = child.sent.filter((m) => m.op === 'subscribe').at(index) + if (!message) { + throw new Error('no subscribe message sent') + } + child.emit('message', { op: 'subscribed', id: message.id }) + return message.id +} + +describe('subscribeViaWatcherProcess', () => { + beforeEach(() => { + resetWatcherProcessForTest() + // Why: the client deliberately runs in-process under vitest; these tests + // exercise the forked-process mode, so hide the vitest marker. + vi.stubEnv('VITEST', '') + existsSyncMock.mockReturnValue(true) + forkMock.mockImplementation(() => new FakeChild()) + }) + + afterEach(() => { + disposeWatcherProcess() + vi.unstubAllEnvs() + vi.clearAllMocks() + }) + + it('subscribes through the watcher process and forwards events', async () => { + const callback = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, { ignore: ['**/.git'] }) + const child = currentChild() + expect(child.sent[0]).toMatchObject({ op: 'subscribe', dir: '/repo' }) + const id = ackSubscribe(child) + await promise + + const events = [{ type: 'update', path: '/repo/a.txt' }] + child.emit('message', { op: 'events', id, events }) + expect(callback).toHaveBeenCalledWith(null, events) + }) + + it('forwards watcher errors to the callback', async () => { + const callback = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, {}) + const child = currentChild() + const id = ackSubscribe(child) + await promise + + child.emit('message', { op: 'watch-error', id, message: 'boom' }) + expect(callback).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' }), []) + }) + + it('rejects the subscribe when the watcher process reports failure', async () => { + const promise = subscribeViaWatcherProcess('/gone', vi.fn(), {}) + const child = currentChild() + const id = child.sent[0].id + child.emit('message', { op: 'subscribe-failed', id, message: 'Error opening directory' }) + await expect(promise).rejects.toThrow('Error opening directory') + }) + + it('resolves unsubscribe on the child ack', async () => { + const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + const child = currentChild() + const id = ackSubscribe(child) + const subscription = await promise + + const unsubPromise = subscription.unsubscribe() + expect(child.sent.at(-1)).toEqual({ op: 'unsubscribe', id }) + child.emit('message', { op: 'unsubscribed', id }) + await expect(unsubPromise).resolves.toBeUndefined() + }) + + it('resolves a pending unsubscribe when the child dies', async () => { + const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + const child = currentChild() + ackSubscribe(child) + const subscription = await promise + + const unsubPromise = subscription.unsubscribe() + child.connected = false + child.emit('exit', 3221226505, null) + await expect(unsubPromise).resolves.toBeUndefined() + }) + + it('respawns after a crash, resubscribes, and reports the interruption', async () => { + const callback = vi.fn() + const onInterruption = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, {}, onInterruption) + const first = currentChild() + const id = ackSubscribe(first) + await promise + + // Simulate the 0xc0000409 fail-fast: the watcher process dies. + first.connected = false + first.emit('exit', 3221226505, null) + + const second = currentChild() + expect(second).not.toBe(first) + expect(second.sent[0]).toMatchObject({ op: 'subscribe', id, dir: '/repo' }) + expect(onInterruption).not.toHaveBeenCalled() + + second.emit('message', { op: 'subscribed', id }) + expect(onInterruption).toHaveBeenCalledTimes(1) + + const events = [{ type: 'create', path: '/repo/b.txt' }] + second.emit('message', { op: 'events', id, events }) + expect(callback).toHaveBeenCalledWith(null, events) + }) + + it('completes an in-flight subscribe across a crash-respawn', async () => { + const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + const first = currentChild() + expect(first.sent[0].op).toBe('subscribe') + + first.connected = false + first.emit('exit', 3221226505, null) + + const second = currentChild() + ackSubscribe(second) + await expect(promise).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) + }) + + it('disables watching after repeated crashes instead of fork-bombing', async () => { + const callback = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, {}) + ackSubscribe(currentChild()) + await promise + + for (let crash = 0; crash < 2; crash++) { + const child = currentChild() + child.connected = false + child.emit('exit', 3221226505, null) + ackSubscribe(currentChild()) + } + expect(forkMock).toHaveBeenCalledTimes(3) + + const last = currentChild() + last.connected = false + last.emit('exit', 3221226505, null) + + expect(forkMock).toHaveBeenCalledTimes(3) + expect(callback).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('crashed repeatedly') }), + [] + ) + }) + + it('uses the in-process watcher under vitest', async () => { + vi.stubEnv('VITEST', 'true') + const unsubscribe = vi.fn().mockResolvedValue(undefined) + parcelSubscribeMock.mockResolvedValue({ unsubscribe }) + const callback = vi.fn() + + const subscription = await subscribeViaWatcherProcess('/repo', callback, { + ignore: ['**/.git'] + }) + expect(forkMock).not.toHaveBeenCalled() + expect(parcelSubscribeMock).toHaveBeenCalledWith('/repo', callback, { ignore: ['**/.git'] }) + await subscription.unsubscribe() + expect(unsubscribe).toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/parcel-watcher-process.ts b/src/main/ipc/parcel-watcher-process.ts new file mode 100644 index 000000000..25e52794a --- /dev/null +++ b/src/main/ipc/parcel-watcher-process.ts @@ -0,0 +1,320 @@ +// Host side of the out-of-process @parcel/watcher (see +// parcel-watcher-process-entry.ts). Why: native watcher teardown races +// fail-fast the hosting process (issue #7547), so local subscriptions live in +// a disposable forked child; when it crashes the host respawns it and +// resubscribes every live root, and callers are told via onInterruption so +// they can refresh state that changed during the gap. +import { fork, type ChildProcess } from 'node:child_process' +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import type * as ParcelWatcher from '@parcel/watcher' +import type { + HostToWatcherMessage, + WatcherProcessEvent, + WatcherProcessSubscribeOptions, + WatcherToHostMessage +} from './parcel-watcher-process-entry' + +export type { WatcherProcessEvent, WatcherProcessSubscribeOptions } + +export type WatcherProcessCallback = (err: Error | null, events: WatcherProcessEvent[]) => void +export type WatcherProcessSubscription = { unsubscribe(): Promise } + +// Why: a crash loop (e.g. a root that faults the native watcher on every +// resubscribe) must degrade to "file watching disabled" rather than fork-bomb. +const CRASH_WINDOW_MS = 30_000 +const MAX_CRASHES_PER_WINDOW = 3 + +type SubscriptionRecord = { + id: number + dir: string + opts: WatcherProcessSubscribeOptions + callback: WatcherProcessCallback + onInterruption?: () => void + pendingSubscribe?: { resolve: () => void; reject: (err: Error) => void } +} + +let child: ChildProcess | null = null +let nextSubscriptionId = 1 +let crashTimes: number[] = [] +let shutdownRequested = false +let loggedInProcessFallback = false +const records = new Map() +const pendingUnsubscribes = new Map void>() + +function loadElectronApp(): { getAppPath(): string; isPackaged: boolean } | null { + try { + return require('electron').app ?? null + } catch { + return null + } +} + +function getWatcherProcessEntryPath(): string { + const app = loadElectronApp() + const appPath = app?.getAppPath() ?? process.cwd() + // Why: ELECTRON_RUN_AS_NODE bypasses Electron's asar integration, so the + // packaged entry must be forked from app.asar.unpacked. + const basePath = app?.isPackaged ? appPath.replace('app.asar', 'app.asar.unpacked') : appPath + return join(basePath, 'out', 'main', 'parcel-watcher-process-entry.js') +} + +function shouldRunInProcess(entryPath: string): boolean { + // Why: vitest suites mock '@parcel/watcher' at the module level; a forked + // child would bypass those mocks (and could execute a stale build output), + // so tests keep the historical in-process path. + if (process.env.VITEST) { + return true + } + if (existsSync(entryPath)) { + return false + } + if (!loggedInProcessFallback) { + loggedInProcessFallback = true + console.warn( + `[parcel-watcher-process] entry not found at ${entryPath}; using in-process watcher (no crash isolation)` + ) + } + return true +} + +async function subscribeInProcess( + dir: string, + callback: WatcherProcessCallback, + opts: WatcherProcessSubscribeOptions +): Promise { + const watcher = await import('@parcel/watcher') + const subscription = await watcher.subscribe( + dir, + callback as ParcelWatcher.SubscribeCallback, + opts as ParcelWatcher.Options + ) + return { unsubscribe: () => subscription.unsubscribe() } +} + +function inCrashCooldown(): boolean { + const now = Date.now() + crashTimes = crashTimes.filter((time) => now - time < CRASH_WINDOW_MS) + return crashTimes.length >= MAX_CRASHES_PER_WINDOW +} + +function sendToChild(proc: ChildProcess, message: HostToWatcherMessage): void { + try { + proc.send(message) + } catch { + // Channel already closed — the child's exit handler recovers. + } +} + +function ensureWatcherProcess(): ChildProcess | null { + if (shutdownRequested) { + return null + } + if (child?.connected) { + return child + } + if (inCrashCooldown()) { + return null + } + let proc: ChildProcess + try { + proc = fork(getWatcherProcessEntryPath(), [], { + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, + ...(process.platform === 'win32' ? { windowsHide: true } : {}) + }) + } catch (err) { + console.error('[parcel-watcher-process] failed to fork watcher process:', err) + return null + } + proc.stderr?.on('data', (chunk: Buffer) => { + console.error('[parcel-watcher-process]', String(chunk).trimEnd()) + }) + proc.on('message', (message) => { + if (child === proc) { + handleChildMessage(message as WatcherToHostMessage) + } + }) + proc.on('error', () => handleChildGone(proc)) + proc.on('exit', (code, signal) => { + if (child === proc && (code !== 0 || signal)) { + console.error( + `[parcel-watcher-process] watcher process exited (code=${code}, signal=${signal})` + ) + } + handleChildGone(proc) + }) + child = proc + return proc +} + +function handleChildMessage(message: WatcherToHostMessage): void { + if (!message || typeof message !== 'object') { + return + } + if (message.op === 'unsubscribed') { + const resolve = pendingUnsubscribes.get(message.id) + pendingUnsubscribes.delete(message.id) + resolve?.() + return + } + const record = records.get(message.id) + if (!record) { + return + } + if (message.op === 'subscribed') { + const pending = record.pendingSubscribe + record.pendingSubscribe = undefined + if (pending) { + pending.resolve() + } else { + // Reached after a crash-respawn resubscribe: events emitted while the + // watcher process was down are lost, so let the caller refresh. + record.onInterruption?.() + } + return + } + if (message.op === 'subscribe-failed') { + records.delete(message.id) + const pending = record.pendingSubscribe + record.pendingSubscribe = undefined + if (pending) { + pending.reject(new Error(message.message)) + } else { + record.callback(new Error(message.message), []) + } + return + } + if (message.op === 'events') { + record.callback(null, message.events) + return + } + if (message.op === 'watch-error') { + record.callback(new Error(message.message), []) + } +} + +function failAllSubscriptions(err: Error): void { + for (const record of records.values()) { + const pending = record.pendingSubscribe + record.pendingSubscribe = undefined + if (pending) { + pending.reject(err) + } else { + record.callback(err, []) + } + } + records.clear() +} + +function handleChildGone(proc: ChildProcess): void { + if (child !== proc) { + return + } + child = null + // Why: process death released every native handle, so a pending unsubscribe + // is complete by definition — resolve rather than hang worktree deletion. + for (const resolve of pendingUnsubscribes.values()) { + resolve() + } + pendingUnsubscribes.clear() + if (shutdownRequested || records.size === 0) { + return + } + crashTimes.push(Date.now()) + const replacement = ensureWatcherProcess() + if (!replacement) { + console.error( + '[parcel-watcher-process] watcher process crashed repeatedly; disabling file watching' + ) + failAllSubscriptions(new Error('file watcher process crashed repeatedly')) + return + } + console.error( + `[parcel-watcher-process] watcher process crashed; resubscribing ${records.size} root(s)` + ) + for (const record of records.values()) { + sendToChild(replacement, { + op: 'subscribe', + id: record.id, + dir: record.dir, + opts: record.opts + }) + } +} + +function makeSubscription(record: SubscriptionRecord): WatcherProcessSubscription { + return { + unsubscribe: (): Promise => { + if (!records.delete(record.id)) { + return Promise.resolve() + } + const proc = child + if (!proc?.connected) { + return Promise.resolve() + } + return new Promise((resolve) => { + pendingUnsubscribes.set(record.id, resolve) + sendToChild(proc, { op: 'unsubscribe', id: record.id }) + }) + } + } +} + +/** Subscribe to a directory tree via the isolated watcher process. Falls back + * to an in-process @parcel/watcher subscription when the forked entry is not + * available (tests, unbuilt trees). `onInterruption` fires after the watcher + * process crashed and this subscription was transparently re-established — + * events in the gap were lost, so callers should refresh. */ +export function subscribeViaWatcherProcess( + dir: string, + callback: WatcherProcessCallback, + opts: WatcherProcessSubscribeOptions, + onInterruption?: () => void +): Promise { + if (shouldRunInProcess(getWatcherProcessEntryPath())) { + return subscribeInProcess(dir, callback, opts) + } + const record: SubscriptionRecord = { + id: nextSubscriptionId++, + dir, + opts, + callback, + onInterruption + } + return new Promise((resolve, reject) => { + const proc = ensureWatcherProcess() + if (!proc) { + reject(new Error('file watcher process unavailable')) + return + } + records.set(record.id, record) + record.pendingSubscribe = { + resolve: () => resolve(makeSubscription(record)), + reject + } + sendToChild(proc, { op: 'subscribe', id: record.id, dir, opts }) + }) +} + +/** Kill the watcher process at app shutdown. Process death releases native + * handles without running watcher.node's crash-prone async teardown. */ +export function disposeWatcherProcess(): void { + shutdownRequested = true + const proc = child + child = null + for (const resolve of pendingUnsubscribes.values()) { + resolve() + } + pendingUnsubscribes.clear() + records.clear() + proc?.kill() +} + +export function resetWatcherProcessForTest(): void { + disposeWatcherProcess() + shutdownRequested = false + crashTimes = [] + loggedInProcessFallback = false + nextSubscriptionId = 1 +} diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index cffdf6cb6..78dbd0c60 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -19,11 +19,13 @@ const expectedOmpStatusExtension = posix.join( 'extensions', 'orca-agent-status.ts' ) -const expectedAttributionShimDir = join( - '/tmp/orca-user-data', - 'orca-terminal-attribution', - isWindowsHost ? 'win32' : 'posix' -) +function expectedAttributionShimDir(): string { + return join( + '/tmp/orca-user-data', + 'orca-terminal-attribution', + process.platform === 'win32' ? 'win32' : 'posix' + ) +} const { handleMock, @@ -1219,7 +1221,7 @@ describe('registerPtyHandlers', () => { expect(env.ORCA_GIT_COMMIT_TRAILER).toBe('Co-authored-by: Orca ') expect(env.ORCA_GH_PR_FOOTER).toBe('Made with [Orca](https://github.com/stablyai/orca) 🐋') expect(env.ORCA_GH_ISSUE_FOOTER).toBe('Made with [Orca](https://github.com/stablyai/orca) 🐋') - expect(env.PATH).toContain(expectedAttributionShimDir) + expect(env.PATH).toContain(expectedAttributionShimDir()) }) it('skips git/gh attribution shims when attribution is disabled', async () => { @@ -1231,7 +1233,7 @@ describe('registerPtyHandlers', () => { expect(env.ORCA_GIT_COMMIT_TRAILER).toBeUndefined() expect(env.ORCA_GH_PR_FOOTER).toBeUndefined() expect(env.ORCA_GH_ISSUE_FOOTER).toBeUndefined() - expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir) + expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir()) }) it('prepends git/gh attribution shims for daemon-backed local PTYs', async () => { @@ -1260,7 +1262,7 @@ describe('registerPtyHandlers', () => { const env = daemonSpawn.mock.calls.at(-1)![0].env expect(env.ORCA_ENABLE_GIT_ATTRIBUTION).toBe('1') - expect(env.PATH).toContain(expectedAttributionShimDir) + expect(env.PATH).toContain(expectedAttributionShimDir()) }) it('overrides ambient CODEX_HOME with the Orca-managed home for system default', async () => { @@ -1677,6 +1679,47 @@ describe('registerPtyHandlers', () => { expect(spawnOptions.env.ORCA_AGENT_HOOK_TOKEN).toBe('agent-token') }) + it('threads the validated pane identity into registerPty for a runtime-created daemon PTY (#7587)', async () => { + type RuntimeSpawnController = { + spawn(args: { + cols: number + rows: number + worktreeId?: string + tabId?: string + leafId?: string + env?: Record + }): Promise<{ id: string }> + } + const leafId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + setupDaemonAdapter() + const runtime = { + setPtyController: vi.fn(), + registerPty: vi.fn(), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + const controller = runtime.setPtyController.mock.calls[0]?.[0] as RuntimeSpawnController + + await controller.spawn({ + cols: 80, + rows: 24, + worktreeId: 'wt-runtime', + tabId: 'tab-1', + leafId + }) + + // Why: runtime-created spawns (e.g. the mobile-create materialize path) + // must thread the same {tabId, leafId} so the catch-path rescue can find + // and keep their live PTY (#7587). + expect(runtime.registerPty).toHaveBeenCalledWith(expect.any(String), 'wt-runtime', null, { + tabId: 'tab-1', + leafId + }) + }) + it('uses the owning project WSL runtime for runtime-created daemon PTYs', async () => { await withWin32Platform(async () => { _setWslCachesForTests({ available: true, distros: ['Ubuntu'] }) @@ -1827,7 +1870,7 @@ describe('registerPtyHandlers', () => { const spawnOptions = daemonSpawn.mock.calls.at(-1)?.[0] as DaemonSpawnCall expect(spawnOptions.env.PATH.split(delimiter)[0]).toBe('/tmp/orca-agent-teams-bin') - expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir) + expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir()) expect(spawnOptions.env.TERM_PROGRAM).toBeUndefined() expect(spawnOptions.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() expect(spawnOptions.envToDelete).toEqual( @@ -1857,7 +1900,7 @@ describe('registerPtyHandlers', () => { enableGitHubAttribution: true })) expect(env.ORCA_ENABLE_GIT_ATTRIBUTION).toBe('1') - expect(env.PATH).toContain(expectedAttributionShimDir) + expect(env.PATH).toContain(expectedAttributionShimDir()) }) it('keeps the Agent Teams tmux shim ahead of host PATH shims on daemon pty:spawn', async () => { @@ -1878,7 +1921,7 @@ describe('registerPtyHandlers', () => { ) expect(spawnOptions.env.PATH.split(delimiter)[0]).toBe('/tmp/orca-agent-teams-bin') - expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir) + expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir()) expect(spawnOptions.env.TERM_PROGRAM).toBeUndefined() expect(spawnOptions.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() expect(spawnOptions.envToDelete).toEqual( @@ -1995,7 +2038,7 @@ describe('registerPtyHandlers', () => { enableGitHubAttribution: false })) expect(env.ORCA_ENABLE_GIT_ATTRIBUTION).toBeUndefined() - expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir) + expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir()) }) it('does not mutate the caller-provided args.env on the daemon path', async () => { @@ -4248,6 +4291,67 @@ describe('registerPtyHandlers', () => { ) }) + it('threads the validated pane identity into registerPty for a renderer PTY spawn (#7587)', async () => { + const leafId = '88888888-8888-4888-8888-888888888888' + const runtime = { + setPtyController: vi.fn(), + preAllocateHandleForPty: vi.fn(() => 'term_seam'), + registerPreAllocatedHandleForPty: vi.fn(), + registerPty: vi.fn(), + getDriver: vi.fn(() => ({ kind: 'host' })), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + + await handlers.get('pty:spawn')!(mainWindowIpcEvent, { + cols: 80, + rows: 24, + cwd: '/repo', + tabId: 'tab-1', + leafId, + worktreeId: 'wt-1' + }) + + // Why: this is the load-bearing wiring for #7587 — the runtime can only back a + // stalled mobile create from a live spawn if the spawn threads {tabId, leafId}. + expect(runtime.registerPty).toHaveBeenCalledWith(expect.any(String), 'wt-1', null, { + tabId: 'tab-1', + leafId + }) + }) + + it('omits the pane identity from registerPty when the leafId is not a terminal leaf (#7587)', async () => { + const runtime = { + setPtyController: vi.fn(), + preAllocateHandleForPty: vi.fn(() => 'term_seam'), + registerPreAllocatedHandleForPty: vi.fn(), + registerPty: vi.fn(), + getDriver: vi.fn(() => ({ kind: 'host' })), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + + await handlers.get('pty:spawn')!(mainWindowIpcEvent, { + cols: 80, + rows: 24, + cwd: '/repo', + tabId: 'tab-1', + leafId: 'pane:1', + worktreeId: 'wt-1' + }) + + // Why: legacy numeric pane ids (`pane:N`) are not terminal leaf ids, so the + // spawn seam must not fabricate a binding for them (registerPty would ignore + // it anyway); this pins that the seam passes a clean `undefined`. + expect(runtime.registerPty).toHaveBeenCalledWith(expect.any(String), 'wt-1', null, undefined) + }) + it('refreshes native Agent Teams env when captured teammate mode lives in launch args', async () => { const leafId = '11111111-1111-4111-8111-111111111111' const runtime = { @@ -5723,9 +5827,11 @@ describe('registerPtyHandlers', () => { const env = spawnCall[2].env as Record expect(spawnCall[0]).toBe('wsl.exe') expect(env.ORCA_TERMINAL_HANDLE).toBe('term_wsl') + expect(env.ORCA_USER_DATA_PATH).toBe('/tmp/orca-user-data') expect(env.WSLENV?.split(':')).toEqual( expect.arrayContaining([ 'ORCA_TERMINAL_HANDLE/u', + 'ORCA_USER_DATA_PATH/p', 'ORCA_AGENT_HOOK_PORT/u', 'ORCA_AGENT_HOOK_TOKEN/u', 'ORCA_OMP_SOURCE_AGENT_DIR/p', @@ -5735,6 +5841,42 @@ describe('registerPtyHandlers', () => { ) }) + it('forces managed ORCA_USER_DATA_PATH for WSL spawns even when the caller provides a stale root', async () => { + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32' + }) + const runtime = { + setPtyController: vi.fn(), + preAllocateHandleForPty: vi.fn(() => 'term_wsl'), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + + try { + registerPtyHandlers(mainWindow as never, runtime as never) + await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + shellOverride: 'wsl.exe', + env: { + ORCA_USER_DATA_PATH: '/tmp/stale-orca-user-data' + } + }) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + + const spawnCall = spawnMock.mock.calls.at(-1)! + const env = spawnCall[2].env as Record + expect(spawnCall[0]).toBe('wsl.exe') + expect(env.ORCA_USER_DATA_PATH).toBe('/tmp/orca-user-data') + }) + describe('Windows UTF-8 code page', () => { let originalPlatform: string let originalComspec: string | undefined diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 8be807235..eec917ce9 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -100,7 +100,6 @@ import { } from '../../shared/stable-pane-id' import { isValidTerminalTabId } from '../../shared/terminal-tab-id' import { resolveTerminalStartupCwdForWorkspace } from '../../shared/terminal-startup-cwd' -import { localTerminalCwdCanonicalizer } from '../pty/terminal-cwd-realpath' import { clearMigrationUnsupportedPty, clearMigrationUnsupportedPtysForPaneKey @@ -954,15 +953,14 @@ export function buildPtyHostEnv( baseEnv.ORCA_CODEX_HOME = opts.selectedCodexHomePath } - // Why: in dev mode the `orca` CLI defaults to the production userData - // path, which routes status updates to the packaged Orca instead of this - // dev instance. Injecting ORCA_USER_DATA_PATH ensures CLI calls from - // agents running inside dev terminals reach the correct runtime. We also - // prepend the dev CLI launcher directory to PATH so `orca` resolves to - // the dev build (which supports ORCA_USER_DATA_PATH) instead of the - // production binary at /usr/local/bin/orca. - if (!opts.isPackaged) { + // Why: WSL shells need the managed userData root for shell-ready wrappers; dev-mode terminals need the same export so `orca` targets the live dev instance. + if (opts.isWsl) { + baseEnv.ORCA_USER_DATA_PATH = opts.userDataPath + } else if (!opts.isPackaged) { baseEnv.ORCA_USER_DATA_PATH ??= opts.userDataPath + } + // Why: dev mode needs the launcher PATH override so `orca` resolves to the dev build instead of the production binary at /usr/local/bin/orca. + if (!opts.isPackaged) { const devCliBin = join(opts.userDataPath, 'cli', 'bin') const inheritedPath = readInheritedPath(baseEnv) // Why: avoid a trailing delimiter when PATH is empty — some shells @@ -2719,19 +2717,15 @@ export function registerPtyHandlers( assertFolderWorkspacePathUsable(status) } - const resolveGuardedPtySpawnCwd = ( + const resolvePtySpawnStartupCwd = ( worktreeId: string | undefined, - cwd: string | undefined, - connectionId?: string | null + cwd: string | undefined ): string | undefined => resolveTerminalStartupCwdForWorkspace({ workspaceId: worktreeId, requestedCwd: cwd, resolveFolderWorkspacePath: (folderWorkspaceId) => - store?.getFolderWorkspace(folderWorkspaceId)?.folderPath, - // Why: realpath only makes sense on the local filesystem; SSH worktree - // paths live on the remote host. - canonicalizePath: localTerminalCwdCanonicalizer(connectionId) + store?.getFolderWorkspace(folderWorkspaceId)?.folderPath }) // Why: the runtime controller must route through getProviderForPty() so that @@ -2744,7 +2738,7 @@ export function registerPtyHandlers( await startupPromise } await assertFolderWorkspacePtyPathUsable(args.worktreeId) - const cwd = resolveGuardedPtySpawnCwd(args.worktreeId, args.cwd, args.connectionId) + const cwd = resolvePtySpawnStartupCwd(args.worktreeId, args.cwd) const provider = getProvider(args.connectionId) const isClaudeLaunch = !args.connectionId && isClaudeLaunchCommand(args.command) if (isClaudeLaunch && isClaudeAuthSwitchInProgress()) { @@ -3042,7 +3036,20 @@ export function registerPtyHandlers( runtime?.registerPreAllocatedHandleForPty(result.id, args.preAllocatedHandle) } if (args.worktreeId) { - runtime?.registerPty(result.id, args.worktreeId, args.connectionId ?? null) + runtime?.registerPty( + result.id, + args.worktreeId, + args.connectionId ?? null, + // Why: thread the validated pane identity so main can back a pending + // mobile create from this live spawn even if graph-sync stalls (#7587). + // Bound tabId like the sibling metadataPaneKey/spawnOptions.tabId here. + typeof args.tabId === 'string' && + isValidTerminalTabId(args.tabId) && + args.tabId.length <= 512 && + metadataLeafId !== null + ? { tabId: args.tabId, leafId: metadataLeafId } + : undefined + ) } // Why: arms main's per-PTY Command Code output detector from the launch // command (renderer startupCommand parity); banner detection covers @@ -3407,7 +3414,7 @@ export function registerPtyHandlers( await startupPromise } await assertFolderWorkspacePtyPathUsable(args.worktreeId) - const cwd = resolveGuardedPtySpawnCwd(args.worktreeId, args.cwd, args.connectionId) + const cwd = resolvePtySpawnStartupCwd(args.worktreeId, args.cwd) spawnTiming.mark('preflight') const provider = getProvider(args.connectionId) const isClaudeLaunch = !args.connectionId && isClaudeLaunchCommand(args.command) @@ -4021,7 +4028,21 @@ export function registerPtyHandlers( args.worktreeId.length > 0 && args.worktreeId.length <= 512 ) { - runtime?.registerPty(result.id, args.worktreeId, args.connectionId ?? null) + runtime?.registerPty( + result.id, + args.worktreeId, + args.connectionId ?? null, + // Why: pass the validated pane identity so a mobile create waiting on + // this renderer tab can publish its surface main-side when graph-sync + // is throttled, instead of destroying the live PTY (#7587). Bound the + // untrusted tabId like the sibling metadataPaneKey/spawnOptions.tabId. + typeof args.tabId === 'string' && + isValidTerminalTabId(args.tabId) && + args.tabId.length <= 512 && + metadataLeafId !== null + ? { tabId: args.tabId, leafId: metadataLeafId } + : undefined + ) } // Why: arms main's per-PTY Command Code output detector from the launch // command (renderer startupCommand parity); banner detection covers diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index 0b7c4e071..6a73db56d 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -1,6 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { + getPathMock, + listEnvironmentsMock, + callRuntimeEnvironmentMock, registerCliHandlersMock, registerPreflightHandlersMock, registerClaudeUsageHandlersMock, @@ -57,6 +60,9 @@ const { registerEmulatorFrameStreamHandlersMock, registerEmulatorVideoStreamHandlersMock } = vi.hoisted(() => ({ + getPathMock: vi.fn(() => '/test/user-data'), + listEnvironmentsMock: vi.fn(() => []), + callRuntimeEnvironmentMock: vi.fn(), registerCliHandlersMock: vi.fn(), registerPreflightHandlersMock: vi.fn(), registerClaudeUsageHandlersMock: vi.fn(), @@ -114,6 +120,20 @@ const { registerEmulatorVideoStreamHandlersMock: vi.fn() })) +vi.mock('electron', () => ({ + app: { + getPath: getPathMock + } +})) + +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: listEnvironmentsMock +})) + +vi.mock('./runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: callRuntimeEnvironmentMock +})) + vi.mock('./onboarding', () => ({ registerOnboardingHandlers: registerOnboardingHandlersMock })) @@ -326,6 +346,11 @@ import { registerCoreHandlers } from './register-core-handlers' describe('registerCoreHandlers', () => { beforeEach(() => { + getPathMock.mockReset() + getPathMock.mockReturnValue('/test/user-data') + listEnvironmentsMock.mockReset() + listEnvironmentsMock.mockReturnValue([]) + callRuntimeEnvironmentMock.mockReset() registerCliHandlersMock.mockReset() registerPreflightHandlersMock.mockReset() registerClaudeUsageHandlersMock.mockReset() @@ -382,7 +407,7 @@ describe('registerCoreHandlers', () => { registerEmulatorVideoStreamHandlersMock.mockReset() }) - it('passes the store through to handler registrars that need it', () => { + it('passes the store through to handler registrars that need it', async () => { const store = { marker: 'store' } const runtime = { marker: 'runtime', getAgentBrowserBridge: () => null } const stats = { marker: 'stats' } @@ -415,6 +440,14 @@ describe('registerCoreHandlers', () => { { getAdditionalAiVaultCodexHomePaths, onBeforeRelaunch } ) + const aiVaultOptions = registerAiVaultHandlersMock.mock.calls[0]?.[0] + expect(aiVaultOptions).toBeDefined() + + callRuntimeEnvironmentMock.mockResolvedValueOnce({ + ok: true, + result: { sessions: 'bad-shape' } + }) + expect(registerClaudeUsageHandlersMock).toHaveBeenCalledWith(claudeUsage) expect(registerCodexUsageHandlersMock).toHaveBeenCalledWith(codexUsage) expect(registerOpenCodeUsageHandlersMock).toHaveBeenCalledWith(openCodeUsage) @@ -451,9 +484,14 @@ describe('registerCoreHandlers', () => { expect(registerRuntimeHandlersMock).toHaveBeenCalledWith(runtime) expect(registerRuntimeEnvironmentHandlersMock).toHaveBeenCalledWith(store) expect(registerEphemeralVmHandlersMock).toHaveBeenCalledWith(store) - expect(registerAiVaultHandlersMock).toHaveBeenCalledWith({ - getAdditionalCodexHomePaths: getAdditionalAiVaultCodexHomePaths - }) + expect(registerAiVaultHandlersMock).toHaveBeenCalledWith( + expect.objectContaining({ + getAdditionalCodexHomePaths: getAdditionalAiVaultCodexHomePaths, + getActiveRuntimeAiVaultHostInfos: expect.any(Function), + scanRuntimeAiVaultSessions: expect.any(Function) + }) + ) + expect(aiVaultOptions.getActiveRuntimeAiVaultHostInfos()).toEqual([]) expect(registerNativeChatHandlersMock).toHaveBeenCalled() expect(registerCliHandlersMock).toHaveBeenCalled() expect(registerPreflightHandlersMock).toHaveBeenCalled() @@ -466,6 +504,40 @@ describe('registerCoreHandlers', () => { expect(registerBrowserHandlersMock).toHaveBeenCalled() expect(registerFilesystemWatcherHandlersMock).toHaveBeenCalled() expect(registerSpeechHandlersMock).toHaveBeenCalledWith(store) + + await expect( + aiVaultOptions.scanRuntimeAiVaultSessions( + 'env-123', + { + limit: 10, + scopePaths: ['/workspace'] + }, + { timeoutMs: 3000 } + ) + ).resolves.toEqual({ + sessions: [], + issues: [ + expect.objectContaining({ + executionHostId: 'runtime:env-123', + agent: 'codex', + path: 'env-123', + message: expect.stringContaining('Invalid aiVault.listSessions response') + }) + ], + scannedAt: expect.any(String) + }) + expect(callRuntimeEnvironmentMock).toHaveBeenCalledWith( + '/test/user-data', + 'env-123', + 'aiVault.listSessions', + { + limit: 10, + force: undefined, + scopePaths: ['/workspace'], + executionHostId: 'runtime:env-123' + }, + 3000 + ) }) it('only registers IPC handlers once but always updates web contents id', () => { diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 50dbd0a8f..f651cd002 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -1,3 +1,4 @@ +import { app } from 'electron' import { registerAppHandlers } from './app' import { registerCliHandlers } from './cli' import { registerPreflightHandlers } from './preflight' @@ -69,6 +70,10 @@ import type { AutomationService } from '../automations/service' import type { AgentAwakeService } from '../agent-awake-service' import type { CrashReportStore } from '../crash-reporting/crash-report-store' import type { KeybindingService } from '../keybindings/keybinding-service' +import { + getSavedRuntimeAiVaultHostInfos, + scanRuntimeAiVaultSessions +} from '../ai-vault/runtime-session-scanner' let registered = false @@ -171,7 +176,11 @@ export function registerCoreHandlers( registerRuntimeEnvironmentHandlers(store) registerEphemeralVmHandlers(store) registerAiVaultHandlers({ - getAdditionalCodexHomePaths: lifecycleOptions.getAdditionalAiVaultCodexHomePaths + getAdditionalCodexHomePaths: lifecycleOptions.getAdditionalAiVaultCodexHomePaths, + getActiveRuntimeAiVaultHostInfos: () => + getSavedRuntimeAiVaultHostInfos(app.getPath('userData')), + scanRuntimeAiVaultSessions: async (environmentId, args, options) => + scanRuntimeAiVaultSessions(app.getPath('userData'), environmentId, args, options) }) registerNativeChatHandlers() registerClipboardHandlers(store) diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index e34c43821..c5d1c8f2a 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -1118,6 +1118,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v ipcMain.removeHandler('repos:list') ipcMain.removeHandler('repos:add') ipcMain.removeHandler('repos:remove') + ipcMain.removeHandler('repos:removeForHost') ipcMain.removeHandler('repos:reorder') ipcMain.removeHandler('repos:update') ipcMain.removeHandler('projects:list') @@ -1926,6 +1927,22 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v notifyReposChanged(mainWindow) }) + // Why: forget a project on a single execution host without disturbing the + // same repo id on other hosts (local or a re-added SSH target). Used by the + // SSH-workspace forget flow when a host is removed/disconnected. + ipcMain.handle( + 'repos:removeForHost', + async (_event, args: { repoId: string; hostId: string }) => { + const hostId = normalizeExecutionHostId(args.hostId) + if (!hostId) { + throw new Error(`Invalid host ID: ${args.hostId}`) + } + store.removeProjectForHost(args.repoId, hostId) + invalidateAuthorizedRootsCache() + notifyReposChanged(mainWindow) + } + ) + ipcMain.handle( 'repos:update', ( diff --git a/src/main/ipc/ssh.test.ts b/src/main/ipc/ssh.test.ts index a1db12efa..0c5a51d9a 100644 --- a/src/main/ipc/ssh.test.ts +++ b/src/main/ipc/ssh.test.ts @@ -50,7 +50,8 @@ const { onRequest: vi.fn().mockReturnValue(() => {}), onDispose: vi.fn().mockReturnValue(() => {}), request: vi.fn().mockResolvedValue({}), - notify: vi.fn() + notify: vi.fn(), + probeLiveness: vi.fn().mockResolvedValue(false) }, mockPtyProvider: { onData: vi.fn(), @@ -316,6 +317,7 @@ describe('SSH IPC handlers', () => { mockMux.isDisposed.mockReset().mockReturnValue(false) mockMux.onNotification.mockReset() mockMux.onDispose.mockReset().mockReturnValue(() => {}) + mockMux.probeLiveness.mockReset().mockResolvedValue(false) mockPtyProvider.onData.mockReset() mockPtyProvider.onExit.mockReset() mockPtyProvider.onReplay.mockReset() @@ -778,6 +780,39 @@ describe('SSH IPC handlers', () => { expect(runtime.onPtyExit).toHaveBeenCalledWith('remote-pty', 7) }) + it('mirrors SSH state broadcasts onto the runtime client-event stream', async () => { + const runtime = { + onPtyData: vi.fn(), + onPtyExit: vi.fn(), + notifySshStateChanged: vi.fn() + } + registerSshHandlers(mockStore as never, () => mockWindow as never, runtime as never) + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue({}) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + // Why: paired remote clients only learn SSH state through this hook — + // without it their reconnect overlays never clear (STA-1468). + expect(runtime.notifySshStateChanged).toHaveBeenCalledWith( + 'ssh-1', + expect.objectContaining({ targetId: 'ssh-1', status: 'connected' }) + ) + }) + it('preserves active port forwards and live connections across handler re-registration', async () => { const target: SshTarget = { id: 'ssh-1', @@ -1368,7 +1403,7 @@ describe('SSH IPC handlers', () => { expect(mockConnectionManager.disconnect).toHaveBeenCalledWith('ssh-1') }) - it('forces active SSH sessions to reconnect when the system resumes from sleep', async () => { + it('reconnects on system resume when the relay liveness probe fails', async () => { const target: SshTarget = { id: 'ssh-1', label: 'Server', @@ -1386,6 +1421,7 @@ describe('SSH IPC handlers', () => { error: null, reconnectAttempt: 0 }) + mockMux.probeLiveness.mockResolvedValue(false) await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) @@ -1394,7 +1430,77 @@ describe('SSH IPC handlers', () => { resumeListener() - expect(mockConnectionManager.reconnect).toHaveBeenCalledWith('ssh-1') + await vi.waitFor(() => expect(mockConnectionManager.reconnect).toHaveBeenCalledWith('ssh-1')) + // Why: a failed first probe gets one retry before teardown (slow post-wake network). + expect(mockMux.probeLiveness).toHaveBeenCalledTimes(2) + }) + + it('skips reconnect on system resume when the relay link is still alive', async () => { + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const conn = {} + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue(conn) + mockConnectionManager.getConnection.mockReturnValue(conn) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + mockMux.probeLiveness.mockResolvedValue(true) + + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + const resumeListener = powerMonitorOnMock.mock.calls.find(([event]) => event === 'resume')?.[1] + expect(resumeListener).toBeTypeOf('function') + + resumeListener() + + await vi.waitFor(() => expect(mockMux.probeLiveness).toHaveBeenCalledTimes(1)) + // Let the async resume handler settle before asserting no teardown happened. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mockConnectionManager.reconnect).not.toHaveBeenCalled() + }) + + it('does not reconnect after resume when the target was disconnected during the probe', async () => { + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const conn = {} + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue(conn) + mockConnectionManager.getConnection.mockReturnValue(conn) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + mockMux.probeLiveness.mockResolvedValue(false) + + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + const resumeListener = powerMonitorOnMock.mock.calls.find(([event]) => event === 'resume')?.[1] + expect(resumeListener).toBeTypeOf('function') + + resumeListener() + // Why: the probe window is seconds long; a user disconnect during it must + // win — reconnecting afterwards would resurrect the torn-down target. + mockConnectionManager.getConnection.mockReturnValue(undefined) + + await vi.waitFor(() => expect(mockMux.probeLiveness).toHaveBeenCalledTimes(2)) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mockConnectionManager.reconnect).not.toHaveBeenCalled() }) it('extends active relay grace while the system is suspending', async () => { diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index 0ac0c5e0d..8b5756bff 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -51,6 +51,7 @@ let currentRuntime: OrcaRuntimeService | undefined const SSH_IPC_CHANNELS = [ 'ssh:listTargets', + 'ssh:listRemovedTargetLabels', 'ssh:addTarget', 'ssh:updateTarget', 'ssh:removeTarget', @@ -89,6 +90,16 @@ export function getRegisteredSshState(targetId: string): SshConnectionState | un return registeredGetSshState?.(targetId) } +/** Public targets for runtime RPC clients — same list the desktop renderer gets. */ +export function listRegisteredSshTargets(): SshTarget[] { + return sshStore?.listTargets() ?? [] +} + +/** Removed-target id → last known label, for ghost-host display on paired clients. */ +export function listRegisteredRemovedSshTargetLabels(): Record { + return sshStore?.listRemovedTargetLabels() ?? {} +} + export async function disconnectRegisteredSshTarget(targetId: string): Promise { if (!connectionManager) { return @@ -234,13 +245,14 @@ function broadcastSshState( if (isRuntimeOwnedSshTargetId(targetId)) { return } + const enrichedState = withSshRemotePlatform(targetId, state) const win = getMainWindow() if (win && !win.isDestroyed()) { - win.webContents.send('ssh:state-changed', { - targetId, - state: withSshRemotePlatform(targetId, state) - }) + win.webContents.send('ssh:state-changed', { targetId, state: enrichedState }) } + // Why: paired remote clients have no ssh:state-changed IPC; without this + // their terminals keep a stale reconnect overlay after the host connects. + currentRuntime?.notifySshStateChanged?.(targetId, enrichedState) } function withSshRemotePlatform(targetId: string, state: SshConnectionState): SshConnectionState { @@ -430,6 +442,24 @@ function registerAdvertisedUrlRefresh(getMainWindow: () => BrowserWindow | null) }) } +// Why: macOS can resume the process before the network stack is back up, so +// a failed first probe gets one retry before the link is declared dead (#7773). +const RESUME_PROBE_TIMEOUT_MS = 5_000 +const RESUME_PROBE_ATTEMPTS = 2 + +async function isRelayLinkAliveAfterResume(session: SshRelaySession): Promise { + const mux = session.getMux() + if (!mux || mux.isDisposed()) { + return false + } + for (let attempt = 0; attempt < RESUME_PROBE_ATTEMPTS; attempt++) { + if (await mux.probeLiveness(RESUME_PROBE_TIMEOUT_MS)) { + return true + } + } + return false +} + function registerPowerMonitorReconnect(): void { powerMonitorUnsubscribe?.() const onSuspend = (): void => { @@ -438,19 +468,35 @@ function registerPowerMonitorReconnect(): void { } } const onResume = (): void => { - for (const targetId of activeSessions.keys()) { - const conn = connectionManager?.getConnection(targetId) + for (const [targetId, session] of activeSessions) { + const manager = connectionManager + const conn = manager?.getConnection(targetId) if (!conn) { continue } - const reconnect = connectionManager?.reconnect(targetId) - void reconnect?.catch((err) => { - console.warn( - `[ssh] Failed to reconnect ${targetId} after system resume: ${ - err instanceof Error ? err.message : String(err) - }` - ) - }) + void (async () => { + // Why: unconditional reconnect on every wake tore down live sessions + // and flashed the reconnect overlay (#7773). Only reconnect targets + // whose relay link actually died during sleep. + if (await isRelayLinkAliveAfterResume(session)) { + return + } + // Why: the probe can take ~10s. If the user disconnected or the + // session/connection was replaced meanwhile, reconnecting would + // resurrect a connection that was intentionally torn down. + if (activeSessions.get(targetId) !== session || manager?.getConnection(targetId) !== conn) { + return + } + try { + await manager?.reconnect(targetId) + } catch (err) { + console.warn( + `[ssh] Failed to reconnect ${targetId} after system resume: ${ + err instanceof Error ? err.message : String(err) + }` + ) + } + })() } } powerMonitor.on('suspend', onSuspend) @@ -695,12 +741,35 @@ export function registerSshHandlers( // ── Target CRUD ──────────────────────────────────────────────────── + // Why: SSH target add/import can re-adopt workspaces orphaned on a removed + // target id (see ssh-target-readoption). When that re-points repos, the + // renderer must refresh its repo list to surface the reattached workspaces. + function notifyReposChangedIfReadopted(): void { + if (!sshStore || sshStore.lastReadoptedRepoCount <= 0) { + return + } + sshStore.lastReadoptedRepoCount = 0 + const win = getCurrentMainWindow() + if (win && !win.isDestroyed()) { + win.webContents.send('repos:changed') + } + } + ipcMain.handle('ssh:listTargets', () => { return sshStore!.listTargets() }) + ipcMain.handle('ssh:listRemovedTargetLabels', () => { + return sshStore!.listRemovedTargetLabels() + }) + ipcMain.handle('ssh:addTarget', (_event, args: { target: Omit }) => { - return sshStore!.addTarget(args.target) + const target = sshStore!.addTarget(args.target) + // Why: re-adding a removed host can re-adopt orphaned workspaces (re-point + // repos/worktrees off the dead id). Refresh the renderer's repo list so the + // reattached workspaces move from grey ghosts back onto the live host. + notifyReposChangedIfReadopted() + return target }) ipcMain.handle( @@ -715,7 +784,9 @@ export function registerSshHandlers( }) ipcMain.handle('ssh:importConfig', (_event, args?: { reAdopt?: boolean }) => { - return sshStore!.importFromSshConfig(args) + const result = sshStore!.importFromSshConfig(args) + notifyReposChangedIfReadopted() + return result }) // ── Connection lifecycle ─────────────────────────────────────────── diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index e9f9edfcd..43c943257 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -7946,4 +7946,80 @@ describe('registerWorktreeHandlers', () => { expect(store.setWorktreeMeta).not.toHaveBeenCalled() expect(createSetupRunnerScriptMock).not.toHaveBeenCalled() }) + + describe('worktrees:forgetLocal', () => { + it('forgets a workspace pinned to a removed SSH target without touching the provider', async () => { + const repo = { + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + connectionId: 'ssh-dead', + worktreeBaseRef: null + } + const ptyProvider = {} as never + const worktreeId = 'repo-1::/workspace/feature-wt' + store.getRepo.mockReturnValue(repo) + getLocalPtyProviderMock.mockReturnValue(ptyProvider) + // Why: a removed/disconnected SSH target has no live provider; forgetLocal + // must not reach for one. + getSshGitProviderMock.mockReturnValue(undefined) + + const result = await handlers['worktrees:forgetLocal'](null, { worktreeId }) + + expect(result).toEqual({}) + expect(killAllProcessesForWorktreeMock).toHaveBeenCalledWith(worktreeId, { + runtime: runtimeStub, + localProvider: ptyProvider, + onPtyStopped: clearProviderPtyStateMock + }) + expect(runtimeStub.clearOptimisticReconcileToken).toHaveBeenCalledWith(worktreeId) + expect(store.removeWorktreeMeta).toHaveBeenCalledWith(worktreeId) + expect(advertisedUrlWatcherForgetWorktreeMock).toHaveBeenCalledWith(worktreeId) + expect(deleteWorktreeHistoryDirMock).toHaveBeenCalledWith(worktreeId) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('worktrees:changed', { + repoId: 'repo-1' + }) + // The whole point: local-only cleanup never dispatches to the SSH provider. + expect(getSshGitProviderMock).not.toHaveBeenCalled() + expect(getSshFilesystemProviderMock).not.toHaveBeenCalled() + expect(listWorktreesMock).not.toHaveBeenCalled() + expect(removeWorktreeMock).not.toHaveBeenCalled() + }) + + it('throws when the repo is missing', async () => { + store.getRepo.mockReturnValue(undefined) + + await expect( + handlers['worktrees:forgetLocal'](null, { + worktreeId: 'repo-gone::/workspace/feature-wt' + }) + ).rejects.toThrow(/Repo not found/) + + expect(store.removeWorktreeMeta).not.toHaveBeenCalled() + expect(getSshGitProviderMock).not.toHaveBeenCalled() + }) + + it('rejects forgetting a folder project root', async () => { + const repo = { + id: 'repo-folder', + path: '/workspace/folder', + displayName: 'folder', + badgeColor: '#000', + addedAt: 0, + kind: 'folder' as const + } + store.getRepo.mockReturnValue(repo) + + await expect( + handlers['worktrees:forgetLocal'](null, { + worktreeId: `${repo.id}::${repo.path}` + }) + ).rejects.toThrow(/project root workspace/) + + expect(store.removeWorktreeMeta).not.toHaveBeenCalled() + expect(deleteWorktreeHistoryDirMock).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 8b966e2b5..d3ed83564 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -931,6 +931,7 @@ export function registerWorktreeHandlers( ipcMain.removeHandler('worktrees:resolvePrBase') ipcMain.removeHandler('worktrees:resolveMrBase') ipcMain.removeHandler('worktrees:remove') + ipcMain.removeHandler('worktrees:forgetLocal') ipcMain.removeHandler('worktrees:forceDeletePreservedBranch') ipcMain.removeHandler('worktrees:updateMeta') ipcMain.removeHandler('worktrees:listLineage') @@ -1807,6 +1808,67 @@ export function registerWorktreeHandlers( } ) + // Why: forget-locally drops a workspace from Orca without any remote Git or + // filesystem work. It exists so a workspace pinned to a removed/disconnected + // SSH target — whose provider is gone and whose `worktrees:remove` therefore + // throws at requireSshGitProvider before any cleanup runs — can still be + // cleared from the app. It never touches the remote: no worktree registration, + // no branches, no files are deleted there. + ipcMain.handle( + 'worktrees:forgetLocal', + async (_event, args: { worktreeId: string }): Promise => { + // Why: share the removal in-flight map (not a separate one) so a concurrent + // worktrees:remove and worktrees:forgetLocal on the same id cannot both + // mutate metadata. A forget takes no force/skipArchive options. + const optionsKey = 'forget-local' + const inFlight = worktreeRemovalsInFlight.get(args.worktreeId) + if (inFlight) { + if (inFlight.optionsKey === optionsKey) { + return inFlight.promise + } + throw new Error(`Worktree deletion already in progress: ${args.worktreeId}`) + } + + const forget = (async (): Promise => { + const { repoId } = parseWorktreeId(args.worktreeId) + const repo = store.getRepo(repoId) + if (!repo) { + throw new Error(`Repo not found: ${repoId}`) + } + if (isFolderRepo(repo) && args.worktreeId === getFolderWorkspaceRootId(repo)) { + throw new Error( + 'Cannot delete the project root workspace. Remove the folder project instead.' + ) + } + + // Why: best-effort PTY sweep. killAllProcessesForWorktree resolves + // synchronously for a dead SSH relay (the provider tombstones the lease + // and returns without awaiting the remote), so this never hangs. + await killAllProcessesForWorktree(args.worktreeId, { + runtime, + localProvider: getLocalPtyProvider(), + onPtyStopped: clearProviderPtyState + }).catch((err) => { + console.warn(`[worktree-teardown] forget-local failed for ${args.worktreeId}:`, err) + }) + + runtime.clearOptimisticReconcileToken(args.worktreeId) + removeWorktreeMetadataAndTransientState(store, args.worktreeId) + preservedBranchCleanupByWorktreeId.delete(args.worktreeId) + notifyWorktreesChanged(mainWindow, repoId) + return {} + })() + worktreeRemovalsInFlight.set(args.worktreeId, { optionsKey, promise: forget }) + try { + return await forget + } finally { + if (worktreeRemovalsInFlight.get(args.worktreeId)?.promise === forget) { + worktreeRemovalsInFlight.delete(args.worktreeId) + } + } + } + ) + ipcMain.handle( 'worktrees:forceDeletePreservedBranch', async ( diff --git a/src/main/observability/bundle.test.ts b/src/main/observability/bundle.test.ts index d53271182..347e10258 100644 --- a/src/main/observability/bundle.test.ts +++ b/src/main/observability/bundle.test.ts @@ -140,6 +140,53 @@ describe('bundle — collection', () => { expect(bundle.payload).not.toContain('"name":"old"') }) + it('merges the daemon lifecycle log, bounded by the same lookback', () => { + const daemonFile = join(dir, 'daemon.log') + writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'recent' })])) + writeFileSync( + daemonFile, + makeNDJSON([ + { src: 'daemon', ts: new Date().toISOString(), pid: 1, event: 'startup' }, + { + src: 'daemon', + // 1h ago — outside the 30m window, must be dropped. + ts: new Date(Date.now() - 60 * 60 * 1000).toISOString(), + pid: 1, + event: 'session-exited' + } + ]) + ) + const bundle = collectBundle({ + traceFilePath: traceFile, + maxFiles: 10, + daemonLogFilePath: daemonFile, + daemonLogMaxFiles: 3, + lookbackMinutes: 30, + appVersion: '1', + platform: 'darwin', + arch: 'arm64', + osRelease: '24', + orcaChannel: 'dev' + }) + expect(bundle.payload).toContain('"event":"startup"') + expect(bundle.payload).toContain('"name":"recent"') + expect(bundle.payload).not.toContain('"event":"session-exited"') + }) + + it('collects no daemon log lines when no daemon log path is given', () => { + writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'recent' })])) + const bundle = collectBundle({ + traceFilePath: traceFile, + maxFiles: 10, + appVersion: '1', + platform: 'darwin', + arch: 'arm64', + osRelease: '24', + orcaChannel: 'dev' + }) + expect(bundle.payload).not.toContain('"src":"daemon"') + }) + it('runs the redactor on the merged payload (belt-and-suspenders)', () => { // Simulate a sink-write bug that leaked a secret through. The bundle // pass should still strip it. diff --git a/src/main/observability/bundle.ts b/src/main/observability/bundle.ts index 812e354d5..34011d9e4 100644 --- a/src/main/observability/bundle.ts +++ b/src/main/observability/bundle.ts @@ -39,6 +39,10 @@ const DEFAULT_LOOKBACK_MINUTES = 30 export type CollectBundleOptions = { readonly traceFilePath: string readonly maxFiles: number + /** Detached-daemon lifecycle log. Its rotated family is merged into the + * bundle so daemon-side failures are diagnosable from a field report. */ + readonly daemonLogFilePath?: string + readonly daemonLogMaxFiles?: number readonly lookbackMinutes?: number readonly appVersion: string readonly platform: string @@ -95,7 +99,8 @@ function* readLinesNewestFirst(text: string): Iterable { */ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { const lookbackMs = (opts.lookbackMinutes ?? DEFAULT_LOOKBACK_MINUTES) * 60 * 1000 - const cutoffNanos = BigInt(Date.now() - lookbackMs) * 1_000_000n + const cutoffMs = Date.now() - lookbackMs + const cutoffNanos = BigInt(cutoffMs) * 1_000_000n const bundleSubmissionId = generateBundleSubmissionId() const header: BundleHeader = { bundle_submission_id: bundleSubmissionId, @@ -123,7 +128,15 @@ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { // older than the cutoff in an older file we can stop entirely. We don't // optimize that yet; the worst case (10 × 10 MB = 100 MB scan) takes // <1 s on a modern SSD and bundles are user-initiated, not hot-path. - const files = listRotatedFiles(opts.traceFilePath, opts.maxFiles) + // Trace spans first (the primary payload), then the daemon lifecycle log. + // Daemon records carry an ISO `ts` instead of `endTimeUnixNano`; both are + // filtered by the same lookback below. + const files = [ + ...listRotatedFiles(opts.traceFilePath, opts.maxFiles), + ...(opts.daemonLogFilePath + ? listRotatedFiles(opts.daemonLogFilePath, opts.daemonLogMaxFiles ?? opts.maxFiles) + : []) + ] outer: for (const file of files) { let text: string try { @@ -153,7 +166,11 @@ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { continue } - const record = parsed as { startTimeUnixNano?: string; endTimeUnixNano?: string } + const record = parsed as { + startTimeUnixNano?: string + endTimeUnixNano?: string + ts?: string + } // Filter by end-time, not start-time. A long-lived span started 35 // minutes ago but ending inside the lookback is exactly what we want // in the bundle for diagnosing "session crashed at minute 32." @@ -166,6 +183,13 @@ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { // Non-numeric end-time — keep it; better to over-include than to // drop a record we couldn't classify. } + } else if (typeof record.ts === 'string') { + // Daemon lifecycle lines timestamp with an ISO `ts`; bound them by the + // same lookback window. Unparseable timestamps are kept (over-include). + const tsMs = Date.parse(record.ts) + if (Number.isFinite(tsMs) && tsMs < cutoffMs) { + continue + } } // Run the redactor a SECOND TIME over the parsed shape, in server mode. diff --git a/src/main/observability/index.ts b/src/main/observability/index.ts index 9ab216d50..791653d27 100644 --- a/src/main/observability/index.ts +++ b/src/main/observability/index.ts @@ -28,15 +28,14 @@ // import isolation rule above. The cost of one duplicated array vs. // punching a hole in the architecture is trivially worth it. -import { app } from 'electron' -import { homedir, platform } from 'node:os' -import { join } from 'node:path' import { createLocalFileSink, DEFAULT_MAX_FILES, getRotatedFamilySize, type LocalFileSink } from './local-file-sink' +import { getDaemonLogFilePath, getTraceFilePath } from './logs-directory' +import { DAEMON_LOG_MAX_FILES } from '../daemon/daemon-file-log' import { collectBundle as _collectBundle, type CollectBundleOptions, @@ -128,30 +127,9 @@ export function resolveObservabilityConsent(): ObservabilityConsent { } } -/** Path for the trace NDJSON file. macOS conventional location is - * `~/Library/Application Support/Orca/logs/main.trace.ndjson`; we resolve - * the same intent on Windows / Linux via Electron's `userData` dir. The - * function falls back to homedir when Electron is not available (tests). - */ -export function getTraceFilePath(): string { - let userData: string - try { - userData = app.getPath('userData') - } catch { - // Tests — Electron's `app` may not be initialized. Use a sensible - // OS-conventional fallback so unit tests can construct the path - // without spinning up the full Electron runtime. - const home = homedir() - if (platform() === 'darwin') { - userData = join(home, 'Library', 'Application Support', 'Orca') - } else if (platform() === 'win32') { - userData = join(process.env.APPDATA ?? home, 'Orca') - } else { - userData = join(home, '.config', 'Orca') - } - } - return join(userData, 'logs', 'main.trace.ndjson') -} +// Re-exported so existing importers of the trace path keep working; the +// resolution now lives in one place alongside the daemon log path. +export { getTraceFilePath } from './logs-directory' // ── Module-level state ─────────────────────────────────────────────────── @@ -237,6 +215,11 @@ export function collectDiagnosticBundle( return _collectBundle({ traceFilePath: getTraceFilePath(), maxFiles: DEFAULT_MAX_FILES, + // Why: the detached daemon writes its lifecycle log to a separate file, so + // the bundle collector must be pointed at it explicitly — it does not glob + // the logs directory. + daemonLogFilePath: getDaemonLogFilePath(), + daemonLogMaxFiles: DAEMON_LOG_MAX_FILES, ...meta }) } diff --git a/src/main/observability/logs-directory.ts b/src/main/observability/logs-directory.ts new file mode 100644 index 000000000..94a1b7baa --- /dev/null +++ b/src/main/observability/logs-directory.ts @@ -0,0 +1,41 @@ +// Single source of truth for the app's logs directory and the files inside it. +// macOS convention is `~/Library/Application Support/Orca/logs/`; Windows and +// Linux resolve the same intent via Electron's `userData` dir. Falls back to a +// homedir-derived path when Electron's `app` is unavailable (unit tests). + +import { app } from 'electron' +import { homedir, platform } from 'node:os' +import { join } from 'node:path' + +function getUserDataDir(): string { + try { + return app.getPath('userData') + } catch { + // Tests — Electron's `app` may not be initialized. Use an OS-conventional + // fallback so callers can resolve the path without the Electron runtime. + const home = homedir() + if (platform() === 'darwin') { + return join(home, 'Library', 'Application Support', 'Orca') + } + if (platform() === 'win32') { + return join(process.env.APPDATA ?? home, 'Orca') + } + return join(home, '.config', 'Orca') + } +} + +export function getLogsDirectory(): string { + return join(getUserDataDir(), 'logs') +} + +/** NDJSON trace file written by the main-process error-tracking sink. */ +export function getTraceFilePath(): string { + return join(getLogsDirectory(), 'main.trace.ndjson') +} + +/** NDJSON lifecycle log written by the detached daemon process. Shared here so + * the daemon fork (which passes it as `--log-file`) and the bundle collector + * (which reads it) agree on one path. */ +export function getDaemonLogFilePath(): string { + return join(getLogsDirectory(), 'daemon.log') +} diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index d4862d9dc..52f826935 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -2988,6 +2988,16 @@ describe('Store', () => { expect(updated?.projectGroupOrder).toBe(1) }) + it('updates repo execution host identity', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1' })) + + const updated = store.updateRepo('r1', { executionHostId: 'runtime:env-1' }) + + expect(updated?.executionHostId).toBe('runtime:env-1') + expect(store.getRepo('r1')?.executionHostId).toBe('runtime:env-1') + }) + it('getRepo returns undefined for nonexistent id', async () => { const store = await createStore() expect(store.getRepo('nonexistent')).toBeUndefined() @@ -3058,6 +3068,270 @@ describe('Store', () => { expect(store.getWorktreeLineage('r2::/other')).toBeDefined() }) + // ── 6b. removeProjectForHost is host-scoped ─────────────────────────── + + it('removeProjectForHost removes only the target host row for a shared repo id', async () => { + const store = await createStore() + // Same repo id on both local and an SSH host. + store.addRepo(makeRepo({ id: 'shared', path: '/local/repo' })) + store.addRepo( + makeRepo({ + id: 'shared', + path: '/remote/repo', + connectionId: 'ssh-old', + executionHostId: 'ssh:ssh-old' + }) + ) + store.setWorktreeMeta('shared::/local/repo/wt', { displayName: 'local-wt', hostId: 'local' }) + store.setWorktreeMeta('shared::/remote/repo/wt', { + displayName: 'remote-wt', + hostId: 'ssh:ssh-old' + }) + + store.removeProjectForHost('shared', 'ssh:ssh-old') + + const remaining = store.getRepos().filter((r) => r.id === 'shared') + expect(remaining).toHaveLength(1) + expect(remaining[0].path).toBe('/local/repo') + // Local worktree meta survives; the SSH host's meta is pruned. + expect(store.getWorktreeMeta('shared::/local/repo/wt')).toBeDefined() + expect(store.getWorktreeMeta('shared::/remote/repo/wt')).toBeUndefined() + }) + + it('removeProjectForHost prunes the SSH host meta (tagged hostId) for a shared id', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'shared', path: '/local/repo' })) + store.addRepo( + makeRepo({ + id: 'shared', + path: '/remote/repo', + connectionId: 'ssh-old', + executionHostId: 'ssh:ssh-old' + }) + ) + // SSH worktree meta correctly carries hostId (the normal, stamped case). + store.setWorktreeMeta('shared::/remote/repo/wt', { + displayName: 'remote-wt', + hostId: 'ssh:ssh-old' + }) + // A hostId-less meta under the same id is treated as local and left behind + // (conservative: never deletes the wrong host's meta). + store.setWorktreeMeta('shared::/local/repo/wt', { displayName: 'local-wt' }) + + store.removeProjectForHost('shared', 'ssh:ssh-old') + + expect(store.getWorktreeMeta('shared::/remote/repo/wt')).toBeUndefined() + expect(store.getWorktreeMeta('shared::/local/repo/wt')).toBeDefined() + }) + + it('removeProjectForHost prunes everything when the id exists on no other host', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'only', connectionId: 'ssh-x', executionHostId: 'ssh:ssh-x' })) + store.setWorktreeMeta('only::/repo/wt', { displayName: 'wt', hostId: 'ssh:ssh-x' }) + + store.removeProjectForHost('only', 'ssh:ssh-x') + + expect(store.getRepo('only')).toBeUndefined() + expect(store.getWorktreeMeta('only::/repo/wt')).toBeUndefined() + }) + + // ── 6c. reassignSshTargetId re-adopts orphaned workspaces ───────────── + + it('reassignSshTargetId re-points repos and worktree metas onto the new id', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old', executionHostId: 'ssh:ssh-old' })) + store.setWorktreeMeta('r1::/repo/wt', { displayName: 'wt', hostId: 'ssh:ssh-old' }) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(count).toBe(1) + const repo = store.getRepo('r1')! + expect(repo.connectionId).toBe('ssh-new') + expect(repo.executionHostId).toBe('ssh:ssh-new') + expect(store.getWorktreeMeta('r1::/repo/wt')!.hostId).toBe('ssh:ssh-new') + }) + + it('reassignSshTargetId leaves repos on other hosts untouched', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'local-repo', path: '/local' })) + store.addRepo( + makeRepo({ + id: 'ssh-repo', + path: '/remote', + connectionId: 'ssh-old', + executionHostId: 'ssh:ssh-old' + }) + ) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(count).toBe(1) + expect(store.getRepo('local-repo')!.connectionId).toBeUndefined() + expect(store.getRepo('ssh-repo')!.connectionId).toBe('ssh-new') + }) + + it('reassignSshTargetId re-points a repo that only carries connectionId (no executionHostId)', async () => { + const store = await createStore() + // SSH repos created via addRemoteRepoFromPath leave executionHostId unset. + store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old' })) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(count).toBe(1) + const repo = store.getRepo('r1')! + expect(repo.connectionId).toBe('ssh-new') + // Must not stamp an executionHostId where there wasn't one. + expect(repo.executionHostId).toBeUndefined() + }) + + it('reassignSshTargetId persists a worktree-meta-only re-point (no matching repo)', async () => { + const store = await createStore() + // A meta on the old SSH host with no corresponding repo row — the re-point + // must still be saved, not left in memory only. + store.setWorktreeMeta('r1::/remote/wt', { displayName: 'wt', hostId: 'ssh:ssh-old' }) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + expect(count).toBe(0) // no repo matched + store.flush() + + const reloaded = await createStore() + expect(reloaded.getWorktreeMeta('r1::/remote/wt')?.hostId).toBe('ssh:ssh-new') + }) + + it('reassignSshTargetId migrates session pty ids, reconnect list, leases, and host scope', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old', executionHostId: 'ssh:ssh-old' })) + store.setWorkspaceSession({ + activeRepoId: 'r1', + activeWorktreeId: 'r1::/wt', + activeTabId: 'tab1', + tabsByWorktree: { + 'r1::/wt': [makeTerminalTab({ id: 'tab1', ptyId: 'ssh:ssh-old@@pty-2' })] + }, + terminalLayoutsByTabId: {}, + remoteSessionIdsByTabId: { tab1: 'ssh:ssh-old@@pty-2' }, + activeConnectionIdsAtShutdown: ['ssh-old'] + }) + store.upsertSshRemotePtyLease({ targetId: 'ssh-old', ptyId: 'pty-2', state: 'detached' }) + store.updateUI({ + workspaceHostScope: 'ssh:ssh-old', + visibleWorkspaceHostIds: ['local', 'ssh:ssh-old'], + workspaceHostOrder: ['ssh:ssh-old', 'local'] + }) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + store.flush() + + const reloaded = await createStore() + const session = reloaded.getWorkspaceSession() + expect(session.tabsByWorktree['r1::/wt'][0].ptyId).toBe('ssh:ssh-new@@pty-2') + expect(session.remoteSessionIdsByTabId).toEqual({ tab1: 'ssh:ssh-new@@pty-2' }) + expect(session.activeConnectionIdsAtShutdown).toEqual(['ssh-new']) + expect(reloaded.getSshRemotePtyLeases('ssh-new')).toHaveLength(1) + expect(reloaded.getSshRemotePtyLeases('ssh-old')).toHaveLength(0) + const ui = reloaded.getUI() + expect(ui.workspaceHostScope).toBe('ssh:ssh-new') + expect(ui.visibleWorkspaceHostIds).toEqual(['local', 'ssh:ssh-new']) + expect(ui.workspaceHostOrder).toEqual(['ssh:ssh-new', 'local']) + }) + + it('reassignSshTargetId re-keys a session partition stored under the old ssh host id', async () => { + const store = await createStore() + store.setWorkspaceSession( + { + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + tabsByWorktree: { + 'r1::/wt': [makeTerminalTab({ id: 'tab1', ptyId: 'ssh:ssh-old@@pty-9' })] + }, + terminalLayoutsByTabId: {} + }, + 'ssh:ssh-old' + ) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + store.flush() + + const reloaded = await createStore() + // Old-key partition is gone; the re-keyed one carries migrated pty ids. + expect(reloaded.getWorkspaceSession('ssh:ssh-old').tabsByWorktree).toEqual({}) + expect(reloaded.getWorkspaceSession('ssh:ssh-new').tabsByWorktree['r1::/wt'][0].ptyId).toBe( + 'ssh:ssh-new@@pty-9' + ) + }) + + it('reassignSshTargetId keeps the live partition when both host keys exist', async () => { + const store = await createStore() + const baseSession = { + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + terminalLayoutsByTabId: {} + } + store.setWorkspaceSession( + { ...baseSession, tabsByWorktree: { 'r1::/dead': [] } }, + 'ssh:ssh-old' + ) + store.setWorkspaceSession( + { ...baseSession, tabsByWorktree: { 'r1::/live': [] } }, + 'ssh:ssh-new' + ) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(store.getWorkspaceSession('ssh:ssh-old').tabsByWorktree).toEqual({}) + expect(store.getWorkspaceSession('ssh:ssh-new').tabsByWorktree).toEqual({ 'r1::/live': [] }) + }) + + it('reassignSshTargetId re-points an independent provisioned host setup', async () => { + const store = await createStore() + store.addRepo({ + ...makeRepo({ id: 'r1', displayName: 'Cloud Project' }), + upstream: { owner: 'stablyai', repo: 'cloud-project' } + }) + store.createProjectHostSetup({ + projectId: 'github:stablyai/cloud-project', + hostId: 'ssh:ssh-old', + setupId: 'cloud-project::ssh-old', + setupMethod: 'provisioned' + }) + + // Meta-only re-adoption (no repo pinned to the old id) must still migrate + // the provisioned setup, or new worktrees would be born on a dead host id. + store.reassignSshTargetId('ssh-old', 'ssh-new') + + const setups = store.getProjectHostSetups() + const provisioned = setups.find((entry) => entry.id === 'cloud-project::ssh-old') + expect(provisioned?.hostId).toBe('ssh:ssh-new') + }) + + it('reassignSshTargetId drops a stale setup when the new host already has one', async () => { + const store = await createStore() + store.addRepo({ + ...makeRepo({ id: 'r1', displayName: 'Cloud Project' }), + upstream: { owner: 'stablyai', repo: 'cloud-project' } + }) + store.createProjectHostSetup({ + projectId: 'github:stablyai/cloud-project', + hostId: 'ssh:ssh-old', + setupId: 'setup-old', + setupMethod: 'provisioned' + }) + store.createProjectHostSetup({ + projectId: 'github:stablyai/cloud-project', + hostId: 'ssh:ssh-new', + setupId: 'setup-new', + setupMethod: 'provisioned' + }) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + + const setups = store.getProjectHostSetups() + expect(setups.find((entry) => entry.id === 'setup-old')).toBeUndefined() + expect(setups.find((entry) => entry.id === 'setup-new')?.hostId).toBe('ssh:ssh-new') + }) + // ── 7. updateRepo ────────────────────────────────────────────────── it('updateRepo modifies the repo in place', async () => { diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 5bad9510e..b10fa4fe9 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -82,6 +82,7 @@ import { MOBILE_PAIRING_USERDATA_FILES } from './runtime/mobile-pairing-files' import { hardenExistingSecureFile } from '../shared/secure-file' import { LEGACY_DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS, + type RemovedSshTargetTombstone, type SshRemotePtyLease, type SshTarget } from '../shared/ssh-types' @@ -108,9 +109,14 @@ import { normalizeExecutionHostOrder, normalizeExecutionHostId, normalizeVisibleExecutionHostIds, + toSshExecutionHostId, type ExecutionHostId } from '../shared/execution-host' import { toRelaySshPtyId } from './providers/ssh-pty-id' +import { + migrateUiHostScopeSshTargetId, + migrateWorkspaceSessionSshTargetId +} from './ssh/ssh-target-id-migration' import { isWslUncPath } from '../shared/wsl-paths' import { isTerminalLeafId, @@ -2181,6 +2187,10 @@ function remapAcknowledgedAgentPaneKeys( // handful of Claude sessions a daemon can realistically keep alive. const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200 +// Why: bound the removed-SSH-target history so remove/re-add churn can't grow +// the state file without limit. Re-adoption only needs recent removals. +const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50 + function normalizeClaudeLivePtySessionIds(value: unknown): string[] { if (!Array.isArray(value)) { return [] @@ -4172,30 +4182,84 @@ export class Store { // Why: presets are repo-scoped, so removing the repo means the presets // can never be referenced again — drop them with the parent. delete this.state.sparsePresetsByRepo[id] - // Clean up worktree meta for this repo + this.pruneWorktreeStateForRepo(id, null) + this.scheduleSave() + } + + // Why: the same repo id can exist on more than one execution host (local, an + // SSH target, a re-added SSH target). Forgetting one host's copy must remove + // only that host's repo row and worktree metadata — never the local or + // another host's records that happen to share the id. + removeProjectForHost(id: string, hostId: ExecutionHostId): void { + this.state.repos = this.state.repos.filter( + (r) => !(r.id === id && getRepoExecutionHostId(r) === hostId) + ) + const idStillPresent = this.state.repos.some((r) => r.id === id) + // Why: presets are repo-id-scoped (not host-scoped); only drop them once the + // last host's copy of this repo is gone, or a surviving host loses its presets. + if (!idStillPresent) { + delete this.state.sparsePresetsByRepo[id] + } + this.syncProjectHostSetupCompatibilityState() + // Why: if the id survives on another host, prune only this host's worktree + // metas; otherwise prune everything for the id (matches removeProject). + this.pruneWorktreeStateForRepo(id, idStillPresent ? hostId : null) + this.scheduleSave() + } + + // Clean up worktree meta, lineage, and workspace lineage for a repo id. + // When hostId is null, prune all of the repo's entries; when a hostId is + // given, prune only entries whose meta.hostId resolves to that host (a + // missing hostId is treated as local). + private pruneWorktreeStateForRepo(id: string, hostId: ExecutionHostId | null): void { const prefix = `${id}::` + // Why: snapshot host membership up front. Lineage pruning below checks the + // meta.hostId of worktree keys that may already have been deleted from + // worktreeMeta in the first loop, so reading hostId live would misclassify + // an SSH worktree as local once its meta is gone. + const hostMembership = new Map() + const belongsToHost = (key: string): boolean => { + if (!key.startsWith(prefix)) { + return false + } + if (hostId === null) { + return true + } + const cached = hostMembership.get(key) + if (cached !== undefined) { + return cached + } + // Why default to local: worktree metas created on/after host-ownership + // stamping carry hostId. A metas without it predates that and is treated as + // local, so a host-scoped (non-local) prune conservatively leaves it — it + // may leak a stale entry for a legacy SSH worktree sharing a repo id with a + // local repo, but it never deletes the wrong host's live meta. + const metaHostId = this.state.worktreeMeta[key]?.hostId ?? LOCAL_EXECUTION_HOST_ID + const result = metaHostId === hostId + hostMembership.set(key, result) + return result + } for (const key of Object.keys(this.state.worktreeMeta)) { - if (key.startsWith(prefix)) { + if (belongsToHost(key)) { delete this.state.worktreeMeta[key] } } for (const [childId, lineage] of Object.entries(this.state.worktreeLineageById)) { - if (childId.startsWith(prefix) || lineage.parentWorktreeId.startsWith(prefix)) { + if (belongsToHost(childId) || belongsToHost(lineage.parentWorktreeId)) { delete this.state.worktreeLineageById[childId] } } for (const [childKey, lineage] of Object.entries(this.state.workspaceLineageByChildKey)) { const childScope = parseWorkspaceKey(childKey) const parentScope = parseWorkspaceKey(lineage.parentWorkspaceKey) - if (childScope?.type === 'worktree' && childScope.worktreeId.startsWith(prefix)) { + if (childScope?.type === 'worktree' && belongsToHost(childScope.worktreeId)) { delete this.state.workspaceLineageByChildKey[childKey as WorkspaceKey] continue } - if (parentScope?.type === 'worktree' && parentScope.worktreeId.startsWith(prefix)) { + if (parentScope?.type === 'worktree' && belongsToHost(parentScope.worktreeId)) { delete this.state.workspaceLineageByChildKey[childKey as WorkspaceKey] } } - this.scheduleSave() } updateRepo( @@ -4212,6 +4276,7 @@ export class Store { | 'worktreeBaseRef' | 'worktreeBasePath' | 'kind' + | 'executionHostId' | 'symlinkPaths' | 'issueSourcePreference' | 'forkSyncMode' @@ -6006,6 +6071,140 @@ export class Store { } } + getRemovedSshTargetTombstones(): RemovedSshTargetTombstone[] { + return [...(this.state.removedSshTargetTombstones ?? [])] + } + + addRemovedSshTargetTombstone(tombstone: RemovedSshTargetTombstone): void { + const existing = this.state.removedSshTargetTombstones ?? [] + // Why: dedupe by oldTargetId so a remove/re-remove of the same id can't + // stack duplicate tombstones. Newest wins. + const filtered = existing.filter((t) => t.oldTargetId !== tombstone.oldTargetId) + // Cap the history so pathological churn can't grow the state file unbounded. + this.state.removedSshTargetTombstones = [...filtered, tombstone].slice( + -MAX_REMOVED_SSH_TARGET_TOMBSTONES + ) + this.scheduleSave() + } + + removeRemovedSshTargetTombstone(oldTargetId: string): void { + const existing = this.state.removedSshTargetTombstones + if (!existing?.some((t) => t.oldTargetId === oldTargetId)) { + return + } + this.state.removedSshTargetTombstones = existing.filter((t) => t.oldTargetId !== oldTargetId) + this.scheduleSave() + } + + /** + * Re-point every repo and worktree meta pinned to a removed SSH target id + * onto a re-added target's id, so orphaned workspaces reattach to the live + * host instead of remaining un-removable ghosts. Returns the number of repos + * re-pointed (0 when nothing referenced the old id). + */ + reassignSshTargetId(oldTargetId: string, newTargetId: string): number { + if (oldTargetId === newTargetId) { + return 0 + } + const oldHostId = toSshExecutionHostId(oldTargetId) + const newHostId = toSshExecutionHostId(newTargetId) + let repoCount = 0 + for (const repo of this.state.repos) { + const matchesConnection = repo.connectionId === oldTargetId + const matchesHost = repo.executionHostId === oldHostId + if (!matchesConnection && !matchesHost) { + continue + } + if (matchesConnection) { + repo.connectionId = newTargetId + } + // Why: only rewrite executionHostId when it was actually set to the old + // SSH host. SSH repos created via addRemoteRepoFromPath leave it unset and + // derive the host from connectionId, so we must not stamp a value where + // there wasn't one. + if (matchesHost) { + repo.executionHostId = newHostId + } + repoCount++ + } + // Re-point worktree metas whose hostId pointed at the old SSH host. + let metaChanged = false + for (const meta of Object.values(this.state.worktreeMeta)) { + if (meta.hostId === oldHostId) { + meta.hostId = newHostId + metaChanged = true + } + } + // Why: the old id also survives in session pty ids, the startup reconnect + // list, sleeping-agent records, host setups, host-scope UI, and pty leases; + // any un-migrated carrier later throws `SSH target not found` (STA-1468). + let carrierChanged = migrateWorkspaceSessionSshTargetId( + this.state.workspaceSession, + oldTargetId, + newTargetId + ) + for (const session of Object.values(this.state.workspaceSessionsByHostId ?? {})) { + if (session && migrateWorkspaceSessionSshTargetId(session, oldTargetId, newTargetId)) { + carrierChanged = true + } + } + // Why: partitions are read by host id, so one stored under the removed id + // would be orphaned. No writer keys partitions by ssh host today, but the + // schema tolerates it — re-key rather than strand it. If the new key + // already has a partition, that one is live; drop the dead old one. + const partitions = this.state.workspaceSessionsByHostId + const oldPartition = partitions?.[oldHostId] + if (partitions && oldPartition) { + delete partitions[oldHostId] + partitions[newHostId] ??= oldPartition + carrierChanged = true + } + if (migrateUiHostScopeSshTargetId(this.state.ui, oldTargetId, newTargetId)) { + carrierChanged = true + } + for (const lease of this.state.sshRemotePtyLeases ?? []) { + if (lease.targetId === oldTargetId) { + lease.targetId = newTargetId + carrierChanged = true + } + } + let setupsChanged = false + const keptSetups: ProjectHostSetup[] = [] + for (const setup of this.state.projectHostSetups) { + if (setup.hostId !== oldHostId) { + keptSetups.push(setup) + continue + } + const duplicate = this.state.projectHostSetups.some( + (entry) => + entry !== setup && entry.projectId === setup.projectId && entry.hostId === newHostId + ) + // Why: a setup already exists for the re-added host — the old row is a + // stale ghost that would violate the (projectId, hostId) uniqueness. + if (duplicate) { + setupsChanged = true + continue + } + setup.hostId = newHostId + setup.updatedAt = Date.now() + keptSetups.push(setup) + setupsChanged = true + } + if (setupsChanged) { + this.state.projectHostSetups = keptSetups + } + // Why: repo-row and host-setup rewrites can affect host-setup compatibility, + // but meta-only rewrites cannot — keep that sync under this gate. Persist + // whenever anything changed, so partial re-points aren't lost on quit. + if (repoCount > 0 || setupsChanged) { + this.syncProjectHostSetupCompatibilityState() + } + if (repoCount > 0 || metaChanged || carrierChanged || setupsChanged) { + this.scheduleSave() + } + return repoCount + } + // ── SSH Remote PTY Leases ────────────────────────────────────────── getSshRemotePtyLeases(targetId?: string): SshRemotePtyLease[] { diff --git a/src/main/pi/legacy-omp-overlay-migration.ts b/src/main/pi/legacy-omp-overlay-migration.ts new file mode 100644 index 000000000..88baf78ea --- /dev/null +++ b/src/main/pi/legacy-omp-overlay-migration.ts @@ -0,0 +1,242 @@ +import { cpSync, lstatSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs' +import type { Dirent, Stats } from 'node:fs' +import { dirname, join } from 'node:path' +import { ORCA_PI_AGENT_STATUS_EXTENSION_FILE } from './agent-status-extension-source' +import { ORCA_PI_PREFILL_EXTENSION_FILE } from './prefill-extension-source' +import { ORCA_PI_EXTENSION_FILE } from './titlebar-extension-source' +import { isSafeDescendCandidate } from '../pty/overlay-mirror' + +const LEGACY_PI_OVERLAY_MANIFEST_FILE = '.orca-pi-overlay-manifest.json' +const LEGACY_OMP_OVERLAY_MIGRATION_MARKER_FILE = '.orca-omp-overlay-migration-complete' +const PI_AGENT_SETTINGS_FILE = 'settings.json' +const SQLITE_DATABASE_EXTENSION = '.db' +const SQLITE_SIDECAR_SUFFIXES = ['-wal', '-shm', '-journal'] as const +const MANAGED_EXTENSION_FILES = new Set([ + ORCA_PI_EXTENSION_FILE, + ORCA_PI_PREFILL_EXTENSION_FILE, + ORCA_PI_AGENT_STATUS_EXTENSION_FILE +]) + +type DeferredSidecar = { + baseTargetPath: string + entry: Dirent + nextSegments: string[] +} + +function getPathStats(path: string): Stats | undefined { + try { + return lstatSync(path) + } catch { + return undefined + } +} + +function getSqliteSidecarBaseName(name: string): string | undefined { + for (const suffix of SQLITE_SIDECAR_SUFFIXES) { + if (!name.endsWith(suffix)) { + continue + } + const baseName = name.slice(0, -suffix.length) + return baseName.endsWith(SQLITE_DATABASE_EXTENSION) ? baseName : undefined + } + return undefined +} + +function shouldSkipLegacyOverlayEntry(pathSegments: string[]): boolean { + const name = pathSegments.at(-1) + if (!name) { + return true + } + if (pathSegments.length === 1) { + return ( + name === LEGACY_PI_OVERLAY_MANIFEST_FILE || + name === LEGACY_OMP_OVERLAY_MIGRATION_MARKER_FILE || + name === PI_AGENT_SETTINGS_FILE + ) + } + return ( + pathSegments.length === 2 && + pathSegments[0] === 'extensions' && + MANAGED_EXTENSION_FILES.has(name) + ) +} + +function copyLegacyFile( + overlayPath: string, + targetPath: string, + copiedFilePaths: Set +): boolean { + if (getPathStats(targetPath)) { + return true + } + try { + mkdirSync(dirname(targetPath), { recursive: true }) + cpSync(overlayPath, targetPath, { + errorOnExist: true, + force: false, + preserveTimestamps: true + }) + copiedFilePaths.add(targetPath) + return true + } catch { + return false + } +} + +function removeCopiedFiles(paths: string[], copiedFilePaths: Set): void { + for (const path of paths) { + if (!copiedFilePaths.delete(path)) { + continue + } + try { + unlinkSync(path) + } catch { + // Best-effort: withholding the marker lets later spawns retry. + } + } +} + +function copyDeferredSidecars( + overlayDir: string, + sourceAgentDir: string, + copiedFilePaths: Set, + deferredSidecars: DeferredSidecar[] +): boolean { + let completed = true + const copiedSidecarsByBase = new Map() + for (const { baseTargetPath, entry, nextSegments } of deferredSidecars) { + if (!copiedFilePaths.has(baseTargetPath)) { + continue + } + + const overlayPath = join(overlayDir, entry.name) + const targetPath = join(sourceAgentDir, ...nextSegments) + const stats = getPathStats(overlayPath) + if (!stats) { + removeCopiedFiles( + [baseTargetPath, ...(copiedSidecarsByBase.get(baseTargetPath) ?? [])], + copiedFilePaths + ) + completed = false + continue + } + if (stats.isSymbolicLink() || !stats.isFile()) { + continue + } + const wasCopied = copiedFilePaths.has(targetPath) + if (!copyLegacyFile(overlayPath, targetPath, copiedFilePaths)) { + removeCopiedFiles( + [baseTargetPath, ...(copiedSidecarsByBase.get(baseTargetPath) ?? [])], + copiedFilePaths + ) + completed = false + continue + } + if (!wasCopied && copiedFilePaths.has(targetPath)) { + copiedSidecarsByBase.set(baseTargetPath, [ + ...(copiedSidecarsByBase.get(baseTargetPath) ?? []), + targetPath + ]) + } + } + return completed +} + +function copyMissingLegacyOmpOverlayEntries( + overlayDir: string, + sourceAgentDir: string, + pathSegments: string[] = [], + copiedFilePaths: Set = new Set() +): boolean { + let completed = true + let entries: Dirent[] + try { + entries = readdirSync(overlayDir, { withFileTypes: true }) + } catch { + return false + } + + const deferredSidecars: DeferredSidecar[] = [] + for (const entry of entries) { + const nextSegments = [...pathSegments, entry.name] + if (shouldSkipLegacyOverlayEntry(nextSegments)) { + continue + } + + const sidecarBaseName = getSqliteSidecarBaseName(entry.name) + if (sidecarBaseName) { + deferredSidecars.push({ + baseTargetPath: join(sourceAgentDir, ...pathSegments, sidecarBaseName), + entry, + nextSegments + }) + continue + } + + const overlayPath = join(overlayDir, entry.name) + const targetPath = join(sourceAgentDir, ...nextSegments) + const stats = getPathStats(overlayPath) + if (!stats) { + completed = false + continue + } + if (stats.isSymbolicLink()) { + continue + } + if (stats.isDirectory()) { + const targetStats = getPathStats(targetPath) + if (targetStats && !isSafeDescendCandidate(targetStats)) { + continue + } + if (!targetStats) { + try { + mkdirSync(targetPath, { recursive: true }) + } catch { + completed = false + continue + } + } + completed = + copyMissingLegacyOmpOverlayEntries( + overlayPath, + sourceAgentDir, + nextSegments, + copiedFilePaths + ) && completed + continue + } + if (!stats.isFile()) { + continue + } + completed = copyLegacyFile(overlayPath, targetPath, copiedFilePaths) && completed + } + + return ( + copyDeferredSidecars(overlayDir, sourceAgentDir, copiedFilePaths, deferredSidecars) && completed + ) +} + +export function migrateLegacyOmpOverlayState(sourceAgentDir: string, overlayDir: string): void { + // Why: temporary rescue shim for OMP builds from the legacy overlay window. + // Remove after 2026-08-07 once affected users have had a full upgrade window. + const overlayStats = getPathStats(overlayDir) + if (!overlayStats || overlayStats.isSymbolicLink() || !overlayStats.isDirectory()) { + return + } + const markerPath = join(overlayDir, LEGACY_OMP_OVERLAY_MIGRATION_MARKER_FILE) + if (getPathStats(markerPath)) { + return + } + try { + mkdirSync(sourceAgentDir, { recursive: true }) + // Why: some pre-managed-extension builds pointed OMP at this overlay, so + // first-login auth/session files can exist only there after an update. + if (copyMissingLegacyOmpOverlayEntries(overlayDir, sourceAgentDir)) { + // Why: legacy source overlays can be large and are intentionally kept + // for recovery; mark clean migrations so future OMP spawns stay cheap. + writeFileSync(markerPath, 'complete\n') + } + } catch (error) { + console.warn('[pi-titlebar-extension] failed to migrate legacy OMP overlay state:', error) + } +} diff --git a/src/main/pi/titlebar-extension-service.test.ts b/src/main/pi/titlebar-extension-service.test.ts index 75f015831..7516f04da 100644 --- a/src/main/pi/titlebar-extension-service.test.ts +++ b/src/main/pi/titlebar-extension-service.test.ts @@ -1,6 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { + chmodSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readFileSync, @@ -11,6 +15,7 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import type * as osModule from 'node:os' +import type * as fsModule from 'node:fs' import { join } from 'node:path' // The service calls app.getPath('userData') for its overlay root. Point that @@ -50,6 +55,12 @@ function legacyOverlayPath(kind: 'pi' | 'omp', ptyId: string): string { return join(userDataDir, rootDir, ptyId) } +function legacySourceOverlayPath(kind: 'pi' | 'omp', sourceAgentDir: string): string { + const rootDir = kind === 'pi' ? 'pi-agent-overlays' : 'omp-agent-overlays' + const hashed = createHash('sha256').update(`source:${sourceAgentDir}`).digest('hex').slice(0, 32) + return join(userDataDir, rootDir, hashed) +} + describe('PiTitlebarExtensionService', () => { let piHome: string @@ -185,6 +196,242 @@ describe('PiTitlebarExtensionService', () => { expect(readFileSync(sourcePath, 'utf-8')).toBe(content) }) + it('migrates missing OMP state from the old source overlay without overwriting source files', () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + mkdirSync(join(overlayDir, 'extensions'), { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(join(overlayDir, 'agent.db-wal'), 'legacy sqlite wal') + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + writeFileSync(join(overlayDir, 'auth.json'), 'legacy token should not overwrite') + writeFileSync(join(overlayDir, 'settings.json'), '{"overlayOnly":true}') + writeFileSync(join(overlayDir, '.orca-pi-overlay-manifest.json'), '{}') + writeFileSync(join(overlayDir, 'extensions', 'orca-agent-status.ts'), 'stale managed extension') + writeFileSync(join(overlayDir, 'extensions', 'legacy-user-ext.ts'), 'legacy user extension') + mkdirSync(join(overlayDir, 'extensions', 'legacy-package'), { recursive: true }) + writeFileSync( + join(overlayDir, 'extensions', 'legacy-package', 'orca-prefill.ts'), + 'user package file' + ) + + const svc = new PiTitlebarExtensionService() + const env = svc.buildPtyEnv('pty-omp-migrate', piHome, 'omp') + + expect(env.PI_CODING_AGENT_DIR).toBeUndefined() + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(piHome, 'agent.db-wal'), 'utf-8')).toBe('legacy sqlite wal') + expect(readFileSync(join(piHome, 'sessions', 'legacy-session.jsonl'), 'utf-8')).toBe( + 'legacy transcript' + ) + expect(readFileSync(join(piHome, 'auth.json'), 'utf-8')).toBe('secret token') + expect(JSON.parse(readFileSync(join(piHome, 'settings.json'), 'utf-8'))).toEqual({ + defaultProvider: 'amazon-bedrock', + hideThinkingBlock: false, + packages: ['npm:pi-web-access'], + terminal: { + showImages: false, + clearOnShrink: false + } + }) + expect(readFileSync(join(piHome, 'extensions', 'legacy-user-ext.ts'), 'utf-8')).toBe( + 'legacy user extension' + ) + expect( + readFileSync(join(piHome, 'extensions', 'legacy-package', 'orca-prefill.ts'), 'utf-8') + ).toBe('user package file') + expect(readFileSync(join(piHome, 'extensions', 'orca-agent-status.ts'), 'utf-8')).toContain( + '/hook/omp' + ) + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + }) + + it('does not copy stale SQLite sidecars when the target database already exists', () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(join(overlayDir, 'agent.db-wal'), 'legacy sqlite wal') + writeFileSync(join(overlayDir, 'agent.db-shm'), 'legacy sqlite shm') + writeFileSync(join(piHome, 'agent.db'), 'fresh sqlite credentials') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-stale-sidecars', piHome, 'omp') + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('fresh sqlite credentials') + expect(existsSync(join(piHome, 'agent.db-wal'))).toBe(false) + expect(existsSync(join(piHome, 'agent.db-shm'))).toBe(false) + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + }) + + it.skipIf(process.platform === 'win32')( + 'retries a legacy SQLite migration as a whole set after sidecar copy failure', + () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + const walPath = join(overlayDir, 'agent.db-wal') + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(walPath, 'legacy sqlite wal') + chmodSync(walPath, 0o000) + + try { + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-sidecar-fail-1', piHome, 'omp') + + expect(existsSync(join(piHome, 'agent.db'))).toBe(false) + expect(existsSync(join(piHome, 'agent.db-wal'))).toBe(false) + expect(existsSync(join(overlayDir, '.orca-omp-overlay-migration-complete'))).toBe(false) + + chmodSync(walPath, 0o600) + svc.buildPtyEnv('pty-omp-sidecar-fail-2', piHome, 'omp') + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(piHome, 'agent.db-wal'), 'utf-8')).toBe('legacy sqlite wal') + expect( + readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8') + ).toBe('complete\n') + } finally { + chmodSync(walPath, 0o600) + } + } + ) + + it('retries a legacy SQLite migration as a whole set after sidecar stat failure', async () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + const walPath = join(overlayDir, 'agent.db-wal') + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(walPath, 'legacy sqlite wal') + + let failNextWalStat = true + vi.resetModules() + vi.doMock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + lstatSync: (path: Parameters[0]) => { + if (String(path) === walPath && failNextWalStat) { + failNextWalStat = false + throw new Error('transient lstat failure') + } + return actual.lstatSync(path) + } + } + }) + + try { + const { migrateLegacyOmpOverlayState } = await import('./legacy-omp-overlay-migration') + migrateLegacyOmpOverlayState(piHome, overlayDir) + + expect(existsSync(join(piHome, 'agent.db'))).toBe(false) + expect(existsSync(join(piHome, 'agent.db-wal'))).toBe(false) + expect(existsSync(join(overlayDir, '.orca-omp-overlay-migration-complete'))).toBe(false) + + migrateLegacyOmpOverlayState(piHome, overlayDir) + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(piHome, 'agent.db-wal'), 'utf-8')).toBe('legacy sqlite wal') + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + } finally { + vi.doUnmock('node:fs') + vi.resetModules() + } + }) + + it('marks successful legacy OMP migrations so old overlays are not re-scanned', () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-migrate-once-1', piHome, 'omp') + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + + writeFileSync(join(overlayDir, 'later-overlay-only-file'), 'should not migrate') + svc.buildPtyEnv('pty-omp-migrate-once-2', piHome, 'omp') + + expect(existsSync(join(piHome, 'later-overlay-only-file'))).toBe(false) + }) + + it.skipIf(process.platform === 'win32')( + 'skips special legacy overlay entries while continuing the OMP migration', + () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + execFileSync('mkfifo', [join(overlayDir, 'stray-fifo')]) + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-special-entry', piHome, 'omp') + + expect(existsSync(join(piHome, 'stray-fifo'))).toBe(false) + expect(readFileSync(join(piHome, 'sessions', 'legacy-session.jsonl'), 'utf-8')).toBe( + 'legacy transcript' + ) + } + ) + + it.skipIf(process.platform === 'win32')( + 'does not descend through existing target directory symlinks while migrating OMP state', + () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + const outsideDir = mkdtempSync(join(tmpdir(), 'orca-omp-target-junction-')) + const sessionsPath = join(piHome, 'sessions') + + try { + symlinkSync(outsideDir, sessionsPath, 'dir') + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-target-dir-symlink', piHome, 'omp') + + expect(lstatSync(sessionsPath).isSymbolicLink()).toBe(true) + expect(existsSync(join(outsideDir, 'legacy-session.jsonl'))).toBe(false) + } finally { + rmSync(outsideDir, { recursive: true, force: true }) + } + } + ) + + it.skipIf(process.platform === 'win32')( + 'does not follow existing target symlinks while migrating OMP state', + () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + const outsideDir = mkdtempSync(join(tmpdir(), 'orca-omp-dangling-target-')) + + try { + const outsideTarget = join(outsideDir, 'agent.db') + symlinkSync(outsideTarget, join(piHome, 'agent.db'), 'file') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-target-symlink', piHome, 'omp') + + expect(existsSync(outsideTarget)).toBe(false) + expect(lstatSync(join(piHome, 'agent.db')).isSymbolicLink()).toBe(true) + expect(readFileSync(join(piHome, 'sessions', 'legacy-session.jsonl'), 'utf-8')).toBe( + 'legacy transcript' + ) + } finally { + rmSync(outsideDir, { recursive: true, force: true }) + } + } + ) + it('rebuilding managed extensions for the same ptyId does not corrupt the user Pi dir', () => { const svc = new PiTitlebarExtensionService() svc.buildPtyEnv('pty-3', piHome, 'pi') diff --git a/src/main/pi/titlebar-extension-service.ts b/src/main/pi/titlebar-extension-service.ts index d5b3c0a87..37d030b5e 100644 --- a/src/main/pi/titlebar-extension-service.ts +++ b/src/main/pi/titlebar-extension-service.ts @@ -17,6 +17,7 @@ import { isSafeDescendCandidate as sharedIsSafeDescendCandidate, safeRemoveOverlay } from '../pty/overlay-mirror' +import { migrateLegacyOmpOverlayState } from './legacy-omp-overlay-migration' import type { PiAgentKind } from '../../shared/pi-agent-kind' // Why: the Pi test suite imports `isSafeDescendCandidate` from this module's @@ -74,6 +75,12 @@ export class PiTitlebarExtensionService { return join(app.getPath('userData'), OVERLAY_ROOT_DIR_NAME[kind]) } + private getSourceOverlayDir(sourceAgentDir: string, kind: PiAgentKind): string { + // Why: builds before managed extensions stored Pi/OMP state in source-scoped + // overlays. Resolve the old path so OMP upgrades can rescue stranded state. + return join(this.getOverlayRoot(kind), toSafeOverlayDirName(`source:${sourceAgentDir}`)) + } + private getPtyOverlayDir(ptyId: string, kind: PiAgentKind): string { // Why: old Orca versions used PTY-scoped hashed overlays. Keep resolving // that path so new spawns/teardowns can clean stale pre-migration dirs. @@ -173,6 +180,10 @@ export class PiTitlebarExtensionService { // directory should not prevent the terminal from starting. } + if (kind === 'omp') { + migrateLegacyOmpOverlayState(sourceAgentDir, this.getSourceOverlayDir(sourceAgentDir, 'omp')) + } + const installed = this.installManagedExtensions(sourceAgentDir, kind) const env: Record = {} if (kind === 'omp') { diff --git a/src/main/providers/local-pty-shell-ready.ts b/src/main/providers/local-pty-shell-ready.ts index 978d3e94b..99d52002d 100644 --- a/src/main/providers/local-pty-shell-ready.ts +++ b/src/main/providers/local-pty-shell-ready.ts @@ -50,6 +50,10 @@ export type ShellReadySignal = { // ── Shell wrapper files ───────────────────────────────────────────── function getShellReadyWrapperRoot(): string { + // Why: this instance's userData must win over an inherited + // ORCA_USER_DATA_PATH (Orca launched from another Orca's terminal), so the + // wrapper writer root always matches the root buildPtyHostEnv hands to + // WSL children. const userDataPath = app?.getPath?.('userData') ?? process.env.ORCA_USER_DATA_PATH ?? tmpdir() return `${userDataPath}/shell-ready` } @@ -64,8 +68,8 @@ function getRequiredShellReadyWrapperPaths(root = getShellReadyWrapperRoot()): s ] } -function shellReadyWrappersExist(): boolean { - return getRequiredShellReadyWrapperPaths().every((path) => existsSync(path)) +function shellReadyWrappersExist(root = getShellReadyWrapperRoot()): boolean { + return getRequiredShellReadyWrapperPaths(root).every((path) => existsSync(path)) } // Why: if our own process inherited ZDOTDIR from a parent shell that was @@ -288,16 +292,12 @@ fi ` } -function ensureShellReadyWrappers(): void { - if (process.platform === 'win32') { - return - } - if (didEnsureShellReadyWrappers && shellReadyWrappersExist()) { +export function ensureShellReadyWrappersAt(root = getShellReadyWrapperRoot()): void { + if (didEnsureShellReadyWrappers && shellReadyWrappersExist(root)) { return } didEnsureShellReadyWrappers = true - const root = getShellReadyWrapperRoot() const zshDir = `${root}/zsh` const bashDir = `${root}/bash` @@ -365,6 +365,13 @@ ${getZshFinalZdotdirRestoreBlock()} } } +function ensureShellReadyWrappers(): void { + if (process.platform === 'win32') { + return + } + ensureShellReadyWrappersAt() +} + // ── Shell launch config ───────────────────────────────────────────── export type ShellReadyLaunchConfig = { diff --git a/src/main/providers/ssh-filesystem-provider.test.ts b/src/main/providers/ssh-filesystem-provider.test.ts index 6d4170209..d35460bd4 100644 --- a/src/main/providers/ssh-filesystem-provider.test.ts +++ b/src/main/providers/ssh-filesystem-provider.test.ts @@ -417,7 +417,11 @@ describe('SshFilesystemProvider', () => { it('listFiles sends fs.listFiles request', async () => { mux.request.mockResolvedValue(['src/index.ts', 'package.json']) const result = await provider.listFiles('/home/user/project') - expect(mux.request).toHaveBeenCalledWith('fs.listFiles', { rootPath: '/home/user/project' }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { rootPath: '/home/user/project' }, + { signal: undefined } + ) expect(result).toEqual(['src/index.ts', 'package.json']) }) @@ -426,16 +430,35 @@ describe('SshFilesystemProvider', () => { await provider.listFiles('/home/user/project', { excludePaths: ['/home/user/project/worktrees/b'] }) - expect(mux.request).toHaveBeenCalledWith('fs.listFiles', { - rootPath: '/home/user/project', - excludePaths: ['/home/user/project/worktrees/b'] - }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { + rootPath: '/home/user/project', + excludePaths: ['/home/user/project/worktrees/b'] + }, + { signal: undefined } + ) }) it('listFiles omits excludePaths when empty', async () => { mux.request.mockResolvedValue([]) await provider.listFiles('/home/user/project', { excludePaths: [] }) - expect(mux.request).toHaveBeenCalledWith('fs.listFiles', { rootPath: '/home/user/project' }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { rootPath: '/home/user/project' }, + { signal: undefined } + ) + }) + + it('listFiles forwards the cancellation signal to the mux request (#7721)', async () => { + mux.request.mockResolvedValue([]) + const controller = new AbortController() + await provider.listFiles('/home/user/project', { signal: controller.signal }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { rootPath: '/home/user/project' }, + { signal: controller.signal } + ) }) describe('watch', () => { diff --git a/src/main/providers/ssh-filesystem-provider.ts b/src/main/providers/ssh-filesystem-provider.ts index 3adeeec6c..ce5256d27 100644 --- a/src/main/providers/ssh-filesystem-provider.ts +++ b/src/main/providers/ssh-filesystem-provider.ts @@ -283,12 +283,20 @@ export class SshFilesystemProvider implements IFilesystemProvider { return (await this.mux.request('fs.search', opts)) as SearchResult } - async listFiles(rootPath: string, options?: { excludePaths?: string[] }): Promise { + async listFiles( + rootPath: string, + options?: { excludePaths?: string[]; signal?: AbortSignal } + ): Promise { const params: Record = { rootPath } if (options?.excludePaths && options.excludePaths.length > 0) { params.excludePaths = options.excludePaths } - return (await this.mux.request('fs.listFiles', params)) as string[] + // Why #7721: the signal lets a workspace switch send rpc.cancel so the + // relay aborts the full-tree scan instead of stacking abandoned scans + // that starve interactive fs.readDir/fs.stat on the shared SSH channel. + return (await this.mux.request('fs.listFiles', params, { + signal: options?.signal + })) as string[] } async watch(rootPath: string, callback: (events: FsChangeEvent[]) => void): Promise<() => void> { diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index be94599c6..657f6e498 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -240,7 +240,10 @@ export type IFilesystemProvider = { copy(source: string, destination: string): Promise realpath(filePath: string): Promise search(opts: SearchOptions): Promise - listFiles(rootPath: string, options?: { excludePaths?: string[] }): Promise + listFiles( + rootPath: string, + options?: { excludePaths?: string[]; signal?: AbortSignal } + ): Promise scanWorkspaceSpace?( rootPath: string, options?: { signal?: AbortSignal } diff --git a/src/main/providers/windows-shell-args.test.ts b/src/main/providers/windows-shell-args.test.ts index d68f4014b..7d0eeb5b4 100644 --- a/src/main/providers/windows-shell-args.test.ts +++ b/src/main/providers/windows-shell-args.test.ts @@ -1,4 +1,7 @@ -import { describe, expect, it } from 'vitest' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { encodePowerShellCommand, getPowerShellOsc133Bootstrap @@ -17,6 +20,24 @@ function expectedWslArgs(linuxCwd: string, distro?: string): string[] { } describe('resolveWindowsShellLaunchArgs', () => { + let previousUserDataPath: string | undefined + let userDataPath: string + + beforeEach(() => { + previousUserDataPath = process.env.ORCA_USER_DATA_PATH + userDataPath = mkdtempSync(join(tmpdir(), 'windows-shell-args-test-')) + process.env.ORCA_USER_DATA_PATH = userDataPath + }) + + afterEach(() => { + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + rmSync(userDataPath, { recursive: true, force: true }) + }) + it('returns cmd.exe args with chcp 65001 for UTF-8 output', () => { const result = resolveWindowsShellLaunchArgs('cmd.exe', 'C:\\Users\\alice', 'C:\\Users\\alice') expect(result.shellArgs).toEqual(['/K', 'chcp 65001 > nul']) @@ -201,6 +222,27 @@ describe('resolveWindowsShellLaunchArgs', () => { expect(result.validationCwd).toBe('C:\\Users\\alice\\code') }) + it('materializes shell-ready wrappers before building WSL shell args', () => { + const result = resolveWindowsShellLaunchArgs( + 'wsl.exe', + 'C:\\Users\\alice\\code', + 'C:\\Users\\alice' + ) + + expect(result.shellArgs).toEqual(expectedWslArgs('/mnt/c/Users/alice/code')) + expect(existsSync(join(userDataPath, 'shell-ready', 'bash', 'rcfile'))).toBe(true) + expect(existsSync(join(userDataPath, 'shell-ready', 'zsh', '.zshenv'))).toBe(true) + + // Why: the point of materializing wrappers for WSL is that a typed `omp` + // picks up Orca's status extension; pin that shim end to end. + const bashRcfile = readFileSync(join(userDataPath, 'shell-ready', 'bash', 'rcfile'), 'utf8') + const zshLogin = readFileSync(join(userDataPath, 'shell-ready', 'zsh', '.zlogin'), 'utf8') + for (const wrapperFile of [bashRcfile, zshLogin]) { + expect(wrapperFile).toContain('command omp --extension "${ORCA_OMP_STATUS_EXTENSION}" "$@"') + expect(wrapperFile).toContain('omp() { __orca_omp "$@"; }') + } + }) + it('translates MSYS drive cwd to /mnt//... for wsl.exe', () => { const result = resolveWindowsShellLaunchArgs( 'wsl.exe', diff --git a/src/main/providers/windows-shell-args.ts b/src/main/providers/windows-shell-args.ts index 98b119d85..3889edfc5 100644 --- a/src/main/providers/windows-shell-args.ts +++ b/src/main/providers/windows-shell-args.ts @@ -6,6 +6,7 @@ import { escapeWslShCommandForWindows, quotePosixShell } from '../../shared/wsl-login-shell-command' +import { ensureShellReadyWrappersAt } from './local-pty-shell-ready' import { encodePowerShellCommand, getPowerShellOsc133Bootstrap @@ -94,6 +95,7 @@ function getPowerShellEncodedCommand(startupCommand?: string): { * Builds wsl.exe arguments that enter the target directory through the distro shell. */ function buildWslShellArgs(linuxCwd: string, distro?: string): string[] { + ensureShellReadyWrappersAt() const setupCommand = [ `cd ${quotePosixShell(linuxCwd)}`, 'export PATH="$HOME/.local/bin:$PATH"', diff --git a/src/main/pty/terminal-cwd-realpath.test.ts b/src/main/pty/terminal-cwd-realpath.test.ts deleted file mode 100644 index 47110648b..000000000 --- a/src/main/pty/terminal-cwd-realpath.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, describe, expect, it } from 'vitest' -import { - canonicalizeLocalTerminalPath, - localTerminalCwdCanonicalizer -} from './terminal-cwd-realpath' - -describe('canonicalizeLocalTerminalPath', () => { - const root = mkdtempSync(join(tmpdir(), 'orca-cwd-realpath-')) - - afterAll(() => { - rmSync(root, { recursive: true, force: true }) - }) - - it('resolves symlinks to their target', () => { - const outside = join(root, 'outside') - const worktree = join(root, 'worktree') - mkdirSync(outside) - mkdirSync(worktree) - const link = join(worktree, 'escape') - symlinkSync(outside, link, 'dir') - expect(canonicalizeLocalTerminalPath(link)).toBe(canonicalizeLocalTerminalPath(outside)) - }) - - it('returns null for nonexistent paths', () => { - expect(canonicalizeLocalTerminalPath(join(root, 'does-not-exist'))).toBeNull() - }) - - it('skips WSL UNC paths instead of touching the 9P share', () => { - expect(canonicalizeLocalTerminalPath('\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo')).toBeNull() - expect(canonicalizeLocalTerminalPath('//wsl$/Ubuntu/home/jin/repo')).toBeNull() - }) -}) - -describe('localTerminalCwdCanonicalizer', () => { - it('is disabled for SSH connections and enabled locally', () => { - expect(localTerminalCwdCanonicalizer('ssh-1')).toBeUndefined() - expect(localTerminalCwdCanonicalizer(null)).toBe(canonicalizeLocalTerminalPath) - expect(localTerminalCwdCanonicalizer(undefined)).toBe(canonicalizeLocalTerminalPath) - }) -}) diff --git a/src/main/pty/terminal-cwd-realpath.ts b/src/main/pty/terminal-cwd-realpath.ts deleted file mode 100644 index f9131d9f0..000000000 --- a/src/main/pty/terminal-cwd-realpath.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { realpathSync } from 'node:fs' -import { isWslUncPath } from '../../shared/wsl-paths' - -// Why: terminal startup cwd containment is string-based; realpath closes the -// symlink escape for local paths. Only for local worktrees — SSH/remote paths -// are not resolvable on this filesystem. -export function canonicalizeLocalTerminalPath(targetPath: string): string | null { - // Why: realpath over the WSL 9P share is unreliable and can block the main - // process while the distro boots; keep the string containment check only. - if (isWslUncPath(targetPath)) { - return null - } - try { - return realpathSync.native(targetPath) - } catch { - try { - // Why: realpathSync.native can fail on network/UNC mounts where the - // JS implementation still succeeds (same fallback as git repo scanning). - return realpathSync(targetPath) - } catch { - return null - } - } -} - -export function localTerminalCwdCanonicalizer( - connectionId: string | null | undefined -): ((path: string) => string | null) | undefined { - return connectionId ? undefined : canonicalizeLocalTerminalPath -} diff --git a/src/main/pty/wsl-orca-env.test.ts b/src/main/pty/wsl-orca-env.test.ts index ec210e5db..9d7c36c6c 100644 --- a/src/main/pty/wsl-orca-env.test.ts +++ b/src/main/pty/wsl-orca-env.test.ts @@ -23,6 +23,7 @@ describe('addOrcaWslInteropEnv', () => { it('marks OMP status and hook env for Windows to WSL import', () => { const env: Record = { ORCA_TERMINAL_HANDLE: 'term_wsl', + ORCA_USER_DATA_PATH: 'C:\\Users\\jin\\AppData\\Roaming\\Orca', ORCA_OMP_STATUS_EXTENSION: 'C:\\Users\\jin\\.omp\\agent\\extensions\\orca-agent-status.ts', ORCA_PANE_KEY: 'tab-1:leaf-1', ORCA_TAB_ID: 'tab-1', @@ -36,6 +37,7 @@ describe('addOrcaWslInteropEnv', () => { addOrcaWslInteropEnv(env) expect(env.WSLENV).toContain('ORCA_TERMINAL_HANDLE/u') + expect(env.WSLENV).toContain('ORCA_USER_DATA_PATH/p') expect(env.WSLENV).toContain('ORCA_OMP_STATUS_EXTENSION/p') expect(env.WSLENV).toContain('ORCA_PANE_KEY/u') expect(env.WSLENV).toContain('ORCA_TAB_ID/u') diff --git a/src/main/pty/wsl-orca-env.ts b/src/main/pty/wsl-orca-env.ts index 2e4a878f5..40a694a87 100644 --- a/src/main/pty/wsl-orca-env.ts +++ b/src/main/pty/wsl-orca-env.ts @@ -16,10 +16,10 @@ function upsertWslenvEntry(entries: string[], entry: string): void { export function addOrcaWslInteropEnv(env: Record): void { const entries = parseWslenvEntries(env.WSLENV) - // Why: wsl.exe only imports selected Windows env vars. Agent status in WSL - // needs both the pane identity and the hook/OMP coordinates at process start. + // Why: wsl.exe only imports selected Windows env vars, so WSL needs the wrapper root, pane identity, and hook/OMP coordinates at start. const passthroughEntries = [ 'ORCA_TERMINAL_HANDLE/u', + 'ORCA_USER_DATA_PATH/p', 'ORCA_PANE_KEY/u', 'ORCA_TAB_ID/u', 'ORCA_WORKTREE_ID/u', diff --git a/src/main/runtime/mobile-presence-lock.test.ts b/src/main/runtime/mobile-presence-lock.test.ts index 56581919e..a38084c51 100644 --- a/src/main/runtime/mobile-presence-lock.test.ts +++ b/src/main/runtime/mobile-presence-lock.test.ts @@ -74,13 +74,21 @@ const store = { }) } -function createRuntime() { - const runtime = new OrcaRuntimeService(store) +// Why (#7588): the held-modal repro needs indefinite hold (null) while the +// legacy tests rely on the finite 5s default. Wrap getSettings per-test so a +// caller can pick the hold without mutating the shared stub. +function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) { + const effectiveStore = { + ...store, + getSettings: () => ({ ...store.getSettings(), mobileAutoRestoreFitMs }) + } + const runtime = new OrcaRuntimeService(effectiveStore) const ptySizes = new Map([ ['pty-1', { cols: 150, rows: 40 }] ]) const resizes: { ptyId: string; cols: number; rows: number }[] = [] const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = [] + const fitOverrideEvents: { ptyId: string; mode: string; cols: number; rows: number }[] = [] let resizeSucceeds = true runtime.setPtyController({ @@ -107,7 +115,9 @@ function createRuntime() { focusTerminal: vi.fn(), closeTerminal: vi.fn(), sleepWorktree: vi.fn(), - terminalFitOverrideChanged: vi.fn(), + terminalFitOverrideChanged: (ptyId, mode, cols, rows) => { + fitOverrideEvents.push({ ptyId, mode, cols, rows }) + }, terminalDriverChanged: (ptyId, driver) => { driverEvents.push({ ptyId, driver: { ...driver } }) } @@ -118,6 +128,7 @@ function createRuntime() { ptySizes, resizes, driverEvents, + fitOverrideEvents, setResizeSucceeds: (next: boolean) => { resizeSucceeds = next } @@ -314,11 +325,12 @@ describe('mobile presence lock — multi-mobile semantics', () => { }) it('updateMobileViewport re-fits PTY without flipping the driver', async () => { - const { runtime, ptySizes, driverEvents } = createRuntime() + const { runtime, ptySizes, driverEvents, fitOverrideEvents } = createRuntime() await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 38 }) expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 38 }) expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' }) const before = driverEvents.length + const fitEventsBefore = fitOverrideEvents.length // Keyboard opens — viewport shrinks. await expect( @@ -330,6 +342,10 @@ describe('mobile presence lock — multi-mobile semantics', () => { // Why: a viewport update may re-emit driver to refresh listener // wiring, but it must never go through `idle` (no banner flash). expect(driverEvents.slice(before).every((e) => e.driver.kind === 'mobile')).toBe(true) + // Why: phone→phone dim ticks (keyboard show/hide) are the hottest layout + // path and must not wake the renderer's fit-override listeners — the + // emit gate opens only when layout kind or override presence changes. + expect(fitOverrideEvents.length).toBe(fitEventsBefore) }) it('updateMobileViewport late-binds a viewport-less mobile subscriber', async () => { @@ -467,3 +483,252 @@ describe('mobile presence lock — multi-mobile semantics', () => { expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) }) }) + +// Why (#7588): drive the runtime into the reported held-modal state — a phone +// fit that an indefinite hold left behind, followed by a null-viewport +// resubscribe (app update / WebView reload) that re-registers an active +// subscriber with wasResizedToPhone=false while the override is still held. +// This is the state where the desktop "Your phone left this at phone size" +// modal's Restore buttons used to silently no-op. +async function reachHeldModalWithNullViewportResubscribe( + runtime: OrcaRuntimeService +): Promise { + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + runtime.handleMobileUnsubscribe('pty-1', 'phone-A') + await vi.advanceTimersByTimeAsync(300) + // Production RPC passes `params.viewport` straight through, so a client + // that hasn't measured yet arrives here as `undefined`. + await runtime.handleMobileSubscribe('pty-1', 'phone-A', undefined) +} + +describe('mobile presence lock — issue #7588 held-modal restore convergence', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => vi.useRealTimers()) + + // Scenario 1: the reported repro end-to-end. Restore must converge and + // notify BOTH the renderer notifier and a runtime listener (paired), since + // remote/web viewers ride the listener channel. + it('reclaim after a null-viewport resubscribe restores dims, clears override, notifies both channels', async () => { + const { runtime, ptySizes, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await reachHeldModalWithNullViewportResubscribe(runtime) + // Held state: driver idle, override still present, phone-sized PTY. + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' }) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 }) + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 2: a second click after success is an idempotent no-op. The + // persistent null-viewport subscriber keeps reclaim in the active-subscriber + // branch; assert only "returns true, no new PTY resize, no new fit-override + // event" — a benign mobile-facing mode-change notify is acceptable. + it('second Restore click after success returns true with no new resize or fit-override event', async () => { + const { runtime, resizes, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await reachHeldModalWithNullViewportResubscribe(runtime) + expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true) + + const resizeCount = resizes.length + const notifierCount = fitOverrideEvents.length + const listenerCount = listenerEvents.length + + expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true) + expect(resizes.length).toBe(resizeCount) + expect(fitOverrideEvents.length).toBe(notifierCount) + expect(listenerEvents.length).toBe(listenerCount) + }) + + // Scenario 3: the existing driving take-back is unregressed — a phone that is + // actively driving (wasResizedToPhone=true) still flips to desktop, clears + // the override, and notifies both channels. + it('driving take-back still converges: driver → desktop, override cleared, both channels notified', async () => { + const { runtime, ptySizes, fitOverrideEvents } = createRuntime() + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + expect(runtime.getDriver('pty-1').kind).toBe('mobile') + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'desktop' }) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) + expect(fitOverrideEvents.some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 4: a failing resize during a HELD (no-subscriber) restore returns + // false and keeps the override — no lying, no phantom desktop-fit event. + it('held restore with a failing resize returns false and keeps the override', async () => { + const { runtime, fitOverrideEvents, setResizeSucceeds } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + // Last leaver under indefinite hold → override held, no active subscriber. + runtime.handleMobileUnsubscribe('pty-1', 'phone-A') + await vi.advanceTimersByTimeAsync(300) + expect(runtime.isMobileSubscriberActive('pty-1')).toBe(false) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + setResizeSucceeds(false) + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(false) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe( + false + ) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(false) + }) + + // Scenario 5: a failing resize during an ACTIVE-SUBSCRIBER take-back returns + // false, keeps the override, leaves the driver on its mobile lock, and + // restores the prior display mode ('auto') — the fix #3 P1 correction. + it('active-subscriber take-back with a failing resize returns false and preserves the mobile lock', async () => { + const { runtime, fitOverrideEvents, setResizeSucceeds } = createRuntime() + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' }) + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + setResizeSucceeds(false) + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(false) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + // Driver stays mobile (lock retained) and mode is not left lying at 'desktop'. + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' }) + expect(runtime.getMobileDisplayMode('pty-1')).toBe('auto') + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe( + false + ) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(false) + }) + + // Scenario 5b: after a FAILED active-subscriber take-back, wasResizedToPhone + // must be re-armed so a later unsubscribe under a finite auto-restore setting + // still schedules its timer and eventually clears the override. Without the + // re-arm the flag would be stuck false and the phone-fit would strand. + it('failed take-back re-arms wasResizedToPhone so a later unsubscribe still auto-restores', async () => { + // Finite auto-restore (5s default from the rig store). + const { runtime, ptySizes, setResizeSucceeds } = createRuntime() + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 }) + + // Take-back fails → false, flag re-armed, mode rolled back to 'auto'. + setResizeSucceeds(false) + expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(false) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + // Phone then leaves the terminal. Resize works again for the auto-restore. + setResizeSucceeds(true) + runtime.handleMobileUnsubscribe('pty-1', 'phone-A') + // Soft-leave grace, then the finite auto-restore timer. + await vi.advanceTimersByTimeAsync(300) + await vi.advanceTimersByTimeAsync(5_000) + + // The scheduled auto-restore fired: override cleared, PTY back to desktop. + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) + }) + + // Scenario 6: a phone-initiated setDisplayMode('desktop') against a stale + // held override converges through the shared applyMobileDisplayMode seam. + it('phone-initiated setDisplayMode(desktop) against a stale held override converges', async () => { + const { runtime, ptySizes, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await reachHeldModalWithNullViewportResubscribe(runtime) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + + runtime.setMobileDisplayMode('pty-1', 'desktop') + const converged = await runtime.applyMobileDisplayMode('pty-1') + + expect(converged).toBe(true) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 7 (white-box): a held override whose `layouts` entry is gone is + // unreachable via public APIs (onPtyExit deletes both in lockstep), so seed + // it directly. Reclaim must still delete the override and emit a paired + // desktop-fit 0×0 rather than stranding the modal on the next hydrate. + it('orphan cleanup: reclaim on a held override with no layout entry converges', async () => { + const { runtime, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + const internal = runtime as unknown as { + terminalFitOverrides: Map< + string, + { + mode: string + cols: number + rows: number + previousCols: number | null + previousRows: number | null + updatedAt: number + clientId: string + } + > + } + internal.terminalFitOverrides.set('pty-1', { + mode: 'mobile-fit', + cols: 45, + rows: 20, + previousCols: 150, + previousRows: 40, + updatedAt: Date.now(), + clientId: 'phone-A' + }) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(fitOverrideEvents.find((e) => e.mode === 'desktop-fit')).toEqual({ + ptyId: 'pty-1', + mode: 'desktop-fit', + cols: 0, + rows: 0 + }) + expect(listenerEvents.find((e) => e.mode === 'desktop-fit')).toEqual({ + mode: 'desktop-fit', + cols: 0, + rows: 0 + }) + }) +}) diff --git a/src/main/runtime/orca-runtime-terminal-cwd.test.ts b/src/main/runtime/orca-runtime-terminal-cwd.test.ts index 214d2a208..976b8169f 100644 --- a/src/main/runtime/orca-runtime-terminal-cwd.test.ts +++ b/src/main/runtime/orca-runtime-terminal-cwd.test.ts @@ -52,7 +52,7 @@ describe('OrcaRuntimeService terminal startup cwd', () => { ) }) - it('rejects requested terminal cwd values outside the selected worktree', async () => { + it('spawns terminals at a requested cwd outside the selected worktree (#7685)', async () => { const runtime = new OrcaRuntimeService() stubLaunchScope(runtime) const spawn = vi.fn().mockResolvedValue({ id: 'pty-1' }) @@ -63,10 +63,14 @@ describe('OrcaRuntimeService terminal startup cwd', () => { getForegroundProcess: async () => null }) - await expect(runtime.createTerminal('id:wt-1', { cwd: '/repo/app-other' })).rejects.toThrow( - 'Terminal cwd must be inside the selected worktree.' + await runtime.createTerminal('id:wt-1', { cwd: '/repo/app-other' }) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: '/repo/app-other', + worktreeId: 'wt-1' + }) ) - expect(spawn).not.toHaveBeenCalled() }) it('reveals main-spawned terminals with their nested startup cwd', async () => { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 67b9225cf..d8bed8ec4 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -5,6 +5,7 @@ import { performance } from 'node:perf_hooks' import { EventEmitter } from 'node:events' import { randomUUID } from 'node:crypto' import { execFileSync } from 'node:child_process' +import { mkdirSync } from 'node:fs' import { lstat, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' @@ -61,7 +62,13 @@ import { TERMINAL_INPUT_MAX_BYTES, TERMINAL_INPUT_TOO_LARGE_ERROR } from '../../shared/terminal-input' +import { + AGENT_PROMPT_BRACKETED_PASTE_END, + AGENT_PROMPT_BRACKETED_PASTE_START, + buildAgentPromptPasteBytes +} from '../../shared/agent-prompt-injection' import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../shared/clipboard-text' +import { projectHostSetupProjectionFromRepos } from '../../shared/project-host-setup-projection' import { registerSshFilesystemProvider, unregisterSshFilesystemProvider @@ -5251,6 +5258,406 @@ describe('OrcaRuntimeService', () => { } }) + it('keeps existing-folder imports split by runtime host on the same normalized path', async () => { + const tempRoot = await mkdtemp(join(tmpdir(), 'orca-runtime-project-host-')) + const repos: Record[] = [] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + execFileSync('git', ['init'], { cwd: tempRoot, stdio: 'ignore' }) + const first = await runtime.setupProjectExistingFolder({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-1', + path: tempRoot, + kind: 'git', + setupMethod: 'imported-existing-folder' + }) + const second = await runtime.setupProjectExistingFolder({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-2', + path: tempRoot, + kind: 'git', + setupMethod: 'imported-existing-folder' + }) + + expect(repos).toHaveLength(2) + expect(repos).toEqual([ + expect.objectContaining({ + path: tempRoot, + executionHostId: 'runtime:env-1' + }), + expect.objectContaining({ + path: tempRoot, + executionHostId: 'runtime:env-2' + }) + ]) + expect(first.repo).toMatchObject({ + path: tempRoot, + executionHostId: 'runtime:env-1' + }) + expect(first.setup).toMatchObject({ + repoId: first.repo.id, + hostId: 'runtime:env-1' + }) + expect(second.repo).toMatchObject({ + path: tempRoot, + executionHostId: 'runtime:env-2' + }) + expect(second.setup).toMatchObject({ + repoId: second.repo.id, + hostId: 'runtime:env-2' + }) + expect(first.repo.id).not.toBe(second.repo.id) + expect(first.setup.repoId).not.toBe(second.setup.repoId) + } finally { + await rm(tempRoot, { recursive: true, force: true }) + } + }) + + it('keeps path-only runtime addRepo reuse working when a host-qualified repo already exists', async () => { + const repos: Record[] = [ + { + id: 'repo-runtime-1', + path: '/tmp/runtime-shared', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + kind: 'folder', + executionHostId: 'runtime:env-1' + } + ] + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const repo = await runtime.addRepo('/tmp/runtime-shared', 'folder') + + expect(repo).toMatchObject({ + id: 'repo-runtime-1', + path: '/tmp/runtime-shared', + executionHostId: 'runtime:env-1' + }) + expect(repos).toHaveLength(1) + }) + + it('does not hijack a legacy SSH repo at the same path into a runtime host', async () => { + // A legacy SSH repo resolves to `ssh:` even with a null executionHostId, + // so a same-path runtime import must create a new repo instead of adopting it. + const repos: Record[] = [ + { + id: 'repo-ssh-1', + path: '/workspace', + displayName: 'workspace', + badgeColor: 'blue', + addedAt: 1, + kind: 'folder', + connectionId: 'ssh-target-1' + } + ] + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + } + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const repo = await runtime.addRepo('/workspace', 'folder', 'runtime:env-1') + + expect(repos).toHaveLength(2) + expect(repo.id).not.toBe('repo-ssh-1') + expect(repo).toMatchObject({ path: '/workspace', executionHostId: 'runtime:env-1' }) + // The legacy SSH repo must be untouched (no executionHostId stamped onto it). + expect(repos[0]).toMatchObject({ id: 'repo-ssh-1', connectionId: 'ssh-target-1' }) + expect(repos[0]).not.toHaveProperty('executionHostId') + }) + + it('only a runtime host adopts an unstamped repo; local/ssh imports never stamp it', async () => { + // A genuine local repo is indistinguishable from a legacy runtime repo (both have null + // executionHostId and connectionId). Only a runtime host may backfill it — a local or ssh + // import at the same path must leave it untouched rather than re-attribute it to that host. + for (const importHostId of ['local', 'ssh:ssh-target-9'] as const) { + const repos: Record[] = [ + { + id: 'repo-local-1', + path: '/workspace', + displayName: 'workspace', + badgeColor: 'blue', + addedAt: 1, + kind: 'folder' + } + ] + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + } + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const repo = await runtime.addRepo('/workspace', 'folder', importHostId) + + // The matched repo is returned unchanged — no new repo, no executionHostId stamped. + expect(repos).toHaveLength(1) + expect(repo.id).toBe('repo-local-1') + expect(repos[0]).not.toHaveProperty('executionHostId') + } + }) + + it('keeps project clone setup on the cloned host-qualified repo', async () => { + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-project-clone-')) + const clonePath = join(destination, 'orca') + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const repos: Record[] = [] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never + } + spawnSpy.mockImplementation(() => { + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + queueMicrotask(() => { + mkdirSync(clonePath, { recursive: true }) + execFileSync('git', ['init'], { cwd: clonePath, stdio: 'ignore' }) + proc.emit('close', 0, null) + }) + return proc as never + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + const result = await runtime.setupProjectClone({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-1', + url: 'https://example.com/orca.git', + destination + }) + + expect(repos).toHaveLength(1) + expect(result.repo).toMatchObject({ + path: clonePath, + executionHostId: 'runtime:env-1', + projectHostSetupMethod: 'cloned' + }) + expect(result.setup).toMatchObject({ + repoId: result.repo.id, + hostId: 'runtime:env-1', + setupMethod: 'cloned' + }) + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('adopts public clone repos into host-qualified project setup', async () => { + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-project-clone-')) + const clonePath = join(destination, 'orca') + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const repos: Record[] = [] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never + } + spawnSpy.mockImplementation(() => { + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + queueMicrotask(() => { + mkdirSync(clonePath, { recursive: true }) + execFileSync('git', ['init'], { cwd: clonePath, stdio: 'ignore' }) + proc.emit('close', 0, null) + }) + return proc as never + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + const cloned = await runtime.cloneRepo('https://example.com/orca.git', destination) + expect(cloned).toMatchObject({ + path: clonePath + }) + expect(cloned).not.toHaveProperty('executionHostId') + + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-1', + path: clonePath, + kind: 'git', + setupMethod: 'cloned' + }) + + expect(repos).toHaveLength(1) + expect(result.repo).toMatchObject({ + id: cloned.id, + path: clonePath, + executionHostId: 'runtime:env-1', + projectHostSetupMethod: 'cloned' + }) + expect(result.setup).toMatchObject({ + repoId: cloned.id, + hostId: 'runtime:env-1', + setupMethod: 'cloned' + }) + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('keeps project clone repos split by runtime host on the same clone path', async () => { + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-project-clone-')) + const clonePath = join(destination, 'orca') + const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const repos: Record[] = [ + { + id: 'repo-host-a', + path: clonePath, + displayName: 'orca', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1' + } + ] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never + } + spawnSpy.mockImplementation(() => { + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + queueMicrotask(() => { + mkdirSync(clonePath, { recursive: true }) + execFileSync('git', ['init'], { cwd: clonePath, stdio: 'ignore' }) + proc.emit('close', 0, null) + }) + return proc as never + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + const result = await runtime.setupProjectClone({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-2', + url: 'https://example.com/orca.git', + destination + }) + + expect(repos).toHaveLength(2) + expect(repos[0]).toMatchObject({ + id: 'repo-host-a', + executionHostId: 'runtime:env-1' + }) + expect(result.repo).toMatchObject({ + path: clonePath, + executionHostId: 'runtime:env-2' + }) + expect(result.repo.id).not.toBe('repo-host-a') + expect(result.setup).toMatchObject({ + repoId: result.repo.id, + hostId: 'runtime:env-2', + setupMethod: 'cloned' + }) + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + it('defaults runtime createRepo badgeColor to DEFAULT_REPO_BADGE_COLOR', async () => { const added: Record[] = [] const colorStore = { @@ -9947,6 +10354,110 @@ describe('OrcaRuntimeService', () => { expect(writes).toEqual(['continue', '\r']) }) + it('sends agent prompts as bracketed paste before submit', async () => { + vi.useFakeTimers() + try { + const writes: string[] = [] + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), + write: (_ptyId, data) => { + writes.push(data) + return true + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + const prompt = 'line one\nline two\x1b[201~' + + const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt) + await vi.runAllTimersAsync() + const result = await sendPromise + + const pasted = [ + AGENT_PROMPT_BRACKETED_PASTE_START, + 'line one\nline two[201~', + AGENT_PROMPT_BRACKETED_PASTE_END + ].join('') + expect(result).toMatchObject({ + handle, + accepted: true, + bytesWritten: Buffer.byteLength(`${pasted}\r`, 'utf8') + }) + expect(writes).toEqual([pasted, '\r']) + } finally { + vi.useRealTimers() + } + }) + + it('chunks large agent prompt paste frames before delayed submit', async () => { + vi.useFakeTimers() + try { + const writes: string[] = [] + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), + write: (_ptyId, data) => { + writes.push(data) + return true + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + const prompt = `${'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES)}\ntail` + + const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt) + await vi.runAllTimersAsync() + const result = await sendPromise + + const pasteWrites = writes.slice(0, -1) + expect(result.bytesWritten).toBe( + Buffer.byteLength(`${buildAgentPromptPasteBytes(prompt)}\r`, 'utf8') + ) + expect(writes.at(-1)).toBe('\r') + expect(pasteWrites.length).toBeGreaterThan(1) + expect(pasteWrites.join('')).toBe(buildAgentPromptPasteBytes(prompt)) + expect(pasteWrites[0]).toContain(AGENT_PROMPT_BRACKETED_PASTE_START) + expect(pasteWrites.at(-1)).toContain(AGENT_PROMPT_BRACKETED_PASTE_END) + } finally { + vi.useRealTimers() + } + }) + + it('closes an incomplete agent prompt paste when a later chunk write fails', async () => { + vi.useFakeTimers() + try { + const writes: string[] = [] + let writeCount = 0 + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), + write: (_ptyId, data) => { + writeCount += 1 + writes.push(data) + return writeCount !== 2 + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + const prompt = 'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES + 1) + + const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt) + const sendRejection = expect(sendPromise).rejects.toThrow('terminal_not_writable') + await vi.runAllTimersAsync() + + await sendRejection + expect(writes[0]).toContain(AGENT_PROMPT_BRACKETED_PASTE_START) + expect(writes.at(-1)).toBe(AGENT_PROMPT_BRACKETED_PASTE_END) + expect(writes).not.toContain('\r') + } finally { + vi.useRealTimers() + } + }) + it('chunks large terminal.send text before provider writes', async () => { const writes: string[] = [] const runtime = new OrcaRuntimeService(store) @@ -18606,6 +19117,413 @@ describe('OrcaRuntimeService', () => { } }) + // Why: the five #7587 mobile-create tests need an identical full notifier where + // only closeTerminal is observed; one factory keeps notifier-interface changes + // in a single place. + function createMobileCreateTestNotifier( + closeTerminal: (tabId: string, paneRuntimeId?: number) => void + ) { + return { + focusTerminal: vi.fn(), + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn(), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + closeTerminal, + closeSessionTab: vi.fn(), + sleepWorktree: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + } + } + + it('rolls back a mobile create when the materialize spawn fails and no live PTY backs the tab', async () => { + vi.useFakeTimers() + try { + const pendingLeafId = '99999999-9999-4999-8999-999999999999' + const closeTerminal = vi.fn() + // Why: the renderer publishes a handle-less shell surface (no ptyId) and the + // runtime materialize spawn then fails, so NO live PTY ever backs the tab. + // The catch must roll back — the #7587 rescue is gated on a live PTY, not on + // the mere presence of a surface, or a dead shell would resolve as success. + const spawn = vi.fn().mockRejectedValue(new Error('spawn failed')) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-pending', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // Only the tab shell publishes (no ptyId → never ready); no PTY ever binds. + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer-pending', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: `tab-pending::${pendingLeafId}`, + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: `tab-pending::${pendingLeafId}`, + parentTabId: 'tab-pending', + leafId: pendingLeafId, + title: 'Terminal', + isActive: true + } + ] + } + ] + }) + + // Ready-fallback (1s) expires → materialize runs → spawn rejects → catch. + await vi.advanceTimersByTimeAsync(2_000) + const outcome = await settled + + expect(outcome.ok).toBe(false) + expect(closeTerminal).toHaveBeenCalledWith('tab-pending') + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when the renderer never publishes the surface', async () => { + vi.useFakeTimers() + try { + const leafId = '44444444-4444-4444-8444-444444444444' + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + // Why: reply with a tabId but NEVER sync a matching mobileSessionTabs graph, + // reproducing a throttled/hidden renderer that spawns the PTY yet stalls its + // graph-sync publication past the surface timeout (#7587). + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-alive', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // The renderer's own PTY spawn registers with the tab binding — the same + // call the pty IPC layer now makes — without any mobileSessionTabs sync. + runtime.registerPty('pty-alive', TEST_WORKTREE_ID, null, { + tabId: 'tab-alive', + leafId + }) + + // Resolves promptly, well under MOBILE_TERMINAL_SURFACE_TIMEOUT_MS (10s). + await vi.advanceTimersByTimeAsync(50) + const result = await settledCreate + + expect(settled).toBe(true) + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-alive', + leafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when the renderer PTY spawn races ahead of the reply', async () => { + vi.useFakeTimers() + try { + const leafId = '55555555-5555-4555-8555-555555555555' + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + // Why: the spawn and the tabCreate reply travel independent IPC channels; + // here the renderer registers the live PTY before it replies, so only the + // create's immediate pre-wait check can resolve it — asserting it settles + // well under the surface timeout pins that site, not the catch backstop. + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + runtime.registerPty('pty-early', TEST_WORKTREE_ID, null, { + tabId: 'tab-early', + leafId + }) + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-early', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // Resolves via the immediate pre-wait rescue, well under the 10s timeout; + // reverting that site would only resolve later through the catch path. + await vi.advanceTimersByTimeAsync(50) + expect(settled).toBe(true) + const result = await settledCreate + + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-early', + leafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when the renderer snapshot is rejected by the version guard', async () => { + vi.useFakeTimers() + try { + const leafId = '66666666-6666-4666-8666-666666666666' + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-guard', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + // Why: seed an inflated stored version under a stable epoch (no headless / + // serve-owned tabs, so the preserve-merge can't lift the version via + // Math.max) — this is the state prior renderer publications leave behind. + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-guard', + snapshotVersion: 50, + activeGroupId: 'group-guard', + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // The renderer publishes the new tab, but with a stale (lower) version + // under the same epoch, so syncMobileSessionTabs rejects it and the surface + // never lands via graph-sync — the reporter's exact stall variant (#7587). + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-guard', + snapshotVersion: 1, + activeGroupId: 'group-guard', + activeTabId: `tab-guard::${leafId}`, + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: `tab-guard::${leafId}`, + parentTabId: 'tab-guard', + leafId, + title: 'Terminal', + isActive: true + } + ] + } + ] + }) + await vi.advanceTimersByTimeAsync(50) + // The rejected renderer sync must not have resolved the create. + expect(settled).toBe(false) + // Prove the rejection: the stored snapshot still lacks the tab. + const beforeRescue = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + expect( + beforeRescue.tabs.some((tab) => tab.type === 'terminal' && tab.parentTabId === 'tab-guard') + ).toBe(false) + + // The renderer's own PTY spawn registers with the binding and rescues it. + runtime.registerPty('pty-guard', TEST_WORKTREE_ID, null, { + tabId: 'tab-guard', + leafId + }) + await vi.advanceTimersByTimeAsync(50) + const result = await settledCreate + + expect(settled).toBe(true) + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-guard', + leafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive at the surface timeout when only a leaf-synced PTY backs the tab', async () => { + vi.useFakeTimers() + try { + const leafId = '77777777-7777-4777-8777-777777777777' + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + // Why: the renderer pane identity can reach the runtime via leaf graph-sync + // (recordPtyWorktree) without registerPty, and leaf-sync never calls the + // pty-backed rescue; so when the mobileSessionTabs publication stalls past + // the surface timeout, only the catch-path rescue saves the live session — + // this pins the third #7587 rescue site, which the other tests never reach. + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-catch', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // Let the create clear its immediate pre-wait check (no live PTY yet) and + // park in waitForMobileTerminalSurface before any identity arrives. + await vi.advanceTimersByTimeAsync(50) + + // Renderer pane identity arrives via leaf graph-sync — NOT registerPty — so + // no rescue fires here, and the mobileSessionTabs surface is never published. + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'tab-catch', + worktreeId: TEST_WORKTREE_ID, + leafId, + paneRuntimeId: 1, + ptyId: 'pty-catch' + } + ] + }) + + // Surface still unpublished, so the create is still pending. + expect(settled).toBe(false) + + // Cross MOBILE_TERMINAL_SURFACE_TIMEOUT_MS (10s): the catch path must rescue + // from the live PTY instead of rolling the session back destructively. + await vi.advanceTimersByTimeAsync(11_000) + const result = await settledCreate + + expect(settled).toBe(true) + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-catch', + leafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + it('reports browser tab creation as unsupported for a windowless host with no offscreen backend', async () => { const runtime = new OrcaRuntimeService(store) runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) @@ -26628,4 +27546,226 @@ describe('OrcaRuntimeService', () => { expect(preDaemonProvider.shutdown).not.toHaveBeenCalled() }) }) + describe('stale terminal handle resolution (#7718)', () => { + function syncSingleTerminalGraph(runtime: OrcaRuntimeService, ptyId: string): void { + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + title: 'Terminal 1', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId, + paneTitle: 'Terminal 1' + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: 'tab-1::pane:1', + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: 'tab-1::pane:1', + parentTabId: 'tab-1', + leafId: 'pane:1', + title: 'Terminal 1', + isActive: true + } + ] + } + ] + }) + } + + // Why: session-tab mirrors travel as PTY handles, but client-created + // terminals (terminal.create) hold LEAF handles — the kind that can + // diverge from the pane's current PTY across reconnects. Issue one + // directly from the leaf record to pin the resolver semantics. + function issueLeafHandle(runtime: OrcaRuntimeService, ptyId: string): string { + const internals = runtime as unknown as { + leaves: Map + issueHandle: (leaf: unknown) => string + } + const leaf = Array.from(internals.leaves.values()).find( + (candidate) => candidate.ptyId === ptyId + ) + if (!leaf) { + throw new Error('expected leaf record') + } + return internals.issueHandle(leaf) + } + + it('errors with terminal_handle_stale instead of adopting a replacement PTY', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.attachWindow(1) + syncSingleTerminalGraph(runtime, 'pty-a') + const handle = issueLeafHandle(runtime, 'pty-a') + + // Simulate the pane's PTY being replaced while the remote client still + // holds the old handle (the record missed the swap, e.g. across a + // renderer graph reload that preserved live PTY records). + const internals = runtime as unknown as { + leaves: Map + } + for (const leaf of internals.leaves.values()) { + if (leaf.ptyId === 'pty-a') { + leaf.ptyId = 'pty-b' + } + } + + // The unguarded resolver silently adopts the new PTY — the misroute. + expect(runtime.resolveLeafForHandle(handle)).toEqual({ ptyId: 'pty-b' }) + // The guarded resolver surfaces the staleness so clients can re-derive. + expect(() => runtime.resolveLiveLeafForHandle(handle)).toThrow('terminal_handle_stale') + }) + + it('lets a handle issued before its first PTY adopt that PTY without erroring', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.attachWindow(1) + syncSingleTerminalGraph(runtime, 'pty-a') + const handle = issueLeafHandle(runtime, 'pty-a') + + // Simulate the mobile pre-spawn flow: the handle record predates the + // PTY (ptyId null); the pane's first PTY must still resolve. + const internals = runtime as unknown as { + handles: Map + } + const record = internals.handles.get(handle) + if (!record) { + throw new Error('expected handle record') + } + record.ptyId = null + + expect(runtime.resolveLiveLeafForHandle(handle)).toEqual({ ptyId: 'pty-a' }) + }) + }) + + describe('mobile terminal create resilience (#7718)', () => { + it('cancels the surface wait without rolling back when the client connection dies', async () => { + vi.useFakeTimers() + try { + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const abort = new AbortController() + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-abort', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false, + signal: abort.signal + }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // The client's socket dies mid-wait. The create must settle right away + // (not run down the 10s surface timeout) and must NOT close the tab — + // the renderer spawned a real terminal the host user can see. + abort.abort() + await vi.advanceTimersByTimeAsync(0) + const outcome = await settled + + expect(outcome.ok).toBe(false) + if (outcome.ok === false) { + expect(outcome.error.message).toBe('client_disconnected') + } + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when its live shell has no registered pane key', async () => { + vi.useFakeTimers() + try { + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-stall', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false + }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // A live shell backs the tab, but its leaf id is not a terminal UUID + // so no pane key registers: the surface rescue can't publish it, and + // the surface itself never publishes (stalled renderer publication). + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'tab-stall', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-stall', + paneTitle: null + } + ] + }) + + await vi.advanceTimersByTimeAsync(11_000) + const outcome = await settled + + // The create still fails (nothing to return), but the timeout must not + // kill the live terminal — that is the "tab dies after ~10s" symptom. + expect(outcome.ok).toBe(false) + if (outcome.ok === false) { + expect(outcome.error.message).toContain('Timed out') + } + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + }) }) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index d60a4764c..3b2753a42 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -46,6 +46,12 @@ import { TERMINAL_INPUT_TOO_LARGE_ERROR, iterateTerminalInputChunks } from '../../shared/terminal-input' +import { + AGENT_PROMPT_BRACKETED_PASTE_END, + AGENT_PROMPT_SUBMIT, + AGENT_PROMPT_SUBMIT_DELAY_MS, + buildAgentPromptPasteBytes +} from '../../shared/agent-prompt-injection' import { gitExecFileAsync, wslAwareSpawn } from '../git/runner' import { cleanupClaimedCloneTarget, @@ -132,9 +138,11 @@ import type { WorkspaceSessionState, DirEntry } from '../../shared/types' +import { parseExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' import type { SleepingAgentLaunchConfig } from '../../shared/agent-session-resume' import type { RuntimeClientEvent } from '../../shared/runtime-client-events' import { toRuntimeActivateWorktreeEvent } from '../../shared/runtime-client-events' +import type { SshConnectionState } from '../../shared/ssh-types' import type { LinearCurrentIssueContextHints, LinearAttachResult, @@ -187,7 +195,7 @@ import { TASK_PROVIDERS } from '../../shared/task-providers' import { FIRST_PANE_ID } from '../../shared/pane-key' import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../shared/stable-pane-id' import { parseAppSshPtyId } from '../../shared/ssh-pty-id' -import { isValidHostTerminalTabId } from '../../shared/terminal-tab-id' +import { isValidHostTerminalTabId, isValidTerminalTabId } from '../../shared/terminal-tab-id' import { buildAgentDraftLaunchPlan, buildAgentStartupPlan } from '../../shared/tui-agent-startup' import { repoIsRemote } from '../../shared/agent-launch-remote' import { @@ -221,7 +229,6 @@ import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' import { resolveTerminalStartupCwd } from '../../shared/terminal-startup-cwd' -import { localTerminalCwdCanonicalizer } from '../pty/terminal-cwd-realpath' import { isWslUncPath } from '../../shared/wsl-paths' import { folderWorkspaceKey, @@ -1234,6 +1241,10 @@ const RECENT_PTY_PATH_CANDIDATE_LIMIT = 1024 const RECENT_PTY_PATH_CANDIDATE_MAX_BYTES = 4 * 1024 const RECENT_PTY_PATH_CANDIDATE_TOTAL_BYTES = 64 * 1024 +function isClientDisconnectedError(error: unknown): boolean { + return error instanceof Error && error.message === 'client_disconnected' +} + function createTerminalRevealWarning(handle: string, error?: unknown): string { const reason = error instanceof Error && error.message.trim().length > 0 @@ -1466,6 +1477,22 @@ function getRuntimeFolderWorkspaceRootId(repo: Repo): string { return `${repo.id}::${repo.path}` } +// Null executionHostId means host-unaware: path-only callers match any repo, and the first runtime +// host can adopt a legacy (unstamped) repo. But an unstamped repo with a connectionId is an SSH repo +// (resolves to ssh:), so it must not be adopted/matched by a runtime host at the same path. +function runtimeRepoMatchesExecutionHost( + repo: Pick, + executionHostId?: ExecutionHostId | null +): boolean { + if (executionHostId == null) { + return true + } + if (repo.executionHostId != null) { + return repo.executionHostId === executionHostId + } + return repo.connectionId == null +} + function getRuntimeFolderWorkspaceInstanceId(repo: Repo, instanceId: string): string { return `${getRuntimeFolderWorkspaceRootId(repo)}${FOLDER_WORKSPACE_INSTANCE_SEPARATOR}${instanceId}` } @@ -2068,6 +2095,15 @@ export class OrcaRuntimeService { string, Promise >() + // Why: a mobile create waits for the renderer to publish the new tab's surface + // via graph-sync, but a throttled/hidden renderer can park that past the surface + // timeout and the create would then destroy the live PTY (#7587). This lets the + // renderer's own PTY spawn publish the surface main-side, scoped to in-flight + // creates so ordinary renderer spawns never publish here. + private pendingMobileTerminalCreatesByKey = new Map< + string, + { activate: boolean; selectIfNoActiveTab: boolean } + >() private mobileSessionTabListeners = new Set<(snapshot: RuntimeMobileSessionTabsResult) => void>() private leaves = new Map() // Why: PTY output is a per-keystroke hot path. Looking up affected leaves by @@ -2883,6 +2919,12 @@ export class OrcaRuntimeService { this.emitClientEvent({ type: 'reposChanged' }) } + // Why: SSH state changes originate in main's ssh handlers, not in runtime + // methods, so they need a public entry point onto the client-event stream. + notifySshStateChanged(targetId: string, state: SshConnectionState): void { + this.emitClientEvent({ type: 'sshStateChanged', targetId, state }) + } + private notifyActivateWorktree( repoId: string, worktreeId: string, @@ -5321,8 +5363,28 @@ export class OrcaRuntimeService { } } - registerPty(ptyId: string, worktreeId: string, connectionId: string | null = null): void { - this.recordPtyWorktree(ptyId, worktreeId, { connected: true, connectionId }) + registerPty( + ptyId: string, + worktreeId: string, + connectionId: string | null = null, + binding?: { tabId: string; leafId: string } + ): void { + // Why: record the renderer pane identity at spawn time so a stalled graph + // sync can't hide that a live PTY already backs a pending mobile create. + const paneKey = + binding && isValidTerminalTabId(binding.tabId) && isTerminalLeafId(binding.leafId) + ? makePaneKey(binding.tabId, binding.leafId) + : null + this.recordPtyWorktree(ptyId, worktreeId, { + connected: true, + connectionId, + ...(binding && paneKey ? { tabId: binding.tabId, paneKey } : {}) + }) + // Why: the renderer's own PTY spawn is the reliable signal that the pending + // mobile create's tab is live; publish its surface main-side (#7587). + if (binding && paneKey) { + this.ensurePtyBackedMobileSurfaceForRendererTab(worktreeId, binding.tabId) + } } /** Record the spawn launch command so the per-PTY Command Code detector can @@ -6292,6 +6354,7 @@ export class OrcaRuntimeService { source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + pendingEscapeTailAnsi?: string } | null> { return this.serializeTerminalBufferFromAvailableState(ptyId, opts) } @@ -6676,6 +6739,7 @@ export class OrcaRuntimeService { source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + pendingEscapeTailAnsi?: string } | null> { const headlessSnapshot = await this.serializeHeadlessTerminalBuffer(ptyId, opts) if (headlessSnapshot) { @@ -6793,6 +6857,9 @@ export class OrcaRuntimeService { source?: 'headless' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + // Why: dangling mid-escape tail the restorer must write LAST, after any + // reset, so the next live chunk completes it instead of rendering it + // literally (Bug E / #7329). pendingEscapeTailAnsi?: string } | null> { const state = this.headlessTerminals.get(ptyId) @@ -6822,6 +6889,9 @@ export class OrcaRuntimeService { seq: state.outputSequence, source: 'headless' as const, oscLinks: snapshot.oscLinks, + ...(snapshot.pendingEscapeTailAnsi + ? { pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi } + : {}), // Why: lets the renderer skip the destructive scrollback clear when // restoring an alt-screen snapshot — clearing wipes xterm's own // history that the TUI relies on for scroll-up after a tab return. @@ -6863,6 +6933,32 @@ export class OrcaRuntimeService { return { ptyId: leaf.ptyId } } + // Why: remote clients hold handles across transport reconnects. A handle + // minted for a concrete PTY must never silently adopt a different PTY that + // later occupies the same pane — that misroutes keystrokes (#7718). Handles + // still awaiting their first PTY (ptyId null) may adopt it, which preserves + // the mobile pre-spawn subscribe flow. + resolveLiveLeafForHandle(handle: string): { ptyId: string | null } | null { + const record = this.handles.get(handle) + if (!record) { + return null + } + if (record.tabId.startsWith('pty:')) { + return { ptyId: record.ptyId } + } + const leaf = this.leaves.get(this.getLeafKey(record.tabId, record.leafId)) + if (!leaf) { + return null + } + if ( + record.ptyId !== null && + (leaf.ptyId !== record.ptyId || leaf.ptyGeneration !== record.ptyGeneration) + ) { + throw new Error('terminal_handle_stale') + } + return { ptyId: leaf.ptyId } + } + async resolveTerminalCwd(handle: string): Promise { const ptyId = this.resolveLeafForHandle(handle)?.ptyId if (!ptyId) { @@ -7953,13 +8049,30 @@ export class OrcaRuntimeService { // the existing 'resized' event reaches the phone. // 2. Held with no mobile subscriber (post-indefinite-hold): no inner // subscriber to notify; resolve restore target and enqueueLayout - // directly. applyLayout is the SOLE writer of terminalFitOverrides; - // the held branch must not duplicate that mutation. See - // docs/mobile-fit-hold.md. + // directly. applyLayout is the SOLE writer of terminalFitOverrides on + // the normal path, so the held branch defers the mutation to it — the + // one exception is the dead-pty orphan cleanup below, which mirrors + // onPtyExit's sanctioned delete. See docs/mobile-fit-hold.md. + // + // Returns `true` only when the pty ends converged (no fit-override held); + // `false` when a restore was attempted but the resize failed (#7588), or + // when there was nothing to reclaim. On a failed-restore `false`, driver/mode + // are left unchanged so a driving phone keeps its lock and the modal + // truthfully stays — the user can retry. async reclaimTerminalForDesktop(ptyId: string): Promise { if (this.isMobileSubscriberActive(ptyId)) { + // Why (#7588): capture the prior mode so a failed restore can roll the + // routing-only 'desktop' write back — driver/mode transitions must be + // gated on convergence, not committed before we know the resize took. + const priorMode = this.getMobileDisplayMode(ptyId) this.setMobileDisplayMode(ptyId, 'desktop') - await this.applyMobileDisplayMode(ptyId) + const converged = await this.applyMobileDisplayMode(ptyId) + if (!converged) { + // Resize failed — override still held. Leave the driver on its mobile + // lock and undo the mode write so nothing is left lying at 'desktop'. + this.setMobileDisplayMode(ptyId, priorMode) + return false + } this.setDriver(ptyId, { kind: 'desktop' }) // Why: a desktop-initiated reclaim is "I'm taking over right now", // not a sticky preference. The next mobile subscribe (e.g. user @@ -7983,15 +8096,32 @@ export class OrcaRuntimeService { const renderer = this.lastRendererSizes.get(ptyId) const cols = renderer?.cols ?? heldOverride.previousCols ?? fallback.cols const rows = renderer?.rows ?? heldOverride.previousRows ?? fallback.rows - await this.enqueueLayout(ptyId, { kind: 'desktop', cols, rows }) - this.setDriver(ptyId, { kind: 'desktop' }) - // Why: a desktop-initiated reclaim is "I'm taking over right now", - // not a sticky preference. Reset to auto so the next mobile subscribe - // re-enters phone-fit. (Held-PTY branch may not have an entry, but - // calling setMobileDisplayMode('auto') is a no-op deletion in that - // case — safe and idempotent.) - this.setMobileDisplayMode(ptyId, 'auto') - return true + const result = await this.enqueueLayout(ptyId, { kind: 'desktop', cols, rows }) + if (result.ok) { + this.setDriver(ptyId, { kind: 'desktop' }) + // Why: a desktop-initiated reclaim is "I'm taking over right now", + // not a sticky preference. Reset to auto so the next mobile subscribe + // re-enters phone-fit. (Held-PTY branch may not have an entry, but + // calling setMobileDisplayMode('auto') is a no-op deletion in that + // case — safe and idempotent.) + this.setMobileDisplayMode(ptyId, 'auto') + return true + } + // Why (#7588): the layout entry is gone (pty exited) but the override is + // still held — unreachable via public APIs today (onPtyExit deletes both + // in lockstep), but reporting success while stranding the override would + // re-show the modal on the next hydrate. Run the same cleanup onPtyExit + // does (delete override + paired desktop-fit 0×0) so the renderer + // converges; nothing to resize on a dead pty. + if (result.reason === 'pty-exited' && this.terminalFitOverrides.has(ptyId)) { + this.terminalFitOverrides.delete(ptyId) + this.notifier?.terminalFitOverrideChanged(ptyId, 'desktop-fit', 0, 0) + this.notifyFitOverrideListeners(ptyId, 'desktop-fit', 0, 0) + return true + } + // resize-failed: the override remains held; report the truth so the + // modal correctly stays and the user can retry. Driver/mode untouched. + return false } return false } @@ -8107,7 +8237,8 @@ export class OrcaRuntimeService { // // applyLayout is the SOLE writer of: // - this.layouts - // - this.terminalFitOverrides + // - this.terminalFitOverrides (except the sanctioned dead-pty cleanups in + // onPtyExit and reclaimTerminalForDesktop's orphan branch, which delete) // - this.ptyController.resize (i.e. the actual PTY dims) // // Every trigger that wants to change PTY dims or flip mode goes through @@ -8302,11 +8433,17 @@ export class OrcaRuntimeService { this.resizeHeadlessTerminal(ptyId, target.cols, target.rows) } - // Why: emit fit-override-changed only when the *mode* flips. Layouts - // can change dims without flipping mode (keyboard show/hide while - // phone), and waking the renderer on every viewport tick is wasteful - // churn. - if (modeChanged) { + // Why: emit fit-override-changed when the *mode* flips. Layouts can + // change dims without flipping mode (keyboard show/hide while phone), + // and waking the renderer on every viewport tick is wasteful churn. + // Defense-in-depth (#7588): also emit when the override's presence + // changed even without a kind flip. applyLayout is the sole writer and + // keeps override presence in lockstep with layout kind, so overrideChanged + // ≡ modeChanged in every reachable state today; the extra clause fires + // only if that invariant is ever violated, repairing the renderer instead + // of stranding the held modal. + const overrideChanged = (prevFitOverride != null) !== (target.kind === 'phone') + if (modeChanged || overrideChanged) { // Why: phone→desktop arms the renderer-cascade suppress window // before the collateral safeFit IPCs arrive. See "Renderer cascade // suppression". @@ -8719,7 +8856,13 @@ export class OrcaRuntimeService { // Multi-mobile: the most recent mobile actor's viewport drives the active // phone-fit dims. The earliest-by-subscribe-time subscriber's // previousCols/Rows drive the desktop-restore target. - async applyMobileDisplayMode(ptyId: string): Promise { + // + // Returns the post-condition "no fit-override remains held" (#7588): `true` + // when it cleared a held override OR nothing was held to begin with, `false` + // only when a restore was attempted and the resize failed (override rolled + // back, still held). reclaimTerminalForDesktop gates its driver/mode + // transitions on this; other callers ignore it. + async applyMobileDisplayMode(ptyId: string): Promise { const mode = this.getMobileDisplayMode(ptyId) const inner = this.mobileSubscribers.get(ptyId) const subscriber = inner ? this.pickMostRecentActor(inner) : null @@ -8728,25 +8871,39 @@ export class OrcaRuntimeService { if (mode === 'desktop') { // Reset wasResizedToPhone on every fitted subscriber so a future // toggle back to auto re-issues the resize. applyLayout owns the - // actual PTY resize + override delete + renderer notify. - let anyWasResized = false - if (inner) { - for (const sub of inner.values()) { - if (sub.wasResizedToPhone) { - anyWasResized = true - sub.wasResizedToPhone = false - } - } + // actual PTY resize + override delete + renderer notify. Track which + // subscribers we cleared so a failed resize can re-arm them. + const clearedFitSubscribers = inner + ? [...inner.values()].filter((sub) => sub.wasResizedToPhone) + : [] + for (const sub of clearedFitSubscribers) { + sub.wasResizedToPhone = false } - if (anyWasResized) { + const anyWasResized = clearedFitSubscribers.length > 0 + // Why (#7588): also restore when a fit-override is still held but no + // subscriber carries wasResizedToPhone — e.g. a null-viewport resubscribe + // after an indefinite hold resets the flag yet leaves the override, + // stranding the desktop "phone size" modal. Reuse resolveDesktopRestoreTarget + // (the same resolver the anyWasResized branch uses) so the two adjacent + // restore paths can never resolve to different dims for the same state. + if (anyWasResized || this.terminalFitOverrides.has(ptyId)) { const restore = this.resolveDesktopRestoreTarget(ptyId) - await this.enqueueLayout(ptyId, { + const result = await this.enqueueLayout(ptyId, { kind: 'desktop', cols: restore.cols, rows: restore.rows }) + // Why (#7588): a failed resize rolls the override back (still held), so + // re-arm the flags we cleared. Otherwise a later unsubscribe under a + // finite mobileAutoRestoreFitMs would see wasResizedToPhone=false, skip + // scheduling its auto-restore timer, and strand the held phone-fit. + if (!result.ok) { + for (const sub of clearedFitSubscribers) { + sub.wasResizedToPhone = true + } + } } else { - // No subscriber was fitted — emit a mode-change resize event so + // Nothing was fitted or held — emit a mode-change resize event so // the mobile client still learns the toggle landed. const size = this.getTerminalSize(ptyId) this.notifyTerminalResize(ptyId, { @@ -8765,7 +8922,10 @@ export class OrcaRuntimeService { const viewport = subscriberRecord.viewport if (viewport) { await this.handleMobileSubscribe(ptyId, subscriberRecord.clientId, viewport) - return + // After a phone-fit an override IS held, so this reports false. The + // auto branch is never reached from reclaim (it sets 'desktop' + // first); computed here only to keep the post-condition uniform. + return !this.terminalFitOverrides.has(ptyId) } } // Why: always emit the mode change even when no resize occurred — the @@ -8781,6 +8941,7 @@ export class OrcaRuntimeService { seq: this.layouts.get(ptyId)?.seq }) } + return !this.terminalFitOverrides.has(ptyId) } // Why: called after a desktop renderer path has successfully resized the @@ -9446,6 +9607,35 @@ export class OrcaRuntimeService { } } + async sendTerminalAgentPrompt( + handle: string, + prompt: string, + options: { + beforeWrite?: (ptyId: string) => void | Promise + suffixFailureError?: string + } = {} + ): Promise { + const payload = buildAgentPromptPasteBytes(prompt) + const bytesWritten = Buffer.byteLength(`${payload}${AGENT_PROMPT_SUBMIT}`, 'utf8') + const pty = this.getLivePtyForHandle(handle) + if (pty) { + if (!pty.pty.connected) { + throw new Error('terminal_not_writable') + } + await assertTerminalInputWithinLimitWithYield(payload) + await this.writeTerminalAgentPrompt(pty.pty.ptyId, payload, options) + return { handle, accepted: true, bytesWritten } + } + + const { leaf } = this.getLiveLeafForHandle(handle) + if (!leaf.writable || !leaf.ptyId) { + throw new Error('terminal_not_writable') + } + await assertTerminalInputWithinLimitWithYield(payload) + await this.writeTerminalAgentPrompt(leaf.ptyId, payload, options) + return { handle, accepted: true, bytesWritten } + } + async getTerminalAgentStatus(handle: string): Promise { const terminal = this.getTerminalAgentStatusSnapshot(handle) const explicitStatus = this.getFreshExplicitAgentStatusForHandle(handle) @@ -9803,6 +9993,54 @@ export class OrcaRuntimeService { } } + private async writeTerminalAgentPrompt( + ptyId: string, + pastePayload: string, + options: { + beforeWrite?: (ptyId: string) => void | Promise + suffixFailureError?: string + } = {} + ): Promise { + let wrotePasteBytes = false + let completedPaste = false + try { + const chunks = iterateTerminalInputChunks(pastePayload) + let chunk = chunks.next() + while (!chunk.done) { + await options.beforeWrite?.(ptyId) + const wrote = this.ptyController?.write(ptyId, chunk.value) ?? false + if (!wrote) { + throw new Error('terminal_not_writable') + } + wrotePasteBytes = true + chunk = chunks.next() + if (!chunk.done) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } + } + completedPaste = true + } catch (error) { + if (wrotePasteBytes && !completedPaste) { + this.ptyController?.write(ptyId, AGENT_PROMPT_BRACKETED_PASTE_END) + } + throw error + } + + await new Promise((resolve) => setTimeout(resolve, AGENT_PROMPT_SUBMIT_DELAY_MS)) + try { + await options.beforeWrite?.(ptyId) + } catch (error) { + if (options.suffixFailureError) { + throw new Error(options.suffixFailureError) + } + throw error + } + const suffixWrote = this.ptyController?.write(ptyId, AGENT_PROMPT_SUBMIT) ?? false + if (!suffixWrote) { + throw new Error(options.suffixFailureError ?? 'terminal_not_writable') + } + } + async waitForTerminal( handle: string, options?: { @@ -10399,7 +10637,7 @@ export class OrcaRuntimeService { if (!this.store) { throw new Error('runtime_unavailable') } - let repo = await this.addRepo(args.path, args.kind === 'folder' ? 'folder' : 'git') + let repo = await this.addRepo(args.path, args.kind === 'folder' ? 'folder' : 'git', args.hostId) let setup = getProjectHostSetupForRepo(this.listProjectHostSetups(), repo) if (setup.projectId !== args.projectId) { const existingProject = this.listProjects().find((project) => project.id === args.projectId) @@ -10438,7 +10676,7 @@ export class OrcaRuntimeService { } async setupProjectClone(args: ProjectHostSetupCloneArgs): Promise { - const repo = await this.cloneRepo(args.url, args.destination) + const repo = await this.cloneRepo(args.url, args.destination, args.hostId) return await this.setupProjectExistingFolder({ projectId: args.projectId, hostId: args.hostId, @@ -10839,7 +11077,11 @@ export class OrcaRuntimeService { }) } - async addRepo(path: string, kind: 'git' | 'folder' = 'git'): Promise { + async addRepo( + path: string, + kind: 'git' | 'folder' = 'git', + executionHostId?: ExecutionHostId | null + ): Promise { if (!this.store) { throw new Error('runtime_unavailable') } @@ -10852,8 +11094,29 @@ export class OrcaRuntimeService { throw new Error(`Not a valid git repository: ${path}`) } - const existing = this.store.getRepos().find((repo) => runtimePathsEqual(repo.path, path)) + const existing = this.store.getRepos().find((repo) => { + if (!runtimePathsEqual(repo.path, path)) { + return false + } + return runtimeRepoMatchesExecutionHost(repo, executionHostId) + }) if (existing) { + // Only a runtime host backfills a legacy unstamped repo. An unstamped repo is + // indistinguishable from a genuine local repo (both have null executionHostId and + // connectionId), so we never stamp local/ssh onto it — that would re-attribute a + // real local project to the wrong host. Runtime is the only host that lost its + // identity to the pre-#7018 path-only import and needs the backfill. + if ( + existing.executionHostId == null && + parseExecutionHostId(executionHostId)?.kind === 'runtime' + ) { + const adopted = + this.store.updateRepo(existing.id, { executionHostId }) ?? + ({ ...existing, executionHostId } as Repo) + this.invalidateResolvedWorktreeCache() + this.notifyReposChanged() + return adopted + } return existing } @@ -10863,6 +11126,7 @@ export class OrcaRuntimeService { path, displayName: getRepoName(path), badgeColor: DEFAULT_REPO_BADGE_COLOR, + ...(executionHostId != null ? { executionHostId } : {}), ...detected, addedAt: Date.now(), kind, @@ -11001,7 +11265,11 @@ export class OrcaRuntimeService { return { repo: this.store.getRepo(repo.id) ?? repo } } - async cloneRepo(url: string, destination: string): Promise { + async cloneRepo( + url: string, + destination: string, + executionHostId?: ExecutionHostId | null + ): Promise { if (!this.store) { throw new Error('runtime_unavailable') } @@ -11029,7 +11297,8 @@ export class OrcaRuntimeService { trimmedUrl, trimmedDestination, clonePath, - clonePathKey + clonePathKey, + executionHostId ) } finally { release() @@ -11043,14 +11312,19 @@ export class OrcaRuntimeService { trimmedUrl: string, trimmedDestination: string, clonePath: string, - clonePathKey: string + clonePathKey: string, + executionHostId?: ExecutionHostId | null ): Promise { if (!this.store) { throw new Error('runtime_unavailable') } const existingBeforeClone = this.store .getRepos() - .find((repo) => getClonePathComparisonKey(repo.path) === clonePathKey) + .find( + (repo) => + getClonePathComparisonKey(repo.path) === clonePathKey && + runtimeRepoMatchesExecutionHost(repo, executionHostId) + ) if (existingBeforeClone && !isFolderRepo(existingBeforeClone)) { return existingBeforeClone } @@ -11110,7 +11384,11 @@ export class OrcaRuntimeService { const existing = this.store .getRepos() - .find((repo) => getClonePathComparisonKey(repo.path) === clonePathKey) + .find( + (repo) => + getClonePathComparisonKey(repo.path) === clonePathKey && + runtimeRepoMatchesExecutionHost(repo, executionHostId) + ) if (existing) { if (isFolderRepo(existing)) { const updated = this.store.updateRepo(existing.id, { kind: 'git' }) @@ -11131,6 +11409,7 @@ export class OrcaRuntimeService { path: clonePath, displayName: getRepoName(clonePath), badgeColor: DEFAULT_REPO_BADGE_COLOR, + ...(executionHostId != null ? { executionHostId } : {}), ...detected, addedAt: Date.now(), kind: 'git', @@ -16433,7 +16712,7 @@ export class OrcaRuntimeService { const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector) const launchOpts = await this.resolveAgentTerminalCreateOptions(workspace, opts) const cwd = - this.resolveGuardedWorkspaceTerminalCwd(workspace, launchOpts.cwd) ?? workspace.path + this.resolveWorkspaceTerminalStartupCwd(workspace, launchOpts.cwd) ?? workspace.path const preAllocatedHandle = this.createPreAllocatedTerminalHandle() // Why: mint tabId in main before spawn so paneKey is known at PTY env // build time. Hook-based agent status (Claude/Codex/Cursor/Gemini) keys @@ -16626,7 +16905,7 @@ export class OrcaRuntimeService { : opts const worktreeId = workspace?.id const cwd = workspace - ? this.resolveGuardedWorkspaceTerminalCwd(workspace, launchOpts.cwd) + ? this.resolveWorkspaceTerminalStartupCwd(workspace, launchOpts.cwd) : launchOpts.cwd const requestId = randomUUID() @@ -16724,6 +17003,7 @@ export class OrcaRuntimeService { launchAgent?: TuiAgent activate?: boolean clientMutationId?: string + signal?: AbortSignal } = {} ): Promise { const mutationId = opts.clientMutationId @@ -16765,12 +17045,13 @@ export class OrcaRuntimeService { launchAgent?: TuiAgent activate?: boolean clientMutationId?: string + signal?: AbortSignal } = {} ): Promise { this.assertGraphReady() const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector) const worktreeId = workspace.id - const cwd = this.resolveGuardedWorkspaceTerminalCwd(workspace, opts.cwd) + const cwd = this.resolveWorkspaceTerminalStartupCwd(workspace, opts.cwd) this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) let afterDesktopTabId: string | undefined if (opts.afterTabId) { @@ -16804,8 +17085,16 @@ export class OrcaRuntimeService { const reply = await new Promise<{ tabId: string; title: string }>((resolve, reject) => { const timer = setTimeout(() => { ipcMain.removeListener('terminal:tabCreateReply', handler) + opts.signal?.removeEventListener('abort', onAbort) reject(new Error('Terminal creation timed out')) }, 10_000) + // Why: a dead client connection cancels the wait; the renderer tab (and + // its shell) stays alive for the host and mirrors on reconnect (#7718). + const onAbort = (): void => { + clearTimeout(timer) + ipcMain.removeListener('terminal:tabCreateReply', handler) + reject(new Error('client_disconnected')) + } const handler = ( event: Electron.IpcMainEvent, @@ -16816,12 +17105,14 @@ export class OrcaRuntimeService { } clearTimeout(timer) ipcMain.removeListener('terminal:tabCreateReply', handler) + opts.signal?.removeEventListener('abort', onAbort) if (r.error) { reject(new Error(r.error)) } else { resolve({ tabId: r.tabId!, title: r.title ?? '' }) } } + opts.signal?.addEventListener('abort', onAbort, { once: true }) ipcMain.on('terminal:tabCreateReply', handler) win.webContents.send('terminal:requestTabCreate', { requestId, @@ -16842,20 +17133,42 @@ export class OrcaRuntimeService { if (opts.activate !== false) { this.notifier?.focusTerminal(reply.tabId, worktreeId, null) } + // Why: register the wait before the renderer's PTY spawn arrives so that + // spawn (registerPty) can publish the pty-backed surface main-side even if + // graph-sync is stalled (#7587). Removed in the finally below. + const pendingCreateKey = `${worktreeId}::${reply.tabId}` + // Why: a rescue publishes into the active group (opts.targetGroupId is not + // threaded); the renderer's reconciling publication then moves the tab to the + // requested group, so any wrong-group placement is cosmetic and stall-window-only. + this.pendingMobileTerminalCreatesByKey.set(pendingCreateKey, { + activate: opts.activate !== false, + selectIfNoActiveTab: true + }) try { + // Why: the PTY spawn and the tabCreate reply race on independent IPC + // channels; if the spawn already registered, publish immediately so the + // wait resolves without depending on a graph sync. + this.ensurePtyBackedMobileSurfaceForRendererTab(worktreeId, reply.tabId) const surface = await this.waitForMobileTerminalSurface(worktreeId, reply.tabId, { - timeoutMs: MOBILE_TERMINAL_SURFACE_TIMEOUT_MS + timeoutMs: MOBILE_TERMINAL_SURFACE_TIMEOUT_MS, + signal: opts.signal }) if (this.isReadyMobileTerminalSurface(surface)) { return surface } const readySurface = await this.waitForMobileTerminalSurface(worktreeId, reply.tabId, { timeoutMs: MOBILE_TERMINAL_READY_FALLBACK_MS, - requireReady: true + requireReady: true, + signal: opts.signal }).catch(() => null) if (readySurface) { return readySurface } + if (opts.signal?.aborted) { + // Why: nobody is waiting for this create anymore; do not materialize + // or roll back — the renderer's own publication settles the tab. + throw new Error('client_disconnected') + } const pendingSurface = this.findMobileTerminalSurface(worktreeId, reply.tabId) if (!pendingSurface) { throw new Error('Timed out waiting for terminal surface after creation') @@ -16879,12 +17192,34 @@ export class OrcaRuntimeService { } ) } catch (error) { - // Why: the renderer created the tab but its terminal surface never - // published (PTY spawn/handle failure). Roll the half-created tab back via - // the renderer close path so it can't linger as a ghost in mobile - // snapshots, then surface the failure to the caller. + // Why: publication latency (throttled/hidden renderer), not spawn failure, + // can trip the surface timeout. Rescue only when a live PTY actually backs + // the tab — gating on a surface would let a handle-less shell (or a failed + // materialize) resolve as success and skip the ghost-tab rollback (#7587). + if (this.findLiveRegisteredPtyForRendererTab(worktreeId, reply.tabId)) { + const rescued = this.ensurePtyBackedMobileSurfaceForRendererTab(worktreeId, reply.tabId) + if (rescued) { + return rescued + } + } + // Why: don't roll back when (a) the client connection died — the wait + // was cancelled, not the spawn — or (b) a live shell already backs the + // tab (its pane key may simply not be registered yet). Killing a real + // terminal the host user can see is the "tab dies after ~10s" bug (#7718). + if ( + isClientDisconnectedError(error) || + this.hasLiveShellForRendererTab(worktreeId, reply.tabId) + ) { + throw error + } + // Why: the renderer created the tab but no live PTY backs it (true PTY + // spawn/handle failure). Roll the half-created tab back via the renderer + // close path so it can't linger as a ghost in mobile snapshots, then + // surface the failure to the caller. this.notifier?.closeTerminal(reply.tabId) throw error + } finally { + this.pendingMobileTerminalCreatesByKey.delete(pendingCreateKey) } } @@ -16980,7 +17315,7 @@ export class OrcaRuntimeService { } = {} ): Promise { const workspace = await this.resolveTerminalWorkspaceLaunchScope(`id:${worktreeId}`) - const cwd = this.resolveGuardedWorkspaceTerminalCwd(workspace, opts.cwd) + const cwd = this.resolveWorkspaceTerminalStartupCwd(workspace, opts.cwd) // Why: SshPtyProvider treats sessionId as a relay reattach request. Only // synthesize local serve ids; SSH fresh terminals must call pty.spawn. const stableSessionId = @@ -17096,33 +17431,44 @@ export class OrcaRuntimeService { private waitForMobileTerminalSurface( worktreeId: string, parentTabId: string, - options: { timeoutMs?: number; requireReady?: boolean } = {} + options: { timeoutMs?: number; requireReady?: boolean; signal?: AbortSignal } = {} ): Promise { const timeoutMs = options.timeoutMs ?? MOBILE_TERMINAL_SURFACE_TIMEOUT_MS const existing = this.findMobileTerminalSurface(worktreeId, parentTabId, options) if (existing) { return Promise.resolve(existing) } + if (options.signal?.aborted) { + return Promise.reject(new Error('client_disconnected')) + } return new Promise((resolve, reject) => { - const timer = setTimeout(() => { + const cleanup = (): void => { + clearTimeout(timer) + options.signal?.removeEventListener('abort', onAbort) const idx = this.graphSyncCallbacks.indexOf(check) if (idx !== -1) { this.graphSyncCallbacks.splice(idx, 1) } + } + const timer = setTimeout(() => { + cleanup() reject(new Error('Timed out waiting for terminal surface after creation')) }, timeoutMs) + // Why: a dead client connection cancels the wait immediately instead of + // running down the timeout and triggering rollback (#7718). + const onAbort = (): void => { + cleanup() + reject(new Error('client_disconnected')) + } + options.signal?.addEventListener('abort', onAbort, { once: true }) const check = (): void => { const next = this.findMobileTerminalSurface(worktreeId, parentTabId, options) if (!next) { return } - clearTimeout(timer) - const idx = this.graphSyncCallbacks.indexOf(check) - if (idx !== -1) { - this.graphSyncCallbacks.splice(idx, 1) - } + cleanup() resolve(next) } this.graphSyncCallbacks.push(check) @@ -17157,6 +17503,73 @@ export class OrcaRuntimeService { return surface } + // Why: for an in-flight mobile create whose surface hasn't published yet, + // publish it main-side from the live renderer PTY so the create doesn't wait + // on a stalled graph sync and destroy the session (#7587). No-op unless a + // matching create is pending and a live bound PTY exists; never double-inserts. + private ensurePtyBackedMobileSurfaceForRendererTab( + worktreeId: string, + tabId: string + ): RuntimeMobileSessionCreateTerminalResult | null { + const pending = this.pendingMobileTerminalCreatesByKey.get(`${worktreeId}::${tabId}`) + if (!pending) { + return null + } + const existing = this.findMobileTerminalSurface(worktreeId, tabId) + if (existing) { + // Why: the renderer's own publication already landed; stay idempotent. + return existing + } + const pty = this.findLiveRegisteredPtyForRendererTab(worktreeId, tabId) + const leafId = pty ? parsePaneKey(pty.paneKey ?? '')?.leafId : undefined + if (!pty || !leafId) { + return null + } + this.publishPtyBackedMobileSessionTerminal(worktreeId, pty, { + tabId, + leafId, + title: null, + activate: pending.activate, + selectIfNoActiveTab: pending.selectIfNoActiveTab + }) + // Why: waitForMobileTerminalSurface's check closures are drained only inside + // syncWindowGraph; a main-side publish must drain them too or the pending + // wait won't observe the insertion (mirrors syncWindowGraph's drain). + for (const cb of [...this.graphSyncCallbacks]) { + cb() + } + return this.findMobileTerminalSurface(worktreeId, tabId) + } + + private findLiveRegisteredPtyForRendererTab( + worktreeId: string, + tabId: string + ): RuntimePtyWorktreeRecord | null { + for (const pty of this.ptysById.values()) { + if ( + pty.worktreeId === worktreeId && + pty.tabId === tabId && + pty.connected && + parsePaneKey(pty.paneKey ?? '')?.leafId + ) { + return pty + } + } + return null + } + + // Why: rollback guard, looser than findLiveRegisteredPtyForRendererTab — a + // shell whose pane key hasn't registered yet can't be surface-rescued, but + // it is still a real terminal the create timeout must not kill (#7718). + private hasLiveShellForRendererTab(worktreeId: string, tabId: string): boolean { + for (const pty of this.ptysById.values()) { + if (pty.worktreeId === worktreeId && pty.tabId === tabId && pty.connected) { + return true + } + } + return false + } + private isReadyMobileTerminalSurface( surface: RuntimeMobileSessionCreateTerminalResult | null ): boolean { @@ -17849,15 +18262,11 @@ export class OrcaRuntimeService { } } - // Why: every terminal-creation path must apply the same symlink-aware cwd - // guard; keep the canonicalizer wiring in one place. - private resolveGuardedWorkspaceTerminalCwd( - workspace: Pick, + private resolveWorkspaceTerminalStartupCwd( + workspace: Pick, requestedCwd?: string | null ): string | undefined { - return resolveTerminalStartupCwd(workspace.path, requestedCwd, { - canonicalizePath: localTerminalCwdCanonicalizer(workspace.connectionId) - }) + return resolveTerminalStartupCwd(workspace.path, requestedCwd) } private async resolveTerminalWorkspaceLaunchScope( diff --git a/src/main/runtime/orchestration/coordinator.test.ts b/src/main/runtime/orchestration/coordinator.test.ts index a10c4ea20..8593fd816 100644 --- a/src/main/runtime/orchestration/coordinator.test.ts +++ b/src/main/runtime/orchestration/coordinator.test.ts @@ -40,8 +40,8 @@ function createMockRuntime(): CoordinatorRuntime & { setProbeDrift(result: DriftResult): void { mock.probeDriftResult = result }, - async sendTerminal(handle: string, action: { text?: string }) { - mock.sentMessages.push({ handle, text: action.text ?? '' }) + async sendTerminalAgentPrompt(handle: string, prompt: string) { + mock.sentMessages.push({ handle, text: prompt }) return { handle, accepted: true, bytesWritten: 0 } }, async listTerminals() { @@ -275,7 +275,7 @@ describe('Coordinator', () => { db = new OrchestrationDb(':memory:') const runtime = createMockRuntime() runtime.terminals = [{ handle: 'term_a', worktreeId: 'wt1', connected: true, writable: true }] - runtime.sendTerminal = async () => { + runtime.sendTerminalAgentPrompt = async () => { throw new Error('terminal_not_writable') } @@ -690,8 +690,8 @@ describe('Coordinator', () => { const result = await runPromise // Why: silent-skip must NOT burn the circuit-breaker budget. Task must - // stay in `ready`; failDispatch must NOT be called; sendTerminal must - // NOT be called; no dispatch context should exist. + // stay in `ready`; failDispatch must NOT be called; no prompt injection + // should happen; no dispatch context should exist. expect(runtime.sentMessages).toHaveLength(0) expect(db.getTask(task.id)?.status).toBe('ready') expect(db.getDispatchContext(task.id)).toBeUndefined() diff --git a/src/main/runtime/orchestration/coordinator.ts b/src/main/runtime/orchestration/coordinator.ts index 897290c32..2313dfdf3 100644 --- a/src/main/runtime/orchestration/coordinator.ts +++ b/src/main/runtime/orchestration/coordinator.ts @@ -5,7 +5,7 @@ import { buildDispatchPreamble } from './preamble' import { reconcileLifecycleMessage } from './lifecycle-reconciliation' export type CoordinatorRuntime = { - sendTerminal(handle: string, action: { text?: string; enter?: boolean }): Promise + sendTerminalAgentPrompt(handle: string, prompt: string): Promise listTerminals( worktreeSelector?: string, limit?: number @@ -495,10 +495,7 @@ export class Coordinator { } try { - await this.runtime.sendTerminal(targetHandle, { - text: preamble + gateContext, - enter: true - }) + await this.runtime.sendTerminalAgentPrompt(targetHandle, preamble + gateContext) } catch (err) { const updated = this.db.failDispatch( dispatch.id, diff --git a/src/main/runtime/rpc/methods/ai-vault.test.ts b/src/main/runtime/rpc/methods/ai-vault.test.ts new file mode 100644 index 000000000..c7cc56a64 --- /dev/null +++ b/src/main/runtime/rpc/methods/ai-vault.test.ts @@ -0,0 +1,61 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { AI_VAULT_METHODS } from './ai-vault' + +const mocks = vi.hoisted(() => ({ + scanAiVaultSessions: vi.fn() +})) + +vi.mock('../../../ai-vault/session-scanner', () => ({ + scanAiVaultSessions: mocks.scanAiVaultSessions +})) + +beforeEach(() => { + vi.clearAllMocks() + mocks.scanAiVaultSessions.mockResolvedValue({ + sessions: [], + issues: [], + scannedAt: '2026-07-04T00:00:00.000Z' + }) +}) + +describe('aiVault.listSessions runtime RPC', () => { + it('scans server-local sessions under the caller supplied runtime host id', async () => { + const method = AI_VAULT_METHODS.find((entry) => entry.name === 'aiVault.listSessions') + expect(method).toBeDefined() + + const params = method!.params!.parse({ + limit: 25, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:remote-server' + }) + + await method!.handler(params, {} as never) + + expect(mocks.scanAiVaultSessions).toHaveBeenCalledWith({ + limit: 25, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:remote-server' + }) + }) + + it('rejects non-runtime execution host ids before dispatch', () => { + const method = AI_VAULT_METHODS.find((entry) => entry.name === 'aiVault.listSessions') + expect(method).toBeDefined() + + expect(() => + method!.params!.parse({ + executionHostId: 'not-a-runtime-host' + }) + ).toThrow('Invalid runtime execution host id') + expect(() => + method!.params!.parse({ + executionHostId: 'local' + }) + ).toThrow('Invalid runtime execution host id') + expect(() => + method!.params!.parse({ + executionHostId: 'ssh:dev-box' + }) + ).toThrow('Invalid runtime execution host id') + }) +}) diff --git a/src/main/runtime/rpc/methods/ai-vault.ts b/src/main/runtime/rpc/methods/ai-vault.ts new file mode 100644 index 000000000..49591ea1e --- /dev/null +++ b/src/main/runtime/rpc/methods/ai-vault.ts @@ -0,0 +1,36 @@ +import { z } from 'zod' +import { scanAiVaultSessions } from '../../../ai-vault/session-scanner' +import { defineMethod, type RpcMethod } from '../core' +import { parseExecutionHostId } from '../../../../shared/execution-host' + +const executionHostIdSchema = z.string().transform((value, ctx): `runtime:${string}` => { + const parsed = parseExecutionHostId(value) + if (parsed?.kind === 'runtime') { + return parsed.id + } + ctx.addIssue({ + code: 'custom', + message: 'Invalid runtime execution host id' + }) + return z.NEVER +}) + +const listSessionsParamsSchema = z.object({ + limit: z.number().int().positive().optional(), + force: z.boolean().optional(), + scopePaths: z.array(z.string()).optional(), + executionHostId: executionHostIdSchema +}) + +export const AI_VAULT_METHODS: RpcMethod[] = [ + defineMethod({ + name: 'aiVault.listSessions', + params: listSessionsParamsSchema, + handler: async (params) => + scanAiVaultSessions({ + limit: params.limit, + scopePaths: params.scopePaths, + executionHostId: params.executionHostId + }) + }) +] diff --git a/src/main/runtime/rpc/methods/index.ts b/src/main/runtime/rpc/methods/index.ts index 8018375a8..bc0a73985 100644 --- a/src/main/runtime/rpc/methods/index.ts +++ b/src/main/runtime/rpc/methods/index.ts @@ -1,5 +1,6 @@ import type { RpcAnyMethod } from '../core' import { STATUS_METHODS } from './status' +import { AI_VAULT_METHODS } from './ai-vault' import { AUTOMATION_METHODS } from './automations' import { REPO_METHODS } from './repo' import { WORKTREE_METHODS } from './worktree' @@ -39,6 +40,7 @@ import { EMULATOR_METHODS } from './emulator' // auditing the security boundary or wiring new CLI commands. export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [ ...STATUS_METHODS, + ...AI_VAULT_METHODS, ...AUTOMATION_METHODS, ...REPO_METHODS, ...WORKTREE_METHODS, diff --git a/src/main/runtime/rpc/methods/orchestration.test.ts b/src/main/runtime/rpc/methods/orchestration.test.ts index 8fd0da2bf..e5255595a 100644 --- a/src/main/runtime/rpc/methods/orchestration.test.ts +++ b/src/main/runtime/rpc/methods/orchestration.test.ts @@ -1067,7 +1067,9 @@ describe('orchestration RPC methods', () => { setup() const task = db.createTask({ spec: 'work' }) vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - vi.spyOn(runtime, 'sendTerminal').mockRejectedValue(new Error('terminal_not_writable')) + vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockRejectedValue( + new Error('terminal_not_writable') + ) await expect( call('orchestration.dispatch', { @@ -1085,7 +1087,7 @@ describe('orchestration RPC methods', () => { setup() const task = db.createTask({ spec: 'work' }) vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - const send = vi.spyOn(runtime, 'sendTerminal').mockResolvedValue({ + const send = vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ handle: 'term_a', accepted: true, bytesWritten: 1 @@ -1098,7 +1100,35 @@ describe('orchestration RPC methods', () => { devMode: true }) - expect(send.mock.calls[0]?.[1].text).toContain('orca-dev orchestration send') + expect(send).toHaveBeenCalledWith( + 'term_a', + expect.stringContaining('orca-dev orchestration send') + ) + }) + + it('injects preamble through the agent prompt path instead of raw terminal send', async () => { + setup() + const task = db.createTask({ spec: 'line one\nline two' }) + vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) + const agentPrompt = vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ + handle: 'term_a', + accepted: true, + bytesWritten: 1 + }) + const rawSend = vi.spyOn(runtime, 'sendTerminal') + + await call('orchestration.dispatch', { + task: task.id, + to: 'term_a', + inject: true, + from: 'term_coord' + }) + + expect(agentPrompt).toHaveBeenCalledWith( + 'term_a', + expect.stringContaining('line one\nline two') + ) + expect(rawSend).not.toHaveBeenCalled() }) it('rejects inject to terminal without recognized agent', async () => { diff --git a/src/main/runtime/rpc/methods/orchestration.ts b/src/main/runtime/rpc/methods/orchestration.ts index 705791047..f22ad62d8 100644 --- a/src/main/runtime/rpc/methods/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration.ts @@ -492,7 +492,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ let injected = false if (params.inject) { try { - await runtime.sendTerminal(to, { text: preamble, enter: true }) + await runtime.sendTerminalAgentPrompt(to, preamble) injected = true } catch (err) { db.failDispatch(ctx.id, err instanceof Error ? err.message : String(err)) diff --git a/src/main/runtime/rpc/methods/session-tabs.ts b/src/main/runtime/rpc/methods/session-tabs.ts index f2bf1641b..d27d771f3 100644 --- a/src/main/runtime/rpc/methods/session-tabs.ts +++ b/src/main/runtime/rpc/methods/session-tabs.ts @@ -41,7 +41,7 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ defineMethod({ name: 'session.tabs.createTerminal', params: CreateTerminalTab, - handler: async (params, { runtime }) => + handler: async (params, { runtime, signal }) => runtime.createMobileSessionTerminal(params.worktree, { afterTabId: params.afterTabId, targetGroupId: params.targetGroupId, @@ -54,7 +54,10 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ ...(params.launchToken ? { launchToken: params.launchToken } : {}), ...(params.launchAgent ? { launchAgent: params.launchAgent } : {}), activate: params.activate, - clientMutationId: params.clientMutationId + clientMutationId: params.clientMutationId, + // Why: a dead client connection must cancel the surface wait instead + // of running down the timeout and rolling back a live tab (#7718). + signal }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/ssh.test.ts b/src/main/runtime/rpc/methods/ssh.test.ts index 94791a7fd..8efab5083 100644 --- a/src/main/runtime/rpc/methods/ssh.test.ts +++ b/src/main/runtime/rpc/methods/ssh.test.ts @@ -4,14 +4,23 @@ import type { RpcRequest } from '../core' import type { OrcaRuntimeService } from '../../orca-runtime' import { SSH_METHODS } from './ssh' -const { connectRegisteredSshTargetMock, getRegisteredSshStateMock } = vi.hoisted(() => ({ +const { + connectRegisteredSshTargetMock, + getRegisteredSshStateMock, + listRegisteredSshTargetsMock, + listRegisteredRemovedSshTargetLabelsMock +} = vi.hoisted(() => ({ connectRegisteredSshTargetMock: vi.fn(), - getRegisteredSshStateMock: vi.fn() + getRegisteredSshStateMock: vi.fn(), + listRegisteredSshTargetsMock: vi.fn(), + listRegisteredRemovedSshTargetLabelsMock: vi.fn() })) vi.mock('../../../ipc/ssh', () => ({ connectRegisteredSshTarget: connectRegisteredSshTargetMock, - getRegisteredSshState: getRegisteredSshStateMock + getRegisteredSshState: getRegisteredSshStateMock, + listRegisteredSshTargets: listRegisteredSshTargetsMock, + listRegisteredRemovedSshTargetLabels: listRegisteredRemovedSshTargetLabelsMock })) function makeRequest(method: string, params?: unknown): RpcRequest { @@ -62,4 +71,26 @@ describe('ssh RPC methods', () => { expect(response).toMatchObject({ ok: true, result: { state: null } }) }) + + it('lists the registered SSH targets for paired clients', async () => { + const targets = [{ id: 'ssh-1', label: 'Dev box', host: 'dev', port: 22, username: 'me' }] + listRegisteredSshTargetsMock.mockReturnValueOnce(targets) + const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('ssh.listTargets')) + + expect(response).toMatchObject({ ok: true, result: { targets } }) + }) + + it('lists removed-target labels for ghost-host display on paired clients', async () => { + const labels = { 'ssh-old': 'Dev box' } + listRegisteredRemovedSshTargetLabelsMock.mockReturnValueOnce(labels) + const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('ssh.listRemovedTargetLabels')) + + expect(response).toMatchObject({ ok: true, result: { labels } }) + }) }) diff --git a/src/main/runtime/rpc/methods/ssh.ts b/src/main/runtime/rpc/methods/ssh.ts index e4d836ced..6de8634a8 100644 --- a/src/main/runtime/rpc/methods/ssh.ts +++ b/src/main/runtime/rpc/methods/ssh.ts @@ -1,5 +1,10 @@ import { z } from 'zod' -import { connectRegisteredSshTarget, getRegisteredSshState } from '../../../ipc/ssh' +import { + connectRegisteredSshTarget, + getRegisteredSshState, + listRegisteredRemovedSshTargetLabels, + listRegisteredSshTargets +} from '../../../ipc/ssh' import { defineMethod, type RpcMethod } from '../core' const SshTarget = z.object({ @@ -16,5 +21,15 @@ export const SSH_METHODS: RpcMethod[] = [ name: 'ssh.connect', params: SshTarget, handler: async (params) => ({ state: await connectRegisteredSshTarget(params.targetId) }) + }), + defineMethod({ + name: 'ssh.listTargets', + params: null, + handler: () => ({ targets: listRegisteredSshTargets() }) + }), + defineMethod({ + name: 'ssh.listRemovedTargetLabels', + params: null, + handler: () => ({ labels: listRegisteredRemovedSshTargetLabels() }) }) ] diff --git a/src/main/runtime/rpc/methods/terminal.ts b/src/main/runtime/rpc/methods/terminal.ts index a83895f4e..1d543e2a5 100644 --- a/src/main/runtime/rpc/methods/terminal.ts +++ b/src/main/runtime/rpc/methods/terminal.ts @@ -58,6 +58,7 @@ type SnapshotFrameOptions = { truncatedByByteBudget?: boolean source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] + pendingEscapeTailAnsi?: string } type SerializedSnapshot = { @@ -70,6 +71,7 @@ type SerializedSnapshot = { oscLinks?: TerminalOscLinkRange[] scrollbackRows: number truncatedByByteBudget: boolean + pendingEscapeTailAnsi?: string } | null type TerminalViewportClient = { @@ -532,6 +534,7 @@ function sendSnapshotFrames( cwd: options.cwd, source: options.source, oscLinks: options.oscLinks, + pendingEscapeTailAnsi: options.pendingEscapeTailAnsi, truncated: options.truncated === true, truncatedByByteBudget: options.truncatedByByteBudget === true }) @@ -976,7 +979,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ params: TerminalSend, handler: async (params, { runtime }) => { await assertTerminalSendTextWithinLimit(params.text) - const leaf = runtime.resolveLeafForHandle(params.terminal) + // Why: guarded resolution — a stale handle must fail with + // terminal_handle_stale (clients recover by re-deriving the handle) + // instead of evaluating driver/lock state against the wrong PTY (#7718). + const leaf = runtime.resolveLiveLeafForHandle(params.terminal) const driver = leaf?.ptyId ? runtime.getDriver(leaf.ptyId) : null if (leaf?.ptyId && isTerminalInputLockedForClient(runtime, leaf.ptyId, params.client)) { return { @@ -1620,6 +1626,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ cwd: serialized?.cwd, source: serialized?.source, oscLinks: serialized?.oscLinks, + pendingEscapeTailAnsi: serialized?.pendingEscapeTailAnsi, truncated: false, truncatedByByteBudget: serialized?.truncatedByByteBudget, data: serialized?.data ?? '' @@ -1654,8 +1661,19 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ const request = parsed.data detachStream(request.streamId, false) - let leaf = runtime.resolveLeafForHandle(request.terminal) const isMobile = request.client?.type === 'mobile' + let leaf: { ptyId: string | null } | null + try { + // Why: guarded resolution — binding the output stream to whatever + // PTY now occupies a stale handle's pane silently mirrors the wrong + // terminal after a reconnect (#7718). terminal_handle_stale lets the + // client re-derive the handle from the current session snapshot. + leaf = runtime.resolveLiveLeafForHandle(request.terminal) + } catch { + sendStreamError(request.streamId, 'terminal_handle_stale') + emit({ type: 'end', streamId: request.streamId }) + return + } if (!leaf?.ptyId && isMobile) { try { const ptyId = await runtime.waitForLeafPtyId(request.terminal, 10_000, signal) @@ -1849,6 +1867,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ truncatedByByteBudget: serialized?.truncatedByByteBudget, source: serialized?.source, oscLinks: serialized?.oscLinks, + pendingEscapeTailAnsi: serialized?.pendingEscapeTailAnsi, data: serialized?.data ?? (read.tail.length > 0 ? `${read.tail.join('\r\n')}\r\n` : '') }) // Why: baseline for resize re-stream gating; the client already diff --git a/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts b/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts new file mode 100644 index 000000000..59e4d2d1b --- /dev/null +++ b/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from './dispatcher' +import type { RpcRequest } from './core' +import type { OrcaRuntimeService } from '../orca-runtime' +import { TERMINAL_METHODS } from './methods/terminal' +import type { RuntimeTerminalWait } from '../../../shared/runtime-types' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamJson, + encodeTerminalStreamFrame, + encodeTerminalStreamJson +} from '../../../shared/terminal-stream-protocol' + +// Transport-level regression for #7329: the daemon's mid-escape tail +// (pendingEscapeTailAnsi) must survive the terminal.multiplex wire so the +// renderer can replay it after the reset. Without threading it through the +// SnapshotStart JSON frame, the tail is lost and the next live chunk renders +// literally ("colors/garbage around what I type"). + +function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { + return { + getRuntimeId: () => 'test-runtime', + ...overrides + } as OrcaRuntimeService +} + +function makeRequest(method: string, params?: unknown): RpcRequest { + return { id: 'req-1', authToken: 'tok', method, params } +} + +describe('terminal.multiplex pending-escape-tail threading (#7329)', () => { + it('carries the daemon pendingEscapeTailAnsi through the SnapshotStart frame', async () => { + vi.useFakeTimers() + try { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn().mockResolvedValue({ + data: 'user@host:~$ ', + cols: 80, + rows: 24, + // The dangling partial the emulator could not serialize. + pendingEscapeTailAnsi: '\x1b[3' + }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-1', + sendBinary: (bytes) => binaryFrames.push(bytes), + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.runOnlyPendingTimersAsync() + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 5, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' } + }) + }) + )! + ) + + // Drive the subscribe promise chain (readTerminal/serialize awaits + the + // output-batcher flush timer) to completion. + for (let i = 0; i < 5; i += 1) { + await vi.runOnlyPendingTimersAsync() + } + + const snapshotStart = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .find((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart)! + expect(decodeTerminalStreamJson(snapshotStart.payload)).toMatchObject({ + pendingEscapeTailAnsi: '\x1b[3' + }) + + runtime.cleanupSubscription('terminal-multiplex:conn-1') + await dispatchPromise + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/runtime/rpc/terminal-multiplex.test.ts b/src/main/runtime/rpc/terminal-multiplex.test.ts index 280979215..3514ea416 100644 --- a/src/main/runtime/rpc/terminal-multiplex.test.ts +++ b/src/main/runtime/rpc/terminal-multiplex.test.ts @@ -21,6 +21,11 @@ function stubRuntime(overrides: Partial = {}): OrcaRuntimeSe // Why: every multiplex stream registers as a remote view subscriber for // Phase-5 query-authority suppression (terminal-query-authority.md). registerRemoteTerminalViewSubscriber: () => () => {}, + // Why: the multiplex subscribe path resolves handles via + // resolveLiveLeafForHandle (#7718). Default to a live pty so tests that + // only stub the legacy resolveLeafForHandle still bind; tests that need a + // null/stale leaf override this explicitly. + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), ...overrides } as OrcaRuntimeService } @@ -44,7 +49,7 @@ describe('terminal multiplex RPC', () => { current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void } = {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', @@ -261,7 +266,7 @@ describe('terminal multiplex RPC', () => { | undefined const restreamResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() @@ -374,7 +379,7 @@ describe('terminal multiplex RPC', () => { current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void } = {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', @@ -629,6 +634,9 @@ describe('terminal multiplex RPC', () => { resolveLeafForHandle: vi.fn((terminal: string) => ({ ptyId: terminal.replace('terminal-', 'pty-') })), + resolveLiveLeafForHandle: vi.fn((terminal: string) => ({ + ptyId: terminal.replace('terminal-', 'pty-') + })), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn(async (ptyId: string) => ({ data: `snapshot-${ptyId}`, @@ -1171,7 +1179,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi .fn() .mockResolvedValue({ tail: ['line 120'], truncated: false, limited: true }), @@ -1267,7 +1275,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() @@ -1375,7 +1383,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), @@ -1475,7 +1483,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), @@ -1999,7 +2007,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), waitForLeafPtyId: vi.fn( (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => new Promise((_resolve, reject) => { @@ -2079,8 +2087,13 @@ describe('terminal multiplex RPC', () => { let viewSubscriberCount = 0 let leafResolved = false let resolveFirstWait: (ptyId: string) => void = () => {} + // Why: the multiplex subscribe path resolves via resolveLiveLeafForHandle + // (#7718); null makes subscribe A block in waitForLeafPtyId until B resolves. + const resolveLeaf = (): { ptyId: string | null } => + leafResolved ? { ptyId: 'pty-1' } : { ptyId: null } const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn(() => (leafResolved ? { ptyId: 'pty-1' } : { ptyId: null })), + resolveLeafForHandle: vi.fn(resolveLeaf), + resolveLiveLeafForHandle: vi.fn(resolveLeaf), waitForLeafPtyId: vi.fn( () => new Promise((resolve) => { @@ -2197,6 +2210,9 @@ describe('terminal multiplex RPC', () => { }[] = [] const runtime = stubRuntime({ resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + // Why: the multiplex subscribe path resolves the leaf via + // resolveLiveLeafForHandle (#7718), so it must return a live pty here. + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), registerRemoteTerminalViewSubscriber: vi.fn(() => { viewSubscriberCount += 1 let released = false @@ -2286,6 +2302,78 @@ describe('terminal multiplex RPC', () => { expect(viewSubscriberCount).toBe(0) }) + it('rejects a stale terminal handle with terminal_handle_stale instead of binding the wrong PTY', async () => { + // Why: after a reconnect a client can resubscribe with a handle whose + // pane now hosts a different PTY. Binding the stream anyway would mirror + // (and type into) the wrong terminal (#7718); the client recovers from + // terminal_handle_stale by re-deriving the handle from the next snapshot. + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn(() => { + throw new Error('terminal_handle_stale') + }), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-stale-handle', + sendBinary: (bytes) => binaryFrames.push(bytes), + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 9, + terminal: 'stale-terminal', + client: { id: 'desktop-1', type: 'desktop' } + }) + }) + )! + ) + + await vi.waitFor(() => + expect( + messages + .map((msg) => JSON.parse(msg).result) + .some((result) => result?.type === 'end' && result.streamId === 9) + ).toBe(true) + ) + const errorFrame = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .find((frame) => frame?.opcode === TerminalStreamOpcode.Error) + expect(errorFrame && decodeTerminalStreamText(errorFrame.payload)).toBe('terminal_handle_stale') + // The stream must never have bound to any PTY. + expect(runtime.subscribeToTerminalData).not.toHaveBeenCalled() + + cleanups.get('terminal-multiplex:conn-stale-handle')?.() + await dispatchPromise + }) + it('bounds live output queued while a multiplex snapshot is loading', async () => { vi.useFakeTimers() try { @@ -2299,7 +2387,7 @@ describe('terminal multiplex RPC', () => { const dataListenerRef: { current?: (data: string) => void } = {} const snapshotResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => @@ -2408,7 +2496,7 @@ describe('terminal multiplex RPC', () => { const dataListenerRef: { current?: (data: string) => void } = {} const snapshotResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => @@ -2521,7 +2609,7 @@ describe('terminal multiplex RPC', () => { rows: number }) => void = () => {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() diff --git a/src/main/runtime/rpc/terminal-send.test.ts b/src/main/runtime/rpc/terminal-send.test.ts index 82e471000..b778f8149 100644 --- a/src/main/runtime/rpc/terminal-send.test.ts +++ b/src/main/runtime/rpc/terminal-send.test.ts @@ -75,9 +75,34 @@ describe('terminal send RPC', () => { expect(runtime.getTerminalAgentStatus).toHaveBeenCalledWith('terminal-1') }) + it('fails terminal.send with terminal_handle_stale for a stale handle instead of probing the wrong PTY', async () => { + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn(() => { + throw new Error('terminal_handle_stale') + }), + sendTerminal: vi.fn() + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('terminal.send', { + terminal: 'stale-terminal', + text: 'x', + client: { id: 'desktop-1', type: 'desktop' } + }) + ) + + expect(response.ok).toBe(false) + if (response.ok) { + throw new Error('expected stale handle error') + } + expect(response.error.message).toContain('terminal_handle_stale') + expect(runtime.sendTerminal).not.toHaveBeenCalled() + }) + it('drops desktop input while a mobile client owns the terminal floor', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'mobile', clientId: 'mobile-1' }), sendTerminal: vi.fn(), mobileTookFloor: vi.fn() @@ -109,7 +134,7 @@ describe('terminal send RPC', () => { it('accepts legacy clientless mobile input when the current driver is mobile', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'mobile', clientId: 'mobile-1' }), sendTerminal: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -198,7 +223,7 @@ describe('terminal send RPC', () => { vi.useFakeTimers() const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1) const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), sendTerminal: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -236,7 +261,7 @@ describe('terminal send RPC', () => { it('refuses guarded terminal sends when the agent needs permission', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -274,7 +299,7 @@ describe('terminal send RPC', () => { it('allows guarded terminal sends when the agent is sendable', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -316,7 +341,7 @@ describe('terminal send RPC', () => { it('refuses guarded combined text and submit sends before any PTY write', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn(), sendTerminal: vi.fn() @@ -350,7 +375,7 @@ describe('terminal send RPC', () => { it('rechecks the mobile floor lock immediately before guarded PTY writes', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi .fn() .mockReturnValueOnce({ kind: 'desktop' }) diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index a5418500c..c2f949c27 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -308,6 +308,8 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'settings.update', 'ssh.connect', 'ssh.getState', + 'ssh.listRemovedTargetLabels', + 'ssh.listTargets', 'speech.dictation.cancel', 'speech.dictation.chunk', 'speech.dictation.finish', diff --git a/src/main/ssh/ssh-channel-multiplexer.test.ts b/src/main/ssh/ssh-channel-multiplexer.test.ts index 8c56ae145..10123d56a 100644 --- a/src/main/ssh/ssh-channel-multiplexer.test.ts +++ b/src/main/ssh/ssh-channel-multiplexer.test.ts @@ -307,6 +307,81 @@ describe('SshChannelMultiplexer', () => { }) }) + describe('wake guard (timer pause across system sleep, #7773)', () => { + it('does not kill a healthy link on the first tick after a long timer pause', () => { + // Reach steady state with pending unacked keepalives (<5s old at pause). + vi.advanceTimersByTime(5_000) + expect(mux.isDisposed()).toBe(false) + + // Simulate sleep/App Nap: wall clock jumps far ahead with no ticks. + // Without the guard, the first post-wake tick sees lastReceivedAt and + // the pre-pause keepalive both >20s stale and disposes the mux. + vi.setSystemTime(Date.now() + 60 * 60 * 1000) + const writesBefore = transport.written.length + vi.advanceTimersByTime(5_000) + + expect(mux.isDisposed()).toBe(false) + // The guard probes immediately with a fresh keepalive. + expect(transport.written.length).toBeGreaterThan(writesBefore) + expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive) + }) + + it('keeps the link alive after wake when frames resume', () => { + vi.advanceTimersByTime(5_000) + vi.setSystemTime(Date.now() + 60 * 60 * 1000) + vi.advanceTimersByTime(5_000) // guard tick + + // The relay answers the post-wake probe; the link must stay up. + let seq = 1 + for (let i = 0; i < 8; i++) { + vi.advanceTimersByTime(5_000) + transport.dataCallbacks[0](encodeKeepAliveFrame(seq++, 0)) + } + expect(mux.isDisposed()).toBe(false) + }) + + it('still detects a genuinely dead link within the next window after wake', () => { + vi.advanceTimersByTime(5_000) + vi.setSystemTime(Date.now() + 60 * 60 * 1000) + vi.advanceTimersByTime(5_000) // guard tick: reset + probe, no kill + + expect(mux.isDisposed()).toBe(false) + // No frames arrive after the guard reset; the honest window expires. + vi.advanceTimersByTime(25_000) + expect(mux.isDisposed()).toBe(true) + }) + }) + + describe('probeLiveness', () => { + it('sends a keepalive and resolves true when any frame arrives', async () => { + const writesBefore = transport.written.length + const probe = mux.probeLiveness(5_000) + + expect(transport.written.length).toBe(writesBefore + 1) + expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive) + + transport.dataCallbacks[0](encodeKeepAliveFrame(1, 0)) + await expect(probe).resolves.toBe(true) + }) + + it('resolves false when no frame arrives before the timeout', async () => { + const probe = mux.probeLiveness(5_000) + vi.advanceTimersByTime(5_000) + await expect(probe).resolves.toBe(false) + }) + + it('resolves false when the mux is disposed while probing', async () => { + const probe = mux.probeLiveness(5_000) + mux.dispose() + await expect(probe).resolves.toBe(false) + }) + + it('resolves false immediately on a disposed mux', async () => { + mux.dispose() + await expect(mux.probeLiveness(5_000)).resolves.toBe(false) + }) + }) + describe('dispose', () => { it('rejects all pending requests on dispose', async () => { const promise = mux.request('pty.spawn') diff --git a/src/main/ssh/ssh-channel-multiplexer.ts b/src/main/ssh/ssh-channel-multiplexer.ts index 09642387e..8cb0a24f3 100644 --- a/src/main/ssh/ssh-channel-multiplexer.ts +++ b/src/main/ssh/ssh-channel-multiplexer.ts @@ -34,6 +34,9 @@ export type MethodNotificationHandler = (params: Record) => voi export type RequestHandler = (params: Record) => Promise | unknown const REQUEST_TIMEOUT_MS = 30_000 +// Why: a tick gap far beyond the interval means the process was paused +// (system sleep, App Nap timer throttling) — not that the link is dead (#7773). +const WAKE_GAP_MS = KEEPALIVE_SEND_MS * 3 export class SshChannelMultiplexer { private decoder: FrameDecoder @@ -58,6 +61,10 @@ export class SshChannelMultiplexer { // Track the oldest unacked outgoing message timestamp private unackedTimestamps = new Map() + // Why: liveness probes (#7773) resolve on the first frame of any kind — + // a keepalive ack proves the relay round-trip without a full RPC. + private livenessProbeWaiters: { succeed: () => void; fail: () => void }[] = [] + constructor(transport: MultiplexerTransport) { this.transport = transport @@ -232,6 +239,31 @@ export class SshChannelMultiplexer { this.sendMessage(msg) } + /** + * Send a fresh keepalive and resolve true when any frame arrives before the + * timeout. Used on system resume to distinguish a link that survived sleep + * from a dead one before tearing the session down (#7773). + */ + probeLiveness(timeoutMs: number): Promise { + if (this.disposed) { + return Promise.resolve(false) + } + return new Promise((resolve) => { + const settle = (alive: boolean): void => { + clearTimeout(timer) + const idx = this.livenessProbeWaiters.indexOf(waiter) + if (idx !== -1) { + this.livenessProbeWaiters.splice(idx, 1) + } + resolve(alive) + } + const waiter = { succeed: () => settle(true), fail: () => settle(false) } + const timer = setTimeout(() => settle(false), timeoutMs) + this.livenessProbeWaiters.push(waiter) + this.sendKeepAlive() + }) + } + dispose(reason: 'shutdown' | 'connection_lost' = 'shutdown'): void { if (this.disposed) { return @@ -259,6 +291,10 @@ export class SshChannelMultiplexer { reason === 'connection_lost' ? 'SSH connection lost, reconnecting...' : 'Multiplexer disposed' const errorCode = reason === 'connection_lost' ? 'CONNECTION_LOST' : 'DISPOSED' + for (const waiter of this.livenessProbeWaiters.splice(0)) { + waiter.fail() + } + for (const [id, pending] of this.pendingRequests) { pending.cleanup() const err = new Error(errorMessage) as Error & { code: string } @@ -322,6 +358,12 @@ export class SshChannelMultiplexer { } private handleFrame(frame: DecodedFrame): void { + // Why: any decoded frame proves the relay round-trip is alive; resolve + // pending resume probes before ordinary dispatch (#7773). + for (const waiter of this.livenessProbeWaiters.splice(0)) { + waiter.succeed() + } + // Update ack tracking if (frame.id > this.highestReceivedSeq) { this.highestReceivedSeq = frame.id @@ -453,12 +495,28 @@ export class SshChannelMultiplexer { } private startTimeoutCheck(): void { + let lastTickAt = Date.now() this.timeoutTimer = setInterval(() => { if (this.disposed) { return } const now = Date.now() + const sinceLastTick = now - lastTickAt + lastTickAt = now + // Why: after sleep/App Nap the pre-pause keepalive looks stale on the + // first post-wake tick, killing a healthy link (#7773). Reset staleness + // tracking, probe with a fresh keepalive, and let the NEXT full window + // make an honest liveness determination. + if (sinceLastTick > WAKE_GAP_MS) { + this.lastReceivedAt = now + for (const seq of this.unackedTimestamps.keys()) { + this.unackedTimestamps.set(seq, now) + } + this.sendKeepAlive() + return + } + const noDataReceived = now - this.lastReceivedAt > TIMEOUT_MS // Check oldest unacked message diff --git a/src/main/ssh/ssh-connection-store.test.ts b/src/main/ssh/ssh-connection-store.test.ts index f1bf80d17..02e69c6dc 100644 --- a/src/main/ssh/ssh-connection-store.test.ts +++ b/src/main/ssh/ssh-connection-store.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { SshConnectionStore } from './ssh-connection-store' -import type { SshTarget } from '../../shared/ssh-types' +import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), @@ -15,6 +15,8 @@ vi.mock('./ssh-config-parser', () => ({ function createMockStore() { const targets: SshTarget[] = [] let deletedAliases: string[] = [] + const removedTombstones: RemovedSshTargetTombstone[] = [] + const reassignments: { oldTargetId: string; newTargetId: string }[] = [] return { getSshTargets: vi.fn(() => [...targets]), @@ -45,6 +47,24 @@ function createMockStore() { }), clearDeletedSshConfigAliases: vi.fn(() => { deletedAliases = [] + }), + removedTombstones, + reassignments, + getRemovedSshTargetTombstones: vi.fn(() => [...removedTombstones]), + addRemovedSshTargetTombstone: vi.fn((tombstone: RemovedSshTargetTombstone) => { + const filtered = removedTombstones.filter((t) => t.oldTargetId !== tombstone.oldTargetId) + removedTombstones.length = 0 + removedTombstones.push(...filtered, tombstone) + }), + removeRemovedSshTargetTombstone: vi.fn((oldTargetId: string) => { + const kept = removedTombstones.filter((t) => t.oldTargetId !== oldTargetId) + removedTombstones.length = 0 + removedTombstones.push(...kept) + }), + reassignSshTargetId: vi.fn((oldTargetId: string, newTargetId: string) => { + reassignments.push({ oldTargetId, newTargetId }) + // Pretend one repo referenced the old id. + return 1 }) } } @@ -439,4 +459,140 @@ describe('SshConnectionStore', () => { expect(result).toHaveLength(1) }) }) + + describe('re-adoption of orphaned workspaces', () => { + it('records a tombstone when removing any user-facing target', () => { + mockStore.addSshTarget({ + id: 'ssh-1', + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim', + source: 'manual' + }) + + sshStore.removeTarget('ssh-1') + + expect(mockStore.addRemovedSshTargetTombstone).toHaveBeenCalledWith( + expect.objectContaining({ + oldTargetId: 'ssh-1', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + ) + }) + + it('does not tombstone runtime-owned targets', () => { + mockStore.addSshTarget({ + id: 'runtime-ssh-abc', + label: 'VM', + host: 'vm.example.com', + port: 22, + username: 'tim', + owner: { type: 'on-demand-runtime', runtimeId: 'abc' } + }) + + sshStore.removeTarget('runtime-ssh-abc') + + expect(mockStore.addRemovedSshTargetTombstone).not.toHaveBeenCalled() + }) + + it('re-adopts orphaned repos when the same host is re-added', () => { + // Simulate a prior removal by seeding a matching tombstone. + mockStore.addRemovedSshTargetTombstone({ + oldTargetId: 'ssh-old', + host: 'dev.example.com', + port: 22, + username: 'tim', + label: 'Dev', + removedAt: 1 + }) + + sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + + expect(mockStore.reassignSshTargetId).toHaveBeenCalledTimes(1) + const [oldId, newId] = mockStore.reassignSshTargetId.mock.calls[0] + expect(oldId).toBe('ssh-old') + expect(newId).toMatch(/^ssh-/) + // Re-adoption count surfaces so the IPC layer can refresh the repo list. + expect(sshStore.lastReadoptedRepoCount).toBe(1) + }) + + // Why: drive the real remove→re-add path so the tombstone carries the + // defaulted configHost (host) that buildRemovedSshTargetTombstone produces, + // rather than a hand-seeded tombstone without one. + it('re-adopts through an actual removeTarget then re-add of the same host', () => { + const added = sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + sshStore.removeTarget(added.id) + // The tombstone was built from the real target (configHost defaulted to host). + const tombstones = mockStore.getRemovedSshTargetTombstones() + expect(tombstones).toHaveLength(1) + expect(tombstones[0]).toMatchObject({ oldTargetId: added.id, configHost: 'dev.example.com' }) + + mockStore.reassignSshTargetId.mockClear() + const readded = sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + + expect(mockStore.reassignSshTargetId).toHaveBeenCalledWith(added.id, readded.id) + expect(sshStore.lastReadoptedRepoCount).toBe(1) + }) + + // A different account on the SAME host must NOT re-adopt, even though both + // manual adds default configHost to the shared hostname. + it('does not re-adopt a different account on the same host', () => { + const alice = sshStore.addTarget({ + label: 'alice', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + sshStore.removeTarget(alice.id) + mockStore.reassignSshTargetId.mockClear() + + sshStore.addTarget({ + label: 'bob', + host: 'dev.example.com', + port: 2222, + username: 'bob' + }) + + expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled() + }) + + it('does not re-adopt when the re-added host identity differs', () => { + mockStore.addRemovedSshTargetTombstone({ + oldTargetId: 'ssh-old', + host: 'other.example.com', + port: 22, + username: 'root', + label: 'Other', + removedAt: 1 + }) + + sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + + expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled() + expect(sshStore.lastReadoptedRepoCount).toBe(0) + }) + }) }) diff --git a/src/main/ssh/ssh-connection-store.ts b/src/main/ssh/ssh-connection-store.ts index 975da8cdb..df3e6cd8f 100644 --- a/src/main/ssh/ssh-connection-store.ts +++ b/src/main/ssh/ssh-connection-store.ts @@ -2,6 +2,10 @@ import type { Store } from '../persistence' import type { SshTarget } from '../../shared/ssh-types' import { RUNTIME_OWNED_SSH_TARGET_ID_PREFIX } from '../../shared/execution-host' import { loadUserSshConfig, sshConfigHostsToTargets } from './ssh-config-parser' +import { + buildRemovedSshTargetTombstone, + readoptOrphanedWorkspacesForTarget +} from './ssh-target-readoption' export class SshConnectionStore { constructor(private store: Store) {} @@ -10,6 +14,17 @@ export class SshConnectionStore { return this.store.getSshTargets().filter((target) => !isRuntimeOwnedSshTarget(target)) } + /** Map of removed-target id → its last known label, from the re-adoption + * tombstones. Lets the renderer show a friendly host name for a workspace + * still pinned to a target that no longer exists. */ + listRemovedTargetLabels(): Record { + const labels: Record = {} + for (const tombstone of this.store.getRemovedSshTargetTombstones()) { + labels[tombstone.oldTargetId] = tombstone.label + } + return labels + } + getTarget(id: string): SshTarget | undefined { return this.store.getSshTarget(id) } @@ -27,9 +42,17 @@ export class SshConnectionStore { // keep it — lift any tombstone so config sync stops suppressing this alias. this.reclaimAlias(full.configHost ?? full.label) this.store.addSshTarget(full) + // Why: re-adopt workspaces that were orphaned when the same host was removed + // (repos/worktrees still point at the old, now-dead target id). Track the + // count so the IPC layer knows whether to refresh the repo list. + this.lastReadoptedRepoCount = readoptOrphanedWorkspacesForTarget(this.store, full) return full } + /** Repos re-adopted by the most recent addTarget/importFromSshConfig call. + * Lets the IPC layer broadcast repos:changed only when workspaces reattached. */ + lastReadoptedRepoCount = 0 + upsertRuntimeOwnedTarget( runtimeId: string, target: Omit @@ -75,6 +98,13 @@ export class SshConnectionStore { this.store.addDeletedSshConfigAlias(alias) } } + // Why: record the removed target's host identity (for ALL user-facing + // targets, config-managed or manual) so a later re-add of the same host can + // re-adopt any workspaces orphaned on this id. Runtime-owned targets manage + // their own lifecycle and are never re-adopted. + if (target && !isRuntimeOwnedSshTarget(target)) { + this.store.addRemovedSshTargetTombstone(buildRemovedSshTargetTombstone(target, Date.now())) + } this.store.removeSshTarget(id) } @@ -90,6 +120,7 @@ export class SshConnectionStore { * manual targets. Returns the inserted and updated targets. */ importFromSshConfig(options?: { reAdopt?: boolean }): SshTarget[] { + let readoptedThisImport = 0 // Why: the explicit Import action re-adopts every config host, so it clears // all tombstones first. The passive on-open sync passes no flag and keeps // deleted hosts suppressed. @@ -178,10 +209,15 @@ export class SshConnectionStore { } else { const inserted: SshTarget = { ...candidate, source: 'ssh-config' } this.store.addSshTarget(inserted) + // Why: a freshly-inserted config host may be one the user removed and is + // now re-importing — re-adopt its orphaned workspaces. Updated-in-place + // targets keep their id, so their repos were never orphaned. + readoptedThisImport += readoptOrphanedWorkspacesForTarget(this.store, inserted) changed.push(inserted) } } + this.lastReadoptedRepoCount = readoptedThisImport return changed } } diff --git a/src/main/ssh/ssh-port-scanner.test.ts b/src/main/ssh/ssh-port-scanner.test.ts new file mode 100644 index 000000000..09be7c1f6 --- /dev/null +++ b/src/main/ssh/ssh-port-scanner.test.ts @@ -0,0 +1,261 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + PortScanner, + SSH_PORT_SCAN_BASE_INTERVAL_MS, + SSH_PORT_SCAN_MAX_INTERVAL_MS, + type PortScannerWindowVisibility +} from './ssh-port-scanner' +import type { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import type { DetectedPort } from '../../shared/ssh-types' + +type VisibilityHarness = { + visibility: PortScannerWindowVisibility + setVisible: (visible: boolean) => void + listenerCount: () => number +} + +function createVisibilityHarness(initiallyVisible: boolean): VisibilityHarness { + let visible = initiallyVisible + const listeners = new Set<() => void>() + return { + visibility: { + isWindowVisible: () => visible, + onWindowBecameVisible: (listener) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + } + }, + setVisible: (next) => { + const wasVisible = visible + visible = next + if (!wasVisible && next) { + for (const listener of Array.from(listeners)) { + listener() + } + } + }, + listenerCount: () => listeners.size + } +} + +function port(portNumber: number): DetectedPort { + return { port: portNumber, host: '127.0.0.1', pid: 100 + portNumber, processName: 'node' } +} + +function createMux(ports: () => DetectedPort[]): { + mux: SshChannelMultiplexer + request: ReturnType +} { + const request = vi.fn(async () => ({ ports: ports(), platform: 'linux' })) + return { mux: { request } as unknown as SshChannelMultiplexer, request } +} + +const BASE = SSH_PORT_SCAN_BASE_INTERVAL_MS +const MAX = SSH_PORT_SCAN_MAX_INTERVAL_MS + +describe('PortScanner', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('sends zero ports.detect requests while the window is hidden, then scans immediately on show', async () => { + const harness = createVisibilityHarness(false) + const { mux, request } = createMux(() => [port(3000)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + + await vi.advanceTimersByTimeAsync(10 * 60_000) + expect(request).not.toHaveBeenCalled() + + harness.setVisible(true) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + + scanner.dispose() + }) + + it('polls at the base cadence while visible when results keep changing', async () => { + const harness = createVisibilityHarness(true) + let next = 3000 + const { mux, request } = createMux(() => [port(next++)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + + // 5 simulated base intervals -> 5 more scans (no backoff while changing). + await vi.advanceTimersByTimeAsync(5 * BASE) + expect(request).toHaveBeenCalledTimes(6) + + scanner.dispose() + }) + + it('doubles the interval up to the cap while unchanged and resets to base on a change', async () => { + const harness = createVisibilityHarness(true) + let ports = [port(3000)] + const { mux, request } = createMux(() => ports) + const onChanged = vi.fn() + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, onChanged) + + // t=0: first scan is a change (empty -> {3000}) and stays at base. + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + expect(onChanged).toHaveBeenCalledTimes(1) + + // t=12s: unchanged -> next wait doubles to 24s. + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + // t=24s: nothing (waiting until t=36s). + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + // t=36s: unchanged -> next wait caps at 30s (not 48s). + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(3) + + // t=65.999s: still waiting. + await vi.advanceTimersByTimeAsync(MAX - 1) + expect(request).toHaveBeenCalledTimes(3) + + // t=66s: unchanged -> next wait remains capped at 30s. + await vi.advanceTimersByTimeAsync(1) + expect(request).toHaveBeenCalledTimes(4) + + await vi.advanceTimersByTimeAsync(MAX - 1) + expect(request).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(1) + expect(request).toHaveBeenCalledTimes(5) + expect(onChanged).toHaveBeenCalledTimes(1) + + // A changed result resets the cadence back to base. + ports = [port(3000), port(4000)] + await vi.advanceTimersByTimeAsync(MAX) + expect(request).toHaveBeenCalledTimes(6) + expect(onChanged).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(7) + expect(scanner.getDetectedPorts('t1').map((p) => p.port)).toEqual([3000, 4000]) + + scanner.dispose() + }) + + it('resets backoff and scans immediately when scanning restarts (reconnect/session-ready)', async () => { + const harness = createVisibilityHarness(true) + const { mux, request } = createMux(() => [port(3000)]) + const scanner = new PortScanner(harness.visibility) + const onChanged = vi.fn() + scanner.startScanning('t1', mux, onChanged) + + // Back off: scans at t=0, t=12s, t=36s -> interval now 48s. + await vi.advanceTimersByTimeAsync(3 * BASE) + expect(request).toHaveBeenCalledTimes(3) + + // Reconnect paths call startScanning again: immediate scan, base cadence. + scanner.startScanning('t1', mux, onChanged) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(5) + + scanner.dispose() + }) + + it('parks when the window hides mid-run and resumes with an immediate scan on show', async () => { + const harness = createVisibilityHarness(true) + let next = 3000 + const { mux, request } = createMux(() => [port(next++)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + harness.setVisible(false) + await vi.advanceTimersByTimeAsync(30 * 60_000) + expect(request).toHaveBeenCalledTimes(2) + + harness.setVisible(true) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(4) + + scanner.dispose() + }) + + it('never overlaps a slow in-flight request and resumes the chain after it settles', async () => { + const harness = createVisibilityHarness(true) + let resolveFirst: ((value: { ports: DetectedPort[]; platform: string }) => void) | null = null + const request = vi.fn( + () => + new Promise<{ ports: DetectedPort[]; platform: string }>((resolve) => { + resolveFirst = resolve + }) + ) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', { request } as unknown as SshChannelMultiplexer, vi.fn()) + expect(request).toHaveBeenCalledTimes(1) + + // The chain waits for the in-flight request instead of stacking more. + await vi.advanceTimersByTimeAsync(10 * BASE) + expect(request).toHaveBeenCalledTimes(1) + + resolveFirst!({ ports: [port(3000)], platform: 'linux' }) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + scanner.dispose() + }) + + it('stopScanning halts polling and detaches the visibility listener', async () => { + const harness = createVisibilityHarness(true) + const { mux, request } = createMux(() => [port(3000)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + expect(harness.listenerCount()).toBe(1) + + scanner.stopScanning('t1') + expect(harness.listenerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(10 * 60_000) + harness.setVisible(false) + harness.setVisible(true) + await vi.advanceTimersByTimeAsync(10 * 60_000) + expect(request).toHaveBeenCalledTimes(1) + expect(scanner.getDetectedPorts('t1')).toEqual([]) + }) + + it('keeps targets independent: stopping one host leaves the other scanning', async () => { + const harness = createVisibilityHarness(true) + let nextA = 3000 + let nextB = 4000 + const a = createMux(() => [port(nextA++)]) + const b = createMux(() => [port(nextB++)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('host-a', a.mux, vi.fn()) + scanner.startScanning('host-b', b.mux, vi.fn()) + await vi.advanceTimersByTimeAsync(0) + expect(a.request).toHaveBeenCalledTimes(1) + expect(b.request).toHaveBeenCalledTimes(1) + + scanner.stopScanning('host-a') + await vi.advanceTimersByTimeAsync(BASE) + expect(a.request).toHaveBeenCalledTimes(1) + expect(b.request).toHaveBeenCalledTimes(2) + + scanner.dispose() + await vi.advanceTimersByTimeAsync(10 * BASE) + expect(b.request).toHaveBeenCalledTimes(2) + expect(harness.listenerCount()).toBe(0) + }) +}) diff --git a/src/main/ssh/ssh-port-scanner.ts b/src/main/ssh/ssh-port-scanner.ts index 3746308db..6404d035f 100644 --- a/src/main/ssh/ssh-port-scanner.ts +++ b/src/main/ssh/ssh-port-scanner.ts @@ -1,10 +1,30 @@ import type { SshChannelMultiplexer } from './ssh-channel-multiplexer' import type { DetectedPort } from '../../shared/ssh-types' -const POLL_INTERVAL_MS = 3_000 +// Why: every tick walks /proc/*/fd on the remote relay, so cadence is remote +// CPU, not just a local timer. 12s cuts steady-state request volume 4x vs the +// old 3s while keeping new-port detection well under the 30s workspace-scanner +// cadence users already accept. +export const SSH_PORT_SCAN_BASE_INTERVAL_MS = 12_000 +// Why: idle backoff cap — an unchanged port set doubles the interval up to +// this bound, so a quiet remote costs two scans per minute instead of twenty +// without exceeding the existing workspace-port scanner's visible cadence. +export const SSH_PORT_SCAN_MAX_INTERVAL_MS = 30_000 + +export type PortScannerWindowVisibility = { + isWindowVisible: () => boolean + // Fires when a hidden/minimized window is shown again; returns unsubscribe. + onWindowBecameVisible: (listener: () => void) => () => void +} type ScanHandle = { - timer: ReturnType + timer: ReturnType | null + intervalMs: number + // Why: while the window is hidden the scan chain is parked outright — no + // timer wakeups, no remote requests — and the visibility listener resumes + // it with an immediate scan so ports opened while hidden surface at once. + parkedWhileHidden: boolean + unsubscribeVisibility: () => void // Why: keyed by "host:port" (not just port) so that host-distinct listeners // on the same port (e.g. 127.0.0.1:3000 + 0.0.0.0:3000) are tracked separately. previousPorts: Map @@ -17,6 +37,8 @@ type ScanHandle = { export class PortScanner { private handles = new Map() + constructor(private visibility: PortScannerWindowVisibility) {} + startScanning( targetId: string, mux: SshChannelMultiplexer, @@ -25,14 +47,18 @@ export class PortScanner { this.stopScanning(targetId) const handle: ScanHandle = { - timer: null!, + timer: null, + intervalMs: SSH_PORT_SCAN_BASE_INTERVAL_MS, + parkedWhileHidden: false, + unsubscribeVisibility: () => {}, previousPorts: new Map(), initialPorts: null } + const isCurrent = (): boolean => this.handles.get(targetId) === handle - // Why: guard against overlapping scans. On slow remotes, /proc/*/fd walks - // can take longer than POLL_INTERVAL_MS. Without this guard, setInterval - // would stack up concurrent requests on the shared SSH multiplexer. + // Why: guard against overlapping scans. The timer chain only reschedules + // after a poll completes, but the visibility-resume path can race a poll + // still in flight on a slow remote. let polling = false const poll = async (): Promise => { if (polling) { @@ -45,7 +71,7 @@ export class PortScanner { platform: string } - if (!this.handles.has(targetId)) { + if (!isCurrent()) { return } @@ -60,7 +86,10 @@ export class PortScanner { if (!portsEqual(handle.previousPorts, currentPorts)) { handle.previousPorts = currentPorts + handle.intervalMs = SSH_PORT_SCAN_BASE_INTERVAL_MS onChanged(targetId, result.ports, result.platform) + } else { + handle.intervalMs = Math.min(handle.intervalMs * 2, SSH_PORT_SCAN_MAX_INTERVAL_MS) } } catch { // Relay disconnected or request timed out — retry on next interval @@ -69,10 +98,32 @@ export class PortScanner { } } - handle.timer = setInterval(() => void poll(), POLL_INTERVAL_MS) - this.handles.set(targetId, handle) + const tick = async (): Promise => { + handle.timer = null + if (!isCurrent()) { + return + } + if (!this.visibility.isWindowVisible()) { + handle.parkedWhileHidden = true + return + } + await poll() + if (!isCurrent()) { + return + } + handle.timer = setTimeout(() => void tick(), handle.intervalMs) + } - void poll() + handle.unsubscribeVisibility = this.visibility.onWindowBecameVisible(() => { + if (!isCurrent() || !handle.parkedWhileHidden) { + return + } + handle.parkedWhileHidden = false + void tick() + }) + + this.handles.set(targetId, handle) + void tick() } getDetectedPorts(targetId: string): DetectedPort[] { @@ -88,7 +139,10 @@ export class PortScanner { if (!handle) { return } - clearInterval(handle.timer) + if (handle.timer) { + clearTimeout(handle.timer) + } + handle.unsubscribeVisibility() this.handles.delete(targetId) } diff --git a/src/main/ssh/ssh-relay-session.test.ts b/src/main/ssh/ssh-relay-session.test.ts index 03e5145c8..0355ac944 100644 --- a/src/main/ssh/ssh-relay-session.test.ts +++ b/src/main/ssh/ssh-relay-session.test.ts @@ -124,6 +124,10 @@ function createMockDeps() { } as unknown as SshPortForwardManager const mockWindow = { isDestroyed: () => false, + // Why: the port scanner visibility-gates its ticks; a visible mock window + // keeps establish-path tests exercising the scan-on-ready behavior. + isVisible: () => true, + isMinimized: () => false, webContents: { send: vi.fn() } } const getMainWindow = vi.fn().mockReturnValue(mockWindow) diff --git a/src/main/ssh/ssh-relay-session.ts b/src/main/ssh/ssh-relay-session.ts index d2b8e1340..3f6e2e208 100644 --- a/src/main/ssh/ssh-relay-session.ts +++ b/src/main/ssh/ssh-relay-session.ts @@ -57,6 +57,7 @@ import { import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' import { notifyRemoteWorkspaceHandlers } from '../ipc/remote-workspace-events' import { PortScanner } from './ssh-port-scanner' +import { isMainWindowVisible, onMainWindowBecameVisible } from '../window/main-window-visibility' import type { SshPortForwardManager } from './ssh-port-forward' import type { SshConnection } from './ssh-connection' import { joinRemotePath, isWindowsRemoteHost, type RemoteHostPlatform } from './ssh-remote-platform' @@ -987,7 +988,13 @@ export class SshRelaySession { if (!this.mux || this.isDisposed()) { return } - const scanner = new PortScanner() + // Why: each scan walks /proc/*/fd on the remote host, so the scanner skips + // ticks entirely while no window can show the results (hidden to tray or + // minimized overnight) and rescans immediately when the window returns. + const scanner = new PortScanner({ + isWindowVisible: () => isMainWindowVisible(this.getMainWindow()), + onWindowBecameVisible: onMainWindowBecameVisible + }) this.portScanner = scanner // Why: capture the scanner instance so that a late ports.detect callback // from a previous relay session (before reconnect replaced it) is silently diff --git a/src/main/ssh/ssh-remote-cli-host-passthrough.test.ts b/src/main/ssh/ssh-remote-cli-host-passthrough.test.ts new file mode 100644 index 000000000..22920a666 --- /dev/null +++ b/src/main/ssh/ssh-remote-cli-host-passthrough.test.ts @@ -0,0 +1,250 @@ +import { EventEmitter } from 'node:events' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + isPackaged: false, + getAppPath: () => '/host/app' + } +})) +vi.mock('../persistence', () => ({ + getCanonicalUserDataPath: () => '/host/user-data' +})) + +import { + HostCliUnavailableError, + buildHostCliEnv, + resolveHostCliEntryPath, + resolveHostCliKillTimeoutMs, + runHostOrcaCliPassthrough +} from './ssh-remote-cli-host-passthrough' + +type FakeChild = EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + stdin: { end: ReturnType; on: ReturnType } + kill: ReturnType +} + +function createFakeChild(): FakeChild { + const child = new EventEmitter() as FakeChild + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.stdin = { end: vi.fn(), on: vi.fn() } + child.kill = vi.fn() + return child +} + +const BASE_OPTIONS = { + execPath: '/host/electron', + cliEntryPath: '/host/app/out/cli/index.js', + userDataPath: '/host/user-data', + entryExists: () => true +} + +describe('resolveHostCliEntryPath', () => { + it('uses the in-repo entry for dev builds and the unpacked asar entry when packaged', () => { + expect( + resolveHostCliEntryPath({ isPackaged: false, resourcesPath: '/r', appPath: '/host/app' }) + ).toBe(join('/host/app', 'out', 'cli', 'index.js')) + expect( + resolveHostCliEntryPath({ isPackaged: true, resourcesPath: '/r', appPath: '/host/app' }) + ).toBe(join('/r', 'app.asar.unpacked', 'out', 'cli', 'index.js')) + }) +}) + +describe('buildHostCliEnv', () => { + it('forwards only Orca terminal-context vars from the remote env', () => { + const env = buildHostCliEnv({ + hostEnv: { PATH: '/host/bin', NODE_OPTIONS: '--inspect' }, + remoteEnv: { + ORCA_TERMINAL_HANDLE: 'term_remote', + ORCA_WORKTREE_ID: 'repo::/home/alice/wt', + ORCA_PANE_KEY: 'pane-9', + ORCA_WORKSPACE_ID: 'ws-1', + // Why: these are remote-machine paths and must not leak into the host + // subprocess (PATH would break host binary lookup; user-data would + // retarget the CLI at a different local instance). + PATH: '/remote/bin', + ORCA_USER_DATA_PATH: '/remote/user-data' + }, + userDataPath: '/host/user-data', + remoteCwd: '/home/alice/wt/sub' + }) + + expect(env.ORCA_TERMINAL_HANDLE).toBe('term_remote') + expect(env.ORCA_WORKTREE_ID).toBe('repo::/home/alice/wt') + expect(env.ORCA_PANE_KEY).toBe('pane-9') + expect(env.ORCA_WORKSPACE_ID).toBe('ws-1') + expect(env.PATH).toBe('/host/bin') + expect(env.ORCA_USER_DATA_PATH).toBe('/host/user-data') + expect(env.ORCA_CLI_CWD).toBe('/home/alice/wt/sub') + expect(env.ELECTRON_RUN_AS_NODE).toBe('1') + expect(env.NODE_OPTIONS).toBeUndefined() + expect(env.ORCA_NODE_OPTIONS).toBe('--inspect') + }) +}) + +describe('resolveHostCliKillTimeoutMs', () => { + it('extends the kill timer past an explicit --timeout-ms budget', () => { + expect(resolveHostCliKillTimeoutMs(['terminal', 'wait', '--timeout-ms', '1800000'])).toBe( + 1_920_000 + ) + expect(resolveHostCliKillTimeoutMs(['orchestration', 'check', '--timeout-ms=5000'])).toBe( + 600_000 + ) + expect(resolveHostCliKillTimeoutMs(['worktree', 'list'])).toBe(600_000) + }) +}) + +describe('runHostOrcaCliPassthrough', () => { + it('spawns the bundled CLI entry with the remote argv and returns captured output', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { + argv: ['orchestration', 'task-create', '--spec', 'do the thing', '--json'], + cwd: '/home/alice/wt', + env: { ORCA_TERMINAL_HANDLE: 'term_remote' } + }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.stdout.emit('data', Buffer.from('{"ok":true}\n')) + child.stderr.emit('data', Buffer.from('warn\n')) + child.emit('close', 0) + + const result = await resultPromise + expect(result).toEqual({ stdout: '{"ok":true}\n', stderr: 'warn\n', exitCode: 0 }) + + expect(spawn).toHaveBeenCalledTimes(1) + const [execPath, args, options] = spawn.mock.calls[0] as unknown as [ + string, + string[], + { env: NodeJS.ProcessEnv } + ] + expect(execPath).toBe('/host/electron') + expect(args).toEqual([ + '/host/app/out/cli/index.js', + 'orchestration', + 'task-create', + '--spec', + 'do the thing', + '--json' + ]) + expect(options.env.ELECTRON_RUN_AS_NODE).toBe('1') + expect(options.env.ORCA_CLI_CWD).toBe('/home/alice/wt') + expect(options.env.ORCA_TERMINAL_HANDLE).toBe('term_remote') + // Why: stdin must be closed even without a payload so CLI handlers that + // stream stdin see EOF instead of hanging forever. + expect(child.stdin.end).toHaveBeenCalledWith() + }) + + it('pipes a stdin payload to the CLI subprocess', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { + argv: ['linear', 'comment', 'add', 'ENG-1', '--body-file', '-'], + cwd: '/home/alice/wt', + env: {}, + stdin: 'comment body' + }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.emit('close', 0) + await resultPromise + + expect(child.stdin.end).toHaveBeenCalledWith('comment body') + }) + + it('propagates non-zero exit codes', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['worktree', 'show'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.stderr.emit('data', Buffer.from('boom\n')) + child.emit('close', 3) + + await expect(resultPromise).resolves.toEqual({ stdout: '', stderr: 'boom\n', exitCode: 3 }) + }) + + it('throws HostCliUnavailableError when the CLI entry is missing', async () => { + const spawn = vi.fn() + await expect( + runHostOrcaCliPassthrough( + { argv: ['status'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, entryExists: () => false, spawn: spawn as never } + ) + ).rejects.toBeInstanceOf(HostCliUnavailableError) + expect(spawn).not.toHaveBeenCalled() + }) + + it('throws HostCliUnavailableError when the subprocess fails to launch', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['status'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.emit('error', new Error('spawn ENOENT')) + + await expect(resultPromise).rejects.toBeInstanceOf(HostCliUnavailableError) + }) + + it('kills the subprocess and reports an error when the kill timeout elapses', async () => { + vi.useFakeTimers() + try { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['terminal', 'wait', '--for', 'exit'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never, killTimeoutMs: 1000 } + ) + + await vi.advanceTimersByTimeAsync(1001) + const result = await resultPromise + expect(child.kill).toHaveBeenCalledWith('SIGKILL') + expect(result.exitCode).toBe(1) + expect(result.stderr).toContain('timed out') + } finally { + vi.useRealTimers() + } + }) + + it('caps runaway output instead of buffering it unbounded', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['terminal', 'read'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + const chunk = Buffer.alloc(3 * 1024 * 1024, 97) + for (let i = 0; i < 4; i += 1) { + child.stdout.emit('data', chunk) + } + child.emit('close', 0) + + const result = await resultPromise + expect(result.stdout.length).toBeLessThanOrEqual(8 * 1024 * 1024 + 64) + expect(result.stdout).toContain('output truncated') + }) +}) diff --git a/src/main/ssh/ssh-remote-cli-host-passthrough.ts b/src/main/ssh/ssh-remote-cli-host-passthrough.ts new file mode 100644 index 000000000..3ca55edfd --- /dev/null +++ b/src/main/ssh/ssh-remote-cli-host-passthrough.ts @@ -0,0 +1,270 @@ +// Why: the SSH relay shim (`~/.orca-relay/bin/orca`) forwards CLI invocations +// to the host app. Instead of re-implementing every command in a hand-rolled +// switch (the cause of "Unsupported SSH Orca CLI command", #7716), the host +// runs the real bundled `orca` CLI entry in Electron node mode — the same +// entry the local shell command uses — so remote invocations get the full +// command surface (orchestration, worktree, terminal, ...) by construction. +import { app } from 'electron' +import { spawn as nodeSpawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { getCanonicalUserDataPath } from '../persistence' + +export type RemoteOrcaCliRequest = { + argv: string[] + cwd: string + env: Record + stdin?: string +} + +export type RemoteOrcaCliResult = { + stdout: string + stderr: string + exitCode: number +} + +export type HostCliPassthroughOptions = { + execPath?: string + cliEntryPath?: string + userDataPath?: string + hostEnv?: NodeJS.ProcessEnv + spawn?: typeof nodeSpawn + entryExists?: (path: string) => boolean + killTimeoutMs?: number +} + +/** Thrown when the host CLI entry cannot be launched at all; callers fall back + * to the legacy in-process command switch so previously-working commands keep + * working even on broken installs. */ +export class HostCliUnavailableError extends Error {} + +// Why: only Orca terminal-context vars may cross from the remote shell into +// the host CLI process. Remote PATH / ORCA_USER_DATA_PATH are paths on the +// remote machine (meaningless or instance-hijacking on the host), and +// NODE_OPTIONS-style vars could alter host execution. +const REMOTE_CONTEXT_ENV_VARS = [ + 'ORCA_TERMINAL_HANDLE', + 'ORCA_WORKTREE_ID', + 'ORCA_PANE_KEY', + 'ORCA_WORKSPACE_ID' +] as const + +// Why: bound captured output so a runaway command cannot balloon the relay +// JSON-RPC response or main-process memory. +const MAX_CAPTURED_OUTPUT_BYTES = 8 * 1024 * 1024 +const DEFAULT_KILL_TIMEOUT_MS = 10 * 60_000 +const KILL_TIMEOUT_GRACE_MS = 2 * 60_000 + +export function resolveHostCliEntryPath(app: { + isPackaged: boolean + resourcesPath: string + appPath: string +}): string { + // Why: mirrors the packaged launcher scripts (resources/*/bin) and the dev + // launcher in cli-installer.ts — packaged builds ship the CLI entry outside + // app.asar so Electron node mode can execute it directly. + return app.isPackaged + ? join(app.resourcesPath, 'app.asar.unpacked', 'out', 'cli', 'index.js') + : join(app.appPath, 'out', 'cli', 'index.js') +} + +/** Kill timer for the host CLI subprocess. Long-poll commands carry their wait + * budget in `--timeout-ms`; extend past it so the CLI's own timeout fires + * first and produces a proper error message. */ +export function resolveHostCliKillTimeoutMs(argv: string[]): number { + const explicit = parseTimeoutMsFlag(argv) + if (explicit !== null && Number.isFinite(explicit) && explicit > 0) { + return Math.max(DEFAULT_KILL_TIMEOUT_MS, explicit + KILL_TIMEOUT_GRACE_MS) + } + return DEFAULT_KILL_TIMEOUT_MS +} + +export function buildHostCliEnv(args: { + hostEnv: NodeJS.ProcessEnv + remoteEnv: Record + userDataPath: string + remoteCwd: string +}): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { ...args.hostEnv } + for (const key of REMOTE_CONTEXT_ENV_VARS) { + const value = args.remoteEnv[key] + if (typeof value === 'string' && value.length > 0) { + env[key] = value + } + } + // Why: bind the subprocess to this app instance's runtime metadata (dev and + // parallel instances use non-default userData dirs). + env.ORCA_USER_DATA_PATH = args.userDataPath + // Why: the caller's working directory lives on the remote machine, so the + // subprocess cwd cannot be chdir'd there; ORCA_CLI_CWD carries it for + // cwd-based selectors like `--worktree active`. + env.ORCA_CLI_CWD = args.remoteCwd + // Why: same node-mode hygiene as the shipped CLI launchers — stash and clear + // NODE_OPTIONS so Electron's node bootstrap does not inherit them. + env.ORCA_NODE_OPTIONS = args.hostEnv.NODE_OPTIONS ?? '' + env.ORCA_NODE_REPL_EXTERNAL_MODULE = args.hostEnv.NODE_REPL_EXTERNAL_MODULE ?? '' + delete env.NODE_OPTIONS + delete env.NODE_REPL_EXTERNAL_MODULE + env.ELECTRON_RUN_AS_NODE = '1' + return env +} + +export async function runHostOrcaCliPassthrough( + request: RemoteOrcaCliRequest, + options: HostCliPassthroughOptions = {} +): Promise { + // Why: per-field lazy defaults keep the module testable — tests inject all + // three, so no Electron API is touched outside the production path. + const execPath = options.execPath ?? process.execPath + let cliEntryPath: string + let userDataPath: string + try { + cliEntryPath = + options.cliEntryPath ?? + resolveHostCliEntryPath({ + isPackaged: app.isPackaged, + resourcesPath: process.resourcesPath, + appPath: app.getAppPath() + }) + // Why: must match the userData dir the runtime RPC server writes metadata + // to (see index.ts OrcaRuntimeRpcServer wiring), or the CLI subprocess + // reports "Orca is not running" against a healthy app. + userDataPath = options.userDataPath ?? getCanonicalUserDataPath() + } catch (err) { + // Why: no Electron app context (or broken install paths) — degrade to the + // caller's legacy in-process fallback instead of failing the command. + throw new HostCliUnavailableError( + `Host CLI environment unavailable: ${err instanceof Error ? err.message : String(err)}` + ) + } + const hostEnv = options.hostEnv ?? process.env + const spawn = options.spawn ?? nodeSpawn + const entryExists = options.entryExists ?? existsSync + const killTimeoutMs = options.killTimeoutMs ?? resolveHostCliKillTimeoutMs(request.argv) + + if (!entryExists(cliEntryPath)) { + throw new HostCliUnavailableError(`Orca CLI entry not found at ${cliEntryPath}`) + } + + const env = buildHostCliEnv({ + hostEnv, + remoteEnv: request.env, + userDataPath, + remoteCwd: request.cwd + }) + + return await new Promise((resolve, reject) => { + let settled = false + const child = spawn(execPath, [cliEntryPath, ...request.argv], { + env, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) + + const stdout = new CappedOutputCollector(MAX_CAPTURED_OUTPUT_BYTES) + const stderr = new CappedOutputCollector(MAX_CAPTURED_OUTPUT_BYTES) + + const killTimer = setTimeout(() => { + if (settled) { + return + } + settled = true + try { + child.kill('SIGKILL') + } catch { + // best effort — process may already be gone + } + resolve({ + stdout: stdout.toString(), + stderr: `${stderr.toString()}Orca CLI bridge timed out after ${killTimeoutMs}ms on the host.\n`, + exitCode: 1 + }) + }, killTimeoutMs) + killTimer.unref?.() + + child.on('error', (err) => { + if (settled) { + return + } + settled = true + clearTimeout(killTimer) + // Why: failure to launch (ENOENT, EACCES) means the host CLI is not + // runnable at all — signal the caller to use the legacy fallback rather + // than reporting a confusing per-command failure. + reject( + new HostCliUnavailableError(`Failed to launch the Orca CLI on the host: ${err.message}`) + ) + }) + + child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk)) + child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk)) + + child.on('close', (code) => { + if (settled) { + return + } + settled = true + clearTimeout(killTimer) + resolve({ + stdout: stdout.toString(), + stderr: stderr.toString(), + exitCode: typeof code === 'number' ? code : 1 + }) + }) + + if (child.stdin) { + child.stdin.on('error', () => { + // Why: the CLI may exit without draining stdin; EPIPE here is routine. + }) + if (request.stdin !== undefined) { + child.stdin.end(request.stdin) + } else { + child.stdin.end() + } + } + }) +} + +class CappedOutputCollector { + private readonly chunks: Buffer[] = [] + private bytes = 0 + private truncated = false + + constructor(private readonly maxBytes: number) {} + + push(chunk: Buffer): void { + if (this.truncated) { + return + } + const remaining = this.maxBytes - this.bytes + if (chunk.length >= remaining) { + this.chunks.push(chunk.subarray(0, remaining)) + this.bytes = this.maxBytes + this.truncated = true + return + } + this.chunks.push(chunk) + this.bytes += chunk.length + } + + toString(): string { + const text = Buffer.concat(this.chunks).toString('utf8') + return this.truncated ? `${text}\n[orca ssh cli] output truncated\n` : text + } +} + +function parseTimeoutMsFlag(argv: string[]): number | null { + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i] + if (token === '--timeout-ms') { + const next = argv[i + 1] + const parsed = next === undefined ? Number.NaN : Number(next) + return Number.isFinite(parsed) ? parsed : null + } + if (token.startsWith('--timeout-ms=')) { + const parsed = Number(token.slice('--timeout-ms='.length)) + return Number.isFinite(parsed) ? parsed : null + } + } + return null +} diff --git a/src/main/ssh/ssh-remote-orca-cli.test.ts b/src/main/ssh/ssh-remote-orca-cli.test.ts index c64443876..f54c2157c 100644 --- a/src/main/ssh/ssh-remote-orca-cli.test.ts +++ b/src/main/ssh/ssh-remote-orca-cli.test.ts @@ -1,7 +1,45 @@ +import { EventEmitter } from 'node:events' import { describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + isPackaged: false, + getAppPath: () => '/host/app' + } +})) +vi.mock('../persistence', () => ({ + getCanonicalUserDataPath: () => '/host/user-data' +})) + import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { HostCliPassthroughOptions } from './ssh-remote-cli-host-passthrough' import { runRemoteOrcaCli } from './ssh-remote-orca-cli' +// Why: pointing the passthrough at a missing CLI entry forces the legacy +// in-process fallback, which is what these dispatch tests exercise. +const LEGACY_FALLBACK_OPTIONS: HostCliPassthroughOptions = { + execPath: '/host/electron', + cliEntryPath: '/host/app/out/cli/index.js', + userDataPath: '/host/user-data', + entryExists: () => false +} + +type FakeChild = EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + stdin: { end: ReturnType; on: ReturnType } + kill: ReturnType +} + +function createFakeChild(): FakeChild { + const child = new EventEmitter() as FakeChild + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.stdin = { end: vi.fn(), on: vi.fn() } + child.kill = vi.fn() + return child +} + describe('runRemoteOrcaCli', () => { function createRuntime() { const messages: { @@ -93,11 +131,15 @@ describe('runRemoteOrcaCli', () => { it('uses the remote ORCA_TERMINAL_HANDLE as orchestration sender identity', async () => { const { runtime, db } = createRuntime() - const result = await runRemoteOrcaCli(runtime, { - argv: ['orchestration', 'send', '--to', 'term_windows', '--subject', 'ping', '--json'], - cwd: '/home/alice/repo', - env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } - }) + const result = await runRemoteOrcaCli( + runtime, + { + argv: ['orchestration', 'send', '--to', 'term_windows', '--subject', 'ping', '--json'], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + LEGACY_FALLBACK_OPTIONS + ) expect(result.exitCode).toBe(0) const payload = JSON.parse(result.stdout) as { ok: boolean } @@ -108,18 +150,22 @@ describe('runRemoteOrcaCli', () => { it('accepts equals-style orchestration flags in the remote shim', async () => { const { runtime, db } = createRuntime() - const result = await runRemoteOrcaCli(runtime, { - argv: [ - 'orchestration', - 'send', - '--to=term_windows', - '--subject=ping', - '--body=--literal-body', - '--json' - ], - cwd: '/home/alice/repo', - env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } - }) + const result = await runRemoteOrcaCli( + runtime, + { + argv: [ + 'orchestration', + 'send', + '--to=term_windows', + '--subject=ping', + '--body=--literal-body', + '--json' + ], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + LEGACY_FALLBACK_OPTIONS + ) expect(result.exitCode).toBe(0) const payload = JSON.parse(result.stdout) as { ok: boolean } @@ -138,11 +184,15 @@ describe('runRemoteOrcaCli', () => { body: 'hello' }) - const result = await runRemoteOrcaCli(runtime, { - argv: ['orchestration', 'check', '--all', '--json'], - cwd: '/home/alice/repo', - env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } - }) + const result = await runRemoteOrcaCli( + runtime, + { + argv: ['orchestration', 'check', '--all', '--json'], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + LEGACY_FALLBACK_OPTIONS + ) expect(result.exitCode).toBe(0) const payload = JSON.parse(result.stdout) as { @@ -153,4 +203,92 @@ describe('runRemoteOrcaCli', () => { expect(payload.result.count).toBe(1) expect(payload.result.messages[0]?.subject).toBe('pong') }) + + it('routes previously-unsupported commands through the full host CLI', async () => { + const { runtime } = createRuntime() + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runRemoteOrcaCli( + runtime, + { + argv: ['worktree', 'create', '--repo', 'orca', '--branch', 'fix/x', '--json'], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + { + execPath: '/host/electron', + cliEntryPath: '/host/app/out/cli/index.js', + userDataPath: '/host/user-data', + entryExists: () => true, + spawn: spawn as never + } + ) + + await Promise.resolve() + child.stdout.emit('data', Buffer.from('{"ok":true}\n')) + child.emit('close', 0) + + const result = await resultPromise + expect(result).toEqual({ stdout: '{"ok":true}\n', stderr: '', exitCode: 0 }) + const [, args] = spawn.mock.calls[0] as unknown as [string, string[]] + expect(args).toEqual([ + '/host/app/out/cli/index.js', + 'worktree', + 'create', + '--repo', + 'orca', + '--branch', + 'fix/x', + '--json' + ]) + }) + + it('rejects host-interactive commands with a targeted error instead of bridging them', async () => { + const { runtime } = createRuntime() + const spawn = vi.fn() + + const result = await runRemoteOrcaCli( + runtime, + { argv: ['serve'], cwd: '/home/alice', env: {} }, + { ...LEGACY_FALLBACK_OPTIONS, spawn: spawn as never } + ) + + expect(result.exitCode).toBe(1) + expect(result.stderr).toContain('orca serve') + expect(result.stderr).toContain('SSH relay bridge') + expect(spawn).not.toHaveBeenCalled() + }) + + it('reports host-interactive command errors as JSON envelopes with --json', async () => { + const { runtime } = createRuntime() + + const result = await runRemoteOrcaCli( + runtime, + { argv: ['serve', '--json'], cwd: '/home/alice', env: {} }, + LEGACY_FALLBACK_OPTIONS + ) + + expect(result.exitCode).toBe(1) + const payload = JSON.parse(result.stdout) as { + ok: boolean + error: { code: string } + } + expect(payload.ok).toBe(false) + expect(payload.error.code).toBe('unsupported_over_ssh') + }) + + it('explains the root cause when falling back and the command is not in the legacy switch', async () => { + const { runtime } = createRuntime() + + const result = await runRemoteOrcaCli( + runtime, + { argv: ['worktree', 'list'], cwd: '/home/alice', env: {} }, + LEGACY_FALLBACK_OPTIONS + ) + + expect(result.exitCode).toBe(1) + expect(result.stderr).toContain('Unsupported SSH Orca CLI command: worktree list') + expect(result.stderr).toContain('full Orca CLI bridge unavailable') + }) }) diff --git a/src/main/ssh/ssh-remote-orca-cli.ts b/src/main/ssh/ssh-remote-orca-cli.ts index d61fe4f25..d555b5c27 100644 --- a/src/main/ssh/ssh-remote-orca-cli.ts +++ b/src/main/ssh/ssh-remote-orca-cli.ts @@ -3,30 +3,38 @@ import { RpcDispatcher } from '../runtime/rpc/dispatcher' import type { RpcResponse } from '../runtime/rpc/core' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { formatRemoteCli } from './ssh-remote-cli-format' +import { + HostCliUnavailableError, + runHostOrcaCliPassthrough, + type HostCliPassthroughOptions, + type RemoteOrcaCliRequest, + type RemoteOrcaCliResult +} from './ssh-remote-cli-host-passthrough' import { RemoteCliArgumentError, getRemoteLinearHelp, tryDispatchRemoteLinearCli } from './ssh-remote-linear-cli' -export type RemoteOrcaCliRequest = { - argv: string[] - cwd: string - env: Record - stdin?: string -} - -export type RemoteOrcaCliResult = { - stdout: string - stderr: string - exitCode: number -} +export type { RemoteOrcaCliRequest, RemoteOrcaCliResult } from './ssh-remote-cli-host-passthrough' type ParsedRemoteCli = { commandPath: string[] flags: Map } +// Why: these commands run a foreground/interactive process attached to the +// caller's TTY (or a local tmux pane), which a buffered one-shot relay bridge +// cannot host. Everything else routes through the full host CLI. +const HOST_INTERACTIVE_COMMANDS: Record = { + serve: + 'orca serve starts a foreground headless Orca server and cannot run through the SSH relay bridge. Run it directly on the machine that should host Orca.', + 'claude-teams': + 'orca claude-teams starts an interactive Claude Code session and cannot run through the SSH relay bridge. Run it in a terminal on the Orca host machine.', + 'agent-teams-tmux': + 'orca agent-teams-tmux is a tmux pane shim for the Orca host machine and cannot run through the SSH relay bridge.' +} + const REMOTE_BOOLEAN_FLAGS = new Set([ 'all', 'attachments', @@ -48,18 +56,60 @@ const REPEATABLE_REMOTE_STRING_FLAGS = new Set(['label']) export async function runRemoteOrcaCli( runtime: OrcaRuntimeService, - request: RemoteOrcaCliRequest + request: RemoteOrcaCliRequest, + passthroughOptions?: HostCliPassthroughOptions ): Promise { - const dispatcher = new RpcDispatcher({ runtime }) const parsed = parseRemoteCliArgs(request.argv) const json = parsed.flags.has('json') + + const interactiveMessage = HOST_INTERACTIVE_COMMANDS[parsed.commandPath[0] ?? ''] + if (interactiveMessage) { + if (json) { + return { + stdout: `${JSON.stringify(buildLocalError(interactiveMessage, 'unsupported_over_ssh'), null, 2)}\n`, + stderr: '', + exitCode: 1 + } + } + return { stdout: '', stderr: `${interactiveMessage}\n`, exitCode: 1 } + } + + let passthroughFailure: HostCliUnavailableError | null = null + try { + return await runHostOrcaCliPassthrough(request, passthroughOptions) + } catch (err) { + if (!(err instanceof HostCliUnavailableError)) { + throw err + } + // Why: fall back to the legacy in-process command switch below so the + // historical read-only/orchestration surface keeps working even when the + // bundled CLI entry cannot be launched on this install. + passthroughFailure = err + } + return await runLegacyRemoteOrcaCli(runtime, request, parsed, json, passthroughFailure) +} + +async function runLegacyRemoteOrcaCli( + runtime: OrcaRuntimeService, + request: RemoteOrcaCliRequest, + parsed: ParsedRemoteCli, + json: boolean, + passthroughFailure: HostCliUnavailableError +): Promise { + const dispatcher = new RpcDispatcher({ runtime }) const help = getRemoteLinearHelp(parsed) if (help) { return { stdout: `${help}\n`, stderr: '', exitCode: 0 } } try { - const response = await dispatchRemoteCli(dispatcher, parsed, request.env, request.stdin) + const response = await dispatchRemoteCli( + dispatcher, + parsed, + request.env, + request.stdin, + passthroughFailure.message + ) const formatted = json ? { stdout: `${JSON.stringify(response, null, 2)}\n`, stderr: '' } : formatRemoteCli(response) @@ -93,7 +143,8 @@ async function dispatchRemoteCli( dispatcher: RpcDispatcher, parsed: ParsedRemoteCli, env: Record, - stdin?: string + stdin: string | undefined, + passthroughFailureReason: string ): Promise { const command = parsed.commandPath.join(' ') const linearResponse = await tryDispatchRemoteLinearCli(dispatcher, parsed, env, stdin) @@ -156,7 +207,12 @@ async function dispatchRemoteCli( terminal: optionalString(parsed.flags, 'terminal') }) default: - throw new Error(`Unsupported SSH Orca CLI command: ${command}`) + // Why: only reachable when the full host CLI could not be launched; + // include that root cause so users can fix the install instead of + // assuming the command family is unsupported over SSH. + throw new Error( + `Unsupported SSH Orca CLI command: ${command} (full Orca CLI bridge unavailable: ${passthroughFailureReason})` + ) } } diff --git a/src/main/ssh/ssh-target-id-migration.test.ts b/src/main/ssh/ssh-target-id-migration.test.ts new file mode 100644 index 000000000..fa6507d62 --- /dev/null +++ b/src/main/ssh/ssh-target-id-migration.test.ts @@ -0,0 +1,139 @@ +import { describe, it, expect } from 'vitest' +import type { PersistedUIState, TerminalTab, WorkspaceSessionState } from '../../shared/types' +import { + migrateUiHostScopeSshTargetId, + migrateWorkspaceSessionSshTargetId +} from './ssh-target-id-migration' + +const OLD_ID = 'ssh-1783337351840-ohabf0' +const NEW_ID = 'ssh-1783400000000-fresh1' + +const makeTab = (overrides: Partial = {}): TerminalTab => ({ + id: 'tab1', + ptyId: null, + worktreeId: 'r1::/wt', + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1, + ...overrides +}) + +const makeSession = (overrides: Partial = {}): WorkspaceSessionState => ({ + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + ...overrides +}) + +describe('migrateWorkspaceSessionSshTargetId', () => { + it('re-encodes SSH pty ids embedded in tabs, layouts, and remote session ids', () => { + const session = makeSession({ + tabsByWorktree: { + 'r1::/wt': [ + makeTab({ id: 'tab1', ptyId: `ssh:${OLD_ID}@@pty-3` }), + makeTab({ id: 'tab2', ptyId: 'local-pty-7' }), + makeTab({ id: 'tab3', ptyId: `ssh:other-target@@pty-1` }) + ] + }, + terminalLayoutsByTabId: { + tab1: { + root: { type: 'leaf', leafId: 'leaf-1' }, + activeLeafId: 'leaf-1', + expandedLeafId: null, + ptyIdsByLeafId: { 'leaf-1': `ssh:${OLD_ID}@@pty-3` } + } + }, + remoteSessionIdsByTabId: { + tab1: `ssh:${OLD_ID}@@pty-3`, + tab3: `ssh:other-target@@pty-1` + } + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(true) + + const tabs = session.tabsByWorktree['r1::/wt'] + expect(tabs[0].ptyId).toBe(`ssh:${NEW_ID}@@pty-3`) + // Local and other-target pty ids must be untouched. + expect(tabs[1].ptyId).toBe('local-pty-7') + expect(tabs[2].ptyId).toBe(`ssh:other-target@@pty-1`) + expect(session.terminalLayoutsByTabId.tab1.ptyIdsByLeafId).toEqual({ + 'leaf-1': `ssh:${NEW_ID}@@pty-3` + }) + expect(session.remoteSessionIdsByTabId).toEqual({ + tab1: `ssh:${NEW_ID}@@pty-3`, + tab3: `ssh:other-target@@pty-1` + }) + }) + + it('replaces the old id in activeConnectionIdsAtShutdown and dedupes', () => { + const session = makeSession({ + activeConnectionIdsAtShutdown: [OLD_ID, NEW_ID, 'ssh-unrelated'] + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(true) + expect(session.activeConnectionIdsAtShutdown).toEqual([NEW_ID, 'ssh-unrelated']) + }) + + it('re-points sleeping agent records pinned to the old connection', () => { + const session = makeSession({ + sleepingAgentSessionsByPaneKey: { + 'tab1:leaf-1': { + paneKey: 'tab1:leaf-1', + worktreeId: 'r1::/wt', + agent: 'claude', + providerSession: { key: 'session_id', id: 's-1' }, + prompt: 'p', + state: 'done', + capturedAt: 1, + updatedAt: 1, + connectionId: OLD_ID + } + } + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(true) + expect(session.sleepingAgentSessionsByPaneKey?.['tab1:leaf-1'].connectionId).toBe(NEW_ID) + }) + + it('returns false when nothing references the old id', () => { + const session = makeSession({ + tabsByWorktree: { 'r1::/wt': [makeTab({ ptyId: 'local-pty' })] }, + activeConnectionIdsAtShutdown: ['ssh-unrelated'] + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(false) + expect(session.activeConnectionIdsAtShutdown).toEqual(['ssh-unrelated']) + }) +}) + +describe('migrateUiHostScopeSshTargetId', () => { + const makeUi = (overrides: Partial): PersistedUIState => + ({ ...overrides }) as PersistedUIState + + it('re-points scope, visible hosts, and host order, deduping collisions', () => { + const ui = makeUi({ + workspaceHostScope: `ssh:${OLD_ID}`, + visibleWorkspaceHostIds: ['local', `ssh:${OLD_ID}`, `ssh:${NEW_ID}`], + workspaceHostOrder: [`ssh:${OLD_ID}`, 'local'] + }) + + expect(migrateUiHostScopeSshTargetId(ui, OLD_ID, NEW_ID)).toBe(true) + expect(ui.workspaceHostScope).toBe(`ssh:${NEW_ID}`) + expect(ui.visibleWorkspaceHostIds).toEqual(['local', `ssh:${NEW_ID}`]) + expect(ui.workspaceHostOrder).toEqual([`ssh:${NEW_ID}`, 'local']) + }) + + it('returns false when the old host id appears nowhere', () => { + const ui = makeUi({ + workspaceHostScope: 'all', + visibleWorkspaceHostIds: ['local'], + workspaceHostOrder: ['local'] + }) + + expect(migrateUiHostScopeSshTargetId(ui, OLD_ID, NEW_ID)).toBe(false) + }) +}) diff --git a/src/main/ssh/ssh-target-id-migration.ts b/src/main/ssh/ssh-target-id-migration.ts new file mode 100644 index 000000000..a917c4393 --- /dev/null +++ b/src/main/ssh/ssh-target-id-migration.ts @@ -0,0 +1,116 @@ +import type { PersistedUIState, WorkspaceSessionState } from '../../shared/types' +import { parseAppSshPtyId, toAppSshPtyId } from '../../shared/ssh-pty-id' +import { toSshExecutionHostId } from '../../shared/execution-host' + +/** + * Carrier sweep for SSH target re-adoption (see ssh-target-readoption.ts). + * + * reassignSshTargetId re-points repos/worktree metas, but the removed target's + * id is also embedded in other persisted state: app-scoped SSH pty ids + * ("ssh:@@pty-N") inside the workspace session, the startup + * reconnect list, sleeping-agent resume records, and the sidebar host-scope + * arrays. Any survivor resurfaces later as `SSH target "" not found` at + * connect/reattach time (STA-1468), so every carrier must migrate together. + * + * All helpers mutate in place (matching how the Store edits this.state) and + * return whether anything changed so callers can gate scheduleSave. + */ + +function rewriteSshPtyId(ptyId: string, oldTargetId: string, newTargetId: string): string | null { + const parsed = parseAppSshPtyId(ptyId) + if (!parsed || parsed.connectionId !== oldTargetId) { + return null + } + return toAppSshPtyId(newTargetId, parsed.relayPtyId) +} + +function rewriteSshPtyIdRecordValues( + record: Record | undefined, + oldTargetId: string, + newTargetId: string +): boolean { + if (!record) { + return false + } + let changed = false + for (const [key, ptyId] of Object.entries(record)) { + const next = rewriteSshPtyId(ptyId, oldTargetId, newTargetId) + if (next) { + record[key] = next + changed = true + } + } + return changed +} + +/** Re-point every old-target-id carrier inside one workspace session partition. */ +export function migrateWorkspaceSessionSshTargetId( + session: WorkspaceSessionState, + oldTargetId: string, + newTargetId: string +): boolean { + let changed = false + for (const tabs of Object.values(session.tabsByWorktree ?? {})) { + for (const tab of tabs) { + if (!tab.ptyId) { + continue + } + const next = rewriteSshPtyId(tab.ptyId, oldTargetId, newTargetId) + if (next) { + tab.ptyId = next + changed = true + } + } + } + for (const layout of Object.values(session.terminalLayoutsByTabId ?? {})) { + if (rewriteSshPtyIdRecordValues(layout.ptyIdsByLeafId, oldTargetId, newTargetId)) { + changed = true + } + } + if (rewriteSshPtyIdRecordValues(session.remoteSessionIdsByTabId, oldTargetId, newTargetId)) { + changed = true + } + if (session.activeConnectionIdsAtShutdown?.includes(oldTargetId)) { + session.activeConnectionIdsAtShutdown = [ + ...new Set( + session.activeConnectionIdsAtShutdown.map((id) => (id === oldTargetId ? newTargetId : id)) + ) + ] + changed = true + } + for (const record of Object.values(session.sleepingAgentSessionsByPaneKey ?? {})) { + if (record.connectionId === oldTargetId) { + record.connectionId = newTargetId + changed = true + } + } + return changed +} + +/** Re-point the sidebar host-scope arrays pinned to the old SSH host id. */ +export function migrateUiHostScopeSshTargetId( + ui: PersistedUIState, + oldTargetId: string, + newTargetId: string +): boolean { + const oldHostId = toSshExecutionHostId(oldTargetId) + const newHostId = toSshExecutionHostId(newTargetId) + let changed = false + if (ui.workspaceHostScope === oldHostId) { + ui.workspaceHostScope = newHostId + changed = true + } + if (ui.visibleWorkspaceHostIds?.includes(oldHostId)) { + ui.visibleWorkspaceHostIds = [ + ...new Set(ui.visibleWorkspaceHostIds.map((id) => (id === oldHostId ? newHostId : id))) + ] + changed = true + } + if (ui.workspaceHostOrder?.includes(oldHostId)) { + ui.workspaceHostOrder = [ + ...new Set(ui.workspaceHostOrder.map((id) => (id === oldHostId ? newHostId : id))) + ] + changed = true + } + return changed +} diff --git a/src/main/ssh/ssh-target-readoption.test.ts b/src/main/ssh/ssh-target-readoption.test.ts new file mode 100644 index 000000000..f263fe01d --- /dev/null +++ b/src/main/ssh/ssh-target-readoption.test.ts @@ -0,0 +1,198 @@ +import { describe, it, expect } from 'vitest' +import { + buildRemovedSshTargetTombstone, + readoptOrphanedWorkspacesForTarget +} from './ssh-target-readoption' +import type { Store } from '../persistence' +import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types' + +function makeTarget(overrides: Partial = {}): SshTarget { + return { + id: 'ssh-new', + label: 'Dev box', + host: 'dev.example.com', + port: 22, + username: 'tim', + ...overrides + } +} + +/** Minimal in-memory store exposing only what re-adoption touches. */ +function makeFakeStore(tombstones: RemovedSshTargetTombstone[]) { + const reassigned: { oldId: string; newId: string }[] = [] + let current = [...tombstones] + const store = { + getRemovedSshTargetTombstones: () => [...current], + removeRemovedSshTargetTombstone: (oldTargetId: string) => { + current = current.filter((t) => t.oldTargetId !== oldTargetId) + }, + reassignSshTargetId: (oldTargetId: string, newTargetId: string) => { + reassigned.push({ oldId: oldTargetId, newId: newTargetId }) + return 1 + } + } as unknown as Store + return { store, reassigned, remaining: () => current } +} + +const tombstone = ( + overrides: Partial = {} +): RemovedSshTargetTombstone => ({ + oldTargetId: 'ssh-old', + host: 'dev.example.com', + port: 22, + username: 'tim', + label: 'Dev box', + removedAt: 1, + ...overrides +}) + +describe('readoptOrphanedWorkspacesForTarget', () => { + it('re-adopts on matching configHost alias', () => { + const fake = makeFakeStore([tombstone({ configHost: 'devbox', host: 'changed.example.com' })]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: 'devbox', host: 'now.example.com' }) + ) + expect(count).toBe(1) + expect(fake.reassigned).toEqual([{ oldId: 'ssh-old', newId: 'ssh-new' }]) + expect(fake.remaining()).toHaveLength(0) // tombstone consumed + }) + + it('re-adopts on matching host+user+port when no alias', () => { + const fake = makeFakeStore([tombstone()]) + const count = readoptOrphanedWorkspacesForTarget(fake.store, makeTarget()) + expect(count).toBe(1) + expect(fake.reassigned).toEqual([{ oldId: 'ssh-old', newId: 'ssh-new' }]) + }) + + it('does not re-adopt when identity differs', () => { + const fake = makeFakeStore([tombstone({ host: 'other.example.com', username: 'root' })]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(0) + expect(fake.reassigned).toEqual([]) + expect(fake.remaining()).toHaveLength(1) // tombstone left for a future match + }) + + it('matches host/user/port case-insensitively', () => { + const fake = makeFakeStore([tombstone({ host: 'Dev.Example.COM', username: 'Tim' })]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(1) + }) + + it('does not match alias against a different host tuple', () => { + // Different alias AND different tuple => no match. + const fake = makeFakeStore([ + tombstone({ configHost: 'prod', host: 'prod.example.com', username: 'root' }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: 'devbox', host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(0) + }) + + it('is a no-op when there are no tombstones', () => { + const fake = makeFakeStore([]) + expect(readoptOrphanedWorkspacesForTarget(fake.store, makeTarget())).toBe(0) + }) + + it('does NOT re-adopt across two different aliases that share host+user+port', () => { + // prod-deploy removed; prod-admin re-added — same box, different alias. + // These are deliberately distinct targets and must not steal workspaces. + const fake = makeFakeStore([ + tombstone({ configHost: 'prod-deploy', host: 'prod.example.com', username: 'deploy' }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: 'prod-admin', host: 'prod.example.com', username: 'deploy' }) + ) + expect(count).toBe(0) + expect(fake.reassigned).toEqual([]) + expect(fake.remaining()).toHaveLength(1) // tombstone preserved + }) + + it('does NOT re-adopt a different account/port on the same host (implicit alias)', () => { + // Manual adds default configHost to host, so both carry configHost === host. + // That is NOT a real alias — matching on it alone would ignore port/username + // and reattach workspaces to the wrong SSH account on the same machine. + const fake = makeFakeStore([ + tombstone({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 2222, + username: 'bob' + }) + ) + expect(count).toBe(0) + expect(fake.reassigned).toEqual([]) + }) + + it('re-adopts the same account/host/port even with implicit configHost === host', () => { + const fake = makeFakeStore([ + tombstone({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + ) + expect(count).toBe(1) + }) + + it('still re-adopts via tuple when the re-added target has no alias', () => { + // Manual re-add (no configHost) of a host that was config-managed: fall back + // to the tuple since one side lacks an alias to distinguish it. + const fake = makeFakeStore([ + tombstone({ configHost: 'devbox', host: 'dev.example.com', username: 'tim' }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: undefined, host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(1) + }) +}) + +describe('buildRemovedSshTargetTombstone', () => { + it('captures identity fields and omits configHost when absent', () => { + const t = buildRemovedSshTargetTombstone(makeTarget(), 123) + expect(t).toEqual({ + oldTargetId: 'ssh-new', + host: 'dev.example.com', + port: 22, + username: 'tim', + label: 'Dev box', + removedAt: 123 + }) + expect('configHost' in t).toBe(false) + }) + + it('includes configHost when present', () => { + const t = buildRemovedSshTargetTombstone(makeTarget({ configHost: 'devbox' }), 1) + expect(t.configHost).toBe('devbox') + }) +}) diff --git a/src/main/ssh/ssh-target-readoption.ts b/src/main/ssh/ssh-target-readoption.ts new file mode 100644 index 000000000..06b0cefd8 --- /dev/null +++ b/src/main/ssh/ssh-target-readoption.ts @@ -0,0 +1,99 @@ +import type { Store } from '../persistence' +import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types' + +/** + * Re-adoption of workspaces orphaned when an SSH target was removed. + * + * Repos/worktrees store only the (random) target id, so removing a target + * strands them on a dead id. When the user re-adds the same host, a fresh id is + * minted and nothing links the old workspaces to it. We bridge that gap using + * removal-time tombstones ({ oldTargetId, configHost, host, username, port }): + * on add/import we match the new target's identity to a tombstone and re-point + * every repo/worktree from the old id to the new one. + * + * Matching is intentionally strict — configHost (alias) first, then the + * host+username+port tuple — so we only auto-reattach on a confident identity + * match and never mislink two genuinely different hosts. Anything that doesn't + * match cleanly stays a ghost, handled by the forget flow instead. + */ + +type IdentityFields = Pick + +function normalize(value: string | undefined): string { + return value?.trim().toLowerCase() ?? '' +} + +function tupleKey(fields: IdentityFields): string { + return `${normalize(fields.host)}|${fields.port}|${normalize(fields.username)}` +} + +// An alias only counts as a distinguishing identity when it differs from the +// host. addTarget defaults configHost to host, so a manual add with no real +// ssh-config alias has configHost === host — that's not an alias, it's just the +// hostname, and matching on it alone would ignore port/username. +function meaningfulAlias(fields: IdentityFields): string { + const alias = normalize(fields.configHost) + return alias && alias !== normalize(fields.host) ? alias : '' +} + +function tombstoneMatches(tombstone: RemovedSshTargetTombstone, target: IdentityFields): boolean { + const targetAlias = meaningfulAlias(target) + const tombstoneAlias = meaningfulAlias(tombstone) + // Primary: matching ssh-config alias. Stable across remove/re-import. + if (targetAlias && tombstoneAlias) { + // Both carry a real alias — the alias is the identity. Different aliases + // mean deliberately distinct targets (e.g. prod-deploy vs prod-admin on the + // same box with different identity files); do NOT fall through to the tuple, + // or a second alias for the same endpoint would steal the first's workspaces. + return targetAlias === tombstoneAlias + } + // Fallback: identical host+user+port. Used when either side has no real alias + // (manual adds default configHost to host), so a different account or port on + // the same host is correctly treated as a different target. + return tupleKey(tombstone) === tupleKey(target) +} + +/** + * Re-point orphaned repos/worktrees onto `newTarget` if a removed target with + * the same host identity is tombstoned. Consumes the matching tombstone(s). + * Returns the number of repos re-adopted (0 when there was nothing to adopt). + */ +export function readoptOrphanedWorkspacesForTarget(store: Store, newTarget: SshTarget): number { + const tombstones = store.getRemovedSshTargetTombstones() + if (tombstones.length === 0) { + return 0 + } + let readopted = 0 + for (const tombstone of tombstones) { + // Why: a re-added target can't share the id of one that still exists, but + // guard anyway so we never re-point a live target onto itself. + if (tombstone.oldTargetId === newTarget.id) { + store.removeRemovedSshTargetTombstone(tombstone.oldTargetId) + continue + } + if (!tombstoneMatches(tombstone, newTarget)) { + continue + } + readopted += store.reassignSshTargetId(tombstone.oldTargetId, newTarget.id) + // Consume the tombstone whether or not it re-pointed anything: the host has + // returned, so the record has served its purpose. + store.removeRemovedSshTargetTombstone(tombstone.oldTargetId) + } + return readopted +} + +/** Build a tombstone from a target about to be removed. */ +export function buildRemovedSshTargetTombstone( + target: SshTarget, + removedAt: number +): RemovedSshTargetTombstone { + return { + oldTargetId: target.id, + ...(target.configHost ? { configHost: target.configHost } : {}), + host: target.host, + port: target.port, + username: target.username, + label: target.label, + removedAt + } +} diff --git a/src/main/system-resume-broadcast.test.ts b/src/main/system-resume-broadcast.test.ts new file mode 100644 index 000000000..dc67ee27a --- /dev/null +++ b/src/main/system-resume-broadcast.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest' +import { registerSystemResumeBroadcast, SYSTEM_RESUMED_CHANNEL } from './system-resume-broadcast' + +vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: vi.fn(() => []) }, + powerMonitor: { on: vi.fn(), off: vi.fn() } +})) + +type ResumeListener = () => void + +function createResumeSource() { + const state: { listener: ResumeListener | null } = { listener: null } + const source = { + on: vi.fn((_event: 'resume', callback: ResumeListener) => { + state.listener = callback + }), + off: vi.fn((_event: 'resume', _callback: ResumeListener) => { + state.listener = null + }) + } + return { source, fireResume: () => state.listener?.() } +} + +function createWindow(destroyed = false): { + isDestroyed: () => boolean + webContents: { send: ReturnType void>> } +} { + return { + isDestroyed: () => destroyed, + webContents: { send: vi.fn<(channel: string) => void>() } + } +} + +describe('registerSystemResumeBroadcast', () => { + it('broadcasts the resume channel to every live window', () => { + const { source, fireResume } = createResumeSource() + const liveWindow = createWindow() + const destroyedWindow = createWindow(true) + registerSystemResumeBroadcast({ + resumeSource: source, + getWindows: () => [liveWindow, destroyedWindow] + }) + + fireResume() + + expect(liveWindow.webContents.send).toHaveBeenCalledWith(SYSTEM_RESUMED_CHANNEL) + expect(destroyedWindow.webContents.send).not.toHaveBeenCalled() + }) + + it('stops broadcasting after unsubscribe', () => { + const { source, fireResume } = createResumeSource() + const window = createWindow() + const unsubscribe = registerSystemResumeBroadcast({ + resumeSource: source, + getWindows: () => [window] + }) + + unsubscribe() + fireResume() + + expect(source.off).toHaveBeenCalledTimes(1) + expect(window.webContents.send).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/system-resume-broadcast.ts b/src/main/system-resume-broadcast.ts new file mode 100644 index 000000000..990b8d2a6 --- /dev/null +++ b/src/main/system-resume-broadcast.ts @@ -0,0 +1,39 @@ +import { BrowserWindow, powerMonitor } from 'electron' + +export const SYSTEM_RESUMED_CHANNEL = 'system:resumed' + +type ResumeEventSource = { + on(event: 'resume', listener: () => void): unknown + off(event: 'resume', listener: () => void): unknown +} + +type ResumeBroadcastWindow = { + isDestroyed(): boolean + webContents: { send(channel: string): void } +} + +type SystemResumeBroadcastOptions = { + resumeSource?: ResumeEventSource + getWindows?: () => ResumeBroadcastWindow[] +} + +// Why: renderers cannot observe OS sleep/wake directly, and Linux has no +// window-occlusion tracking so visibilitychange never fires around suspend. +// Wake-sensitive renderer recovery needs this explicit resume signal. +export function registerSystemResumeBroadcast( + options: SystemResumeBroadcastOptions = {} +): () => void { + const resumeSource = options.resumeSource ?? powerMonitor + const getWindows = options.getWindows ?? (() => BrowserWindow.getAllWindows()) + const onResume = (): void => { + for (const window of getWindows()) { + if (!window.isDestroyed()) { + window.webContents.send(SYSTEM_RESUMED_CHANNEL) + } + } + } + resumeSource.on('resume', onResume) + return () => { + resumeSource.off('resume', onResume) + } +} diff --git a/src/main/window/main-window-visibility.test.ts b/src/main/window/main-window-visibility.test.ts new file mode 100644 index 000000000..335dc4a87 --- /dev/null +++ b/src/main/window/main-window-visibility.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' + +import { isMainWindowVisible } from './main-window-visibility' + +describe('main window visibility helpers', () => { + it('treats a minimal alive window double as visible', () => { + expect(isMainWindowVisible({ isDestroyed: () => false })).toBe(true) + }) + + it('parks work when the real window is hidden, minimized, destroyed, or missing', () => { + expect( + isMainWindowVisible({ + isDestroyed: () => false, + isVisible: () => false, + isMinimized: () => false + }) + ).toBe(false) + expect( + isMainWindowVisible({ + isDestroyed: () => false, + isVisible: () => true, + isMinimized: () => true + }) + ).toBe(false) + expect(isMainWindowVisible({ isDestroyed: () => true })).toBe(false) + expect(isMainWindowVisible(null)).toBe(false) + }) +}) diff --git a/src/main/window/main-window-visibility.ts b/src/main/window/main-window-visibility.ts new file mode 100644 index 000000000..8b4ca4c46 --- /dev/null +++ b/src/main/window/main-window-visibility.ts @@ -0,0 +1,38 @@ +// Why: BrowserWindow instances are recreated on macOS dock re-activation, so +// long-lived main-process services (e.g. the SSH port scanner) subscribe to +// this process-global signal instead of a specific window instance; index.ts +// re-wires each new window's show/restore events into notifyMainWindowBecameVisible. +type MainWindowBecameVisibleListener = () => void + +type MainWindowVisibilityState = { + isDestroyed: () => boolean + isVisible?: () => boolean + isMinimized?: () => boolean +} + +const listeners = new Set() + +export function notifyMainWindowBecameVisible(): void { + for (const listener of Array.from(listeners)) { + listener() + } +} + +export function onMainWindowBecameVisible(listener: MainWindowBecameVisibleListener): () => void { + listeners.add(listener) + return () => { + listeners.delete(listener) + } +} + +export function isMainWindowVisible(window: MainWindowVisibilityState | null): boolean { + if (window === null || window.isDestroyed()) { + return false + } + + // Why: production BrowserWindow exposes both APIs, but older main-process + // tests use minimal window doubles that should stay visible by default. + const isVisible = window.isVisible?.() ?? true + const isMinimized = window.isMinimized?.() ?? false + return isVisible && !isMinimized +} diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 2e9f0c727..96b894afa 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -868,6 +868,9 @@ export type PreloadApi = { kind?: 'git' | 'folder' }) => Promise<{ repo: Repo } | { error: string }> remove: (args: { repoId: string }) => Promise + // Forget a project on one execution host only, leaving the same repo id on + // other hosts (local or a re-added SSH target) intact. + removeForHost: (args: { repoId: string; hostId: string }) => Promise reorder: (args: { orderedIds: string[] }) => Promise<{ status: 'applied' | 'rejected' }> update: (args: { repoId: string @@ -1068,6 +1071,9 @@ export type PreloadApi = { force?: boolean skipArchive?: boolean }) => Promise + // Forget a workspace from Orca only — no remote Git/filesystem work. Used + // for workspaces pinned to a removed/disconnected SSH host. + forgetLocal: (args: { worktreeId: string }) => Promise forceDeletePreservedBranch: (args: { worktreeId: string branchName: string @@ -2303,7 +2309,9 @@ export type PreloadApi = { rootPath: string connectionId?: string excludePaths?: string[] + requestToken?: string }) => Promise + cancelListFiles: (args: { requestToken: string }) => Promise search: (args: SearchOptions & { connectionId?: string }) => Promise importExternalPaths: (args: { sourcePaths: string[] @@ -2742,6 +2750,7 @@ export type PreloadApi = { ) => () => void onSleepWorktree: (callback: (data: { worktreeId: string }) => void) => () => void onTerminalZoom: (callback: (direction: 'in' | 'out' | 'reset') => void) => () => void + onSystemResumed: (callback: () => void) => () => void readClipboardText: (options?: ReadClipboardTextOptions) => Promise readSelectionClipboardText: (options?: ReadClipboardTextOptions) => Promise saveClipboardImageAsTempFile: (args?: { @@ -2772,7 +2781,6 @@ export type PreloadApi = { callback: (payload: RichMarkdownContextMenuCommandPayload) => void ) => () => void onFullscreenChanged: (callback: (isFullScreen: boolean) => void) => () => void - onSystemResumed: (callback: () => void) => () => void minimize: () => void maximize: () => void isMaximized: () => Promise @@ -2873,6 +2881,9 @@ export type PreloadApi = { } ssh: { listTargets: () => Promise + // Removed-target id → last known label, for showing a friendly host name on + // workspaces still pinned to a target that no longer exists. + listRemovedTargetLabels: () => Promise> addTarget: (args: { target: Omit }) => Promise updateTarget: (args: { id: string diff --git a/src/preload/index.ts b/src/preload/index.ts index d9272ec40..67d173083 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -528,6 +528,8 @@ const api = { remove: (args) => ipcRenderer.invoke('repos:remove', args), + removeForHost: (args) => ipcRenderer.invoke('repos:removeForHost', args), + reorder: (args) => ipcRenderer.invoke('repos:reorder', args), update: (args) => ipcRenderer.invoke('repos:update', args), @@ -660,6 +662,8 @@ const api = { remove: (args) => ipcRenderer.invoke('worktrees:remove', args), + forgetLocal: (args) => ipcRenderer.invoke('worktrees:forgetLocal', args), + forceDeletePreservedBranch: (args) => ipcRenderer.invoke('worktrees:forceDeletePreservedBranch', args), @@ -2743,7 +2747,10 @@ const api = { rootPath: string connectionId?: string excludePaths?: string[] + requestToken?: string }): Promise => ipcRenderer.invoke('fs:listFiles', args), + cancelListFiles: (args: { requestToken: string }): Promise => + ipcRenderer.invoke('fs:cancelListFiles', args), search: (args: { query: string rootPath: string @@ -3936,6 +3943,9 @@ const api = { ssh: { listTargets: (): Promise => ipcRenderer.invoke('ssh:listTargets'), + listRemovedTargetLabels: (): Promise> => + ipcRenderer.invoke('ssh:listRemovedTargetLabels'), + addTarget: (args: { target: Omit }): Promise => ipcRenderer.invoke('ssh:addTarget', args), diff --git a/src/relay/fs-handler-git-fallback.ts b/src/relay/fs-handler-git-fallback.ts index da1f67c7f..8a98b9fa4 100644 --- a/src/relay/fs-handler-git-fallback.ts +++ b/src/relay/fs-handler-git-fallback.ts @@ -7,6 +7,7 @@ * a git-focused app. */ import { spawn } from 'node:child_process' +import { fileListingCancellationError } from '../shared/file-listing-cancellation' import type { SearchOptions, SearchResult } from './fs-handler-utils' import { buildGitLsFilesArgsForQuickOpen } from '../shared/quick-open-filter' import { expandQuickOpenGitFilesWithNestedRepos } from '../shared/quick-open-readdir-walk' @@ -31,8 +32,13 @@ import { buildRelayCommandEnv } from './relay-command-env' */ export function listFilesWithGit( rootPath: string, - excludePathPrefixes: readonly string[] = [] + excludePathPrefixes: readonly string[] = [], + options: { signal?: AbortSignal } = {} ): Promise { + const { signal } = options + if (signal?.aborted) { + return Promise.reject(fileListingCancellationError(signal)) + } const gitPaths = new Set() const { primary, ignoredPass } = buildGitLsFilesArgsForQuickOpen(excludePathPrefixes) const children: { @@ -145,7 +151,7 @@ export function listFilesWithGit( }) } - const killSurvivors = (): void => { + const killSurvivors = (reason: string): void => { // Why: Promise.all returns after the first failed pass, but the sibling // git process can keep streaming on SSH unless we cancel it explicitly. for (const entry of children) { @@ -155,22 +161,35 @@ export function listFilesWithGit( if (entry.child.exitCode === null && entry.child.signalCode === null) { entry.child.kill() } - entry.reject(new Error('git ls-files canceled after sibling failure')) + entry.reject(new Error(reason)) } } + // Why: a cancelled scan (workspace switch, superseded request) must stop + // its git children right away instead of streaming a huge tree the caller + // has already abandoned over the shared SSH channel. + const onAbort = (): void => killSurvivors('git ls-files cancelled') + signal?.addEventListener('abort', onAbort, { once: true }) + return Promise.all([runGitLsFiles(primary), runGitLsFiles(ignoredPass)]) .then(() => expandQuickOpenGitFilesWithNestedRepos({ rootPath, gitPaths, - excludePathPrefixes + excludePathPrefixes, + signal }) ) .catch((err) => { - killSurvivors() + killSurvivors('git ls-files canceled after sibling failure') + if (signal?.aborted) { + throw fileListingCancellationError(signal) + } throw err }) + .finally(() => { + signal?.removeEventListener('abort', onAbort) + }) } /** diff --git a/src/relay/fs-handler-list-files-cancel.test.ts b/src/relay/fs-handler-list-files-cancel.test.ts new file mode 100644 index 000000000..02cd8da6a --- /dev/null +++ b/src/relay/fs-handler-list-files-cancel.test.ts @@ -0,0 +1,127 @@ +/** + * Cancellation behavior of the relay file-list scanners (#7721): an aborted + * scan must kill its child processes immediately and reject with a + * cancellation error instead of streaming an abandoned tree to completion. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { spawnMock } = vi.hoisted(() => ({ + spawnMock: vi.fn() +})) + +vi.mock('child_process', () => ({ + spawn: spawnMock +})) + +import { EventEmitter } from 'node:events' +import type { ChildProcess } from 'node:child_process' +import { listFilesWithRg } from './fs-handler-list-files' +import { listFilesWithGit } from './fs-handler-git-fallback' +import { isFileListingCancellation } from '../shared/file-listing-cancellation' + +function createMockProcess(): ChildProcess { + const p = new EventEmitter() as unknown as ChildProcess + ;(p as unknown as Record).stdout = new EventEmitter() + ;( + (p as unknown as Record).stdout as EventEmitter & { + setEncoding: () => void + } + ).setEncoding = vi.fn() + ;(p as unknown as Record).stderr = new EventEmitter() + ;(p as unknown as Record).kill = vi.fn() + ;(p as unknown as Record).exitCode = null + ;(p as unknown as Record).signalCode = null + return p +} + +describe('relay list-files cancellation', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('listFilesWithRg kills both rg passes and rejects when aborted mid-flight', async () => { + const primaryProc = createMockProcess() + const ignoredProc = createMockProcess() + spawnMock.mockImplementation((_cmd: string, args: string[]) => + args.includes('--no-ignore-vcs') ? ignoredProc : primaryProc + ) + + const controller = new AbortController() + const promise = listFilesWithRg('/remote/root', [], { signal: controller.signal }) + + // Partial output before the abort — must be discarded, not resolved. + ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\n') + controller.abort() + + await expect(promise).rejects.toSatisfy(isFileListingCancellation) + expect(primaryProc.kill).toHaveBeenCalled() + expect(ignoredProc.kill).toHaveBeenCalled() + + // Late close events after cancellation must not fire anything. + primaryProc.emit('close', null, 'SIGTERM') + ignoredProc.emit('close', null, 'SIGTERM') + }) + + it('listFilesWithRg rejects without spawning when the signal is already aborted', async () => { + const controller = new AbortController() + controller.abort() + + await expect( + listFilesWithRg('/remote/root', [], { signal: controller.signal }) + ).rejects.toSatisfy(isFileListingCancellation) + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('listFilesWithRg still resolves normally when a signal is provided but never aborted', async () => { + const primaryProc = createMockProcess() + const ignoredProc = createMockProcess() + spawnMock.mockImplementation((_cmd: string, args: string[]) => + args.includes('--no-ignore-vcs') ? ignoredProc : primaryProc + ) + + const controller = new AbortController() + const promise = listFilesWithRg('/remote/root', [], { signal: controller.signal }) + + setTimeout(() => { + ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\n') + primaryProc.emit('close', 0, null) + ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'dist/out.js\n') + ignoredProc.emit('close', 0, null) + }, 5) + + await expect(promise).resolves.toEqual(['src/index.ts', 'dist/out.js']) + }) + + it('listFilesWithGit kills both git passes and rejects when aborted mid-flight', async () => { + const procs: ChildProcess[] = [] + spawnMock.mockImplementation(() => { + const proc = createMockProcess() + procs.push(proc) + return proc + }) + + const controller = new AbortController() + const promise = listFilesWithGit('/remote/root', [], { signal: controller.signal }) + + expect(procs).toHaveLength(2) + controller.abort() + + await expect(promise).rejects.toSatisfy(isFileListingCancellation) + expect(procs[0].kill).toHaveBeenCalled() + expect(procs[1].kill).toHaveBeenCalled() + }) + + it('listFilesWithGit rejects without spawning when the signal is already aborted', async () => { + const controller = new AbortController() + controller.abort() + + await expect( + listFilesWithGit('/remote/root', [], { signal: controller.signal }) + ).rejects.toSatisfy(isFileListingCancellation) + expect(spawnMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/relay/fs-handler-list-files.ts b/src/relay/fs-handler-list-files.ts index 99e3eb97f..bbe7912ee 100644 --- a/src/relay/fs-handler-list-files.ts +++ b/src/relay/fs-handler-list-files.ts @@ -16,6 +16,7 @@ * denied on a single subdir is expected on home-dir roots) */ import { spawn, type ChildProcess } from 'node:child_process' +import { fileListingCancellationError } from '../shared/file-listing-cancellation' import { buildRgArgsForQuickOpen, normalizeQuickOpenRgLine, @@ -27,8 +28,13 @@ export const LIST_FILES_TIMEOUT_MS = 25_000 export function listFilesWithRg( rootPath: string, - excludePathPrefixes: readonly string[] = [] + excludePathPrefixes: readonly string[] = [], + options: { signal?: AbortSignal } = {} ): Promise { + const { signal } = options + if (signal?.aborted) { + return Promise.reject(fileListingCancellationError(signal)) + } return new Promise((resolve, reject) => { const files = new Set() let done = false @@ -177,7 +183,7 @@ export function listFilesWithRg( child.once('close', handleClose) }) - const killSurvivors = (): void => { + const killSurvivors = (reason: string): void => { // Why: when one pass rejects, Promise.all surfaces the error immediately // but the sibling rg keeps running up to LIST_FILES_TIMEOUT_MS. Kill it // so repeated Quick Open opens don't pile up orphan rg processes on the @@ -189,16 +195,30 @@ export function listFilesWithRg( if (entry.child.exitCode === null && entry.child.signalCode === null) { entry.child.kill() } - entry.reject(new Error('rg list canceled after sibling failure')) + entry.reject(new Error(reason)) } } + // Why: a cancelled scan (workspace switch, superseded request) must stop + // its rg children immediately instead of letting them walk the tree to + // completion and flood the relay with stdout it will only discard. + const onAbort = (): void => { + if (done) { + return + } + done = true + killSurvivors('rg list cancelled') + reject(fileListingCancellationError(signal)) + } + signal?.addEventListener('abort', onAbort, { once: true }) + Promise.all([runPass(primary), runPass(ignoredPass)]) .then(() => { if (done) { return } done = true + signal?.removeEventListener('abort', onAbort) resolve(Array.from(files)) }) .catch((err) => { @@ -206,7 +226,8 @@ export function listFilesWithRg( return } done = true - killSurvivors() + signal?.removeEventListener('abort', onAbort) + killSurvivors('rg list canceled after sibling failure') reject(err instanceof Error ? err : new Error(String(err))) }) }) diff --git a/src/relay/fs-handler-readdir-fallback.ts b/src/relay/fs-handler-readdir-fallback.ts index e49609996..d7c917218 100644 --- a/src/relay/fs-handler-readdir-fallback.ts +++ b/src/relay/fs-handler-readdir-fallback.ts @@ -23,10 +23,12 @@ import { */ export async function listFilesWithReaddir( rootPath: string, - excludePathPrefixes: readonly string[] = [] + excludePathPrefixes: readonly string[] = [], + options: { signal?: AbortSignal } = {} ): Promise { return listQuickOpenFilesWithReaddir(rootPath, { excludePathPrefixes, - budget: createQuickOpenReaddirBudget() + budget: createQuickOpenReaddirBudget(), + signal: options.signal }) } diff --git a/src/relay/fs-handler.ts b/src/relay/fs-handler.ts index c6564c51f..f6417b38d 100644 --- a/src/relay/fs-handler.ts +++ b/src/relay/fs-handler.ts @@ -17,6 +17,11 @@ import { } from './fs-handler-utils' import { listFilesWithGit, searchWithGitGrep } from './fs-handler-git-fallback' import { listFilesWithReaddir } from './fs-handler-readdir-fallback' +import { ListFilesScanCoordinator } from './fs-list-files-scan-coordinator' +import { + isFileListingCancellation, + throwIfFileListingCancelled +} from '../shared/file-listing-cancellation' import { isQuickOpenReaddirBudgetError } from '../shared/quick-open-readdir-walk' import { buildExcludePathPrefixes } from '../shared/quick-open-filter' import { buildInstallRgMessage } from './fs-handler-install-rg' @@ -82,6 +87,7 @@ export class FsHandler { private dispatcher: RelayDispatcher private watches = new Map() private streamRegistry = new RelayStreamRegistry() + private listFilesScans = new ListFilesScanCoordinator() constructor(dispatcher: RelayDispatcher, _context: RelayContext) { this.dispatcher = dispatcher @@ -114,7 +120,7 @@ export class FsHandler { this.dispatcher.onRequest('fs.copy', (p) => this.copy(p)) this.dispatcher.onRequest('fs.realpath', (p) => this.realpath(p)) this.dispatcher.onRequest('fs.search', (p) => this.search(p)) - this.dispatcher.onRequest('fs.listFiles', (p) => this.listFiles(p)) + this.dispatcher.onRequest('fs.listFiles', (p, c) => this.listFiles(p, c)) this.dispatcher.onRequest('fs.workspaceSpaceScan', (p, c) => this.workspaceSpaceScan(p, c)) this.dispatcher.onRequest('fs.watch', (p, context) => this.watch(p, context)) this.dispatcher.onNotification('fs.unwatch', (p, context) => this.unwatch(p, context)) @@ -331,16 +337,33 @@ export class FsHandler { }) } - private async listFiles(params: Record): Promise { + private listFiles(params: Record, context?: RequestContext): Promise { const rootPath = expandTilde(params.rootPath as string) // Why: the main-to-relay RPC adds excludePaths so nested linked worktrees // don't get double-scanned. The shared helper validates the shape and // normalizes into root-relative prefixes; malformed input yields [] so // the request still succeeds (older apps omit the field entirely). const excludePathPrefixes = buildExcludePathPrefixes(rootPath, params.excludePaths) + // Why #7721: full-tree scans are the relay's most expensive request; the + // coordinator caps them at one per client, coalescing duplicates and + // aborting a stale scan when the workspace changes or the host cancels. + return this.listFilesScans.run({ + clientId: context?.clientId ?? 0, + key: JSON.stringify([rootPath, excludePathPrefixes]), + signal: context?.signal, + start: (signal) => this.runListFilesScan(rootPath, excludePathPrefixes, signal) + }) + } + + private async runListFilesScan( + rootPath: string, + excludePathPrefixes: string[], + signal: AbortSignal + ): Promise { const rgAvailable = await checkRgAvailable() + throwIfFileListingCancelled(signal) if (rgAvailable) { - return listFilesWithRg(rootPath, excludePathPrefixes) + return listFilesWithRg(rootPath, excludePathPrefixes, { signal }) } // Why: git ls-files only works inside git repos. Use rev-parse to detect // git ancestry — unlike checking for a local .git entry, this works from @@ -361,7 +384,7 @@ export class FsHandler { // budget errors into install-rg guidance; genuine git failures keep // their own messages. try { - return await listFilesWithGit(rootPath, excludePathPrefixes) + return await listFilesWithGit(rootPath, excludePathPrefixes, { signal }) } catch (err) { if (isQuickOpenReaddirBudgetError(err)) { throw new Error(await buildInstallRgMessage(err)) @@ -375,8 +398,13 @@ export class FsHandler { // problem, so translate the opaque cap error into actionable guidance // the user can act on directly from the error toast. try { - return await listFilesWithReaddir(rootPath, excludePathPrefixes) + return await listFilesWithReaddir(rootPath, excludePathPrefixes, { signal }) } catch (err) { + // Why: a cancelled scan is not an rg-availability problem; wrapping it + // in install-rg guidance would surface bogus advice on the client. + if (isFileListingCancellation(err)) { + throw err + } throw new Error(await buildInstallRgMessage(err)) } } diff --git a/src/relay/fs-list-files-cancel.integration.test.ts b/src/relay/fs-list-files-cancel.integration.test.ts new file mode 100644 index 000000000..588ddb5fe --- /dev/null +++ b/src/relay/fs-list-files-cancel.integration.test.ts @@ -0,0 +1,209 @@ +/** + * End-to-end in-process regression tests for #7721: cancellable fs.listFiles. + * + * Wires the client-side SshChannelMultiplexer to the relay-side + * RelayDispatcher + FsHandler through an in-memory pipe (no SSH). The scan + * body is a controllable fake so the tests are deterministic: + * - aborting the client request sends rpc.cancel and stops the relay scan, + * - interactive fs.readDir is served while a scan is in flight, + * - a scan for a different workspace supersedes the previous one, + * - identical concurrent requests coalesce into one scan. + */ +import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest' +import { mkdtempSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import * as path from 'node:path' +import { tmpdir } from 'node:os' + +const { fakeListFiles } = vi.hoisted(() => { + type ScanRecord = { + rootPath: string + signal: AbortSignal | undefined + resolve: (files: string[]) => void + } + const scans: ScanRecord[] = [] + const fakeListFiles = Object.assign( + vi.fn( + ( + rootPath: string, + _excludes: readonly string[] = [], + options: { signal?: AbortSignal } = {} + ) => + new Promise((resolve, reject) => { + scans.push({ rootPath, signal: options.signal, resolve }) + options.signal?.addEventListener( + 'abort', + () => + // Mirror the real scanners: surface the abort reason (e.g. the + // "superseded" error) so the dispatcher reports it to the host. + reject( + options.signal?.reason instanceof Error + ? options.signal.reason + : new Error('File listing cancelled') + ), + { once: true } + ) + }) + ), + { scans } + ) + return { fakeListFiles } +}) + +vi.mock('./fs-handler-utils', async (importOriginal) => { + const original = (await importOriginal()) as Record + return { + ...original, + checkRgAvailable: () => Promise.resolve(true), + listFilesWithRg: fakeListFiles + } +}) + +import { + SshChannelMultiplexer, + type MultiplexerTransport +} from '../main/ssh/ssh-channel-multiplexer' +import { RelayDispatcher } from './dispatcher' +import { RelayContext } from './context' +import { FsHandler } from './fs-handler' +import { LIST_FILES_SUPERSEDED_MESSAGE } from './fs-list-files-scan-coordinator' + +async function flushPipe(): Promise { + // The in-memory pipe defers each hop with setImmediate; a few macrotask + // turns guarantee request/notification frames have crossed both directions. + for (let i = 0; i < 10; i++) { + await new Promise((resolve) => setImmediate(resolve)) + } +} + +describe('Integration: cancellable fs.listFiles (#7721)', () => { + let tmpDir: string + let mux: SshChannelMultiplexer + let dispatcher: RelayDispatcher + let fsHandler: FsHandler + + beforeEach(() => { + fakeListFiles.mockClear() + fakeListFiles.scans.length = 0 + tmpDir = mkdtempSync(path.join(tmpdir(), 'relay-listfiles-cancel-')) + + let relayFeedFn: (data: Buffer) => void + const clientDataCallbacks: ((data: Buffer) => void)[] = [] + const clientTransport: MultiplexerTransport = { + write: (data: Buffer) => { + setImmediate(() => relayFeedFn?.(data)) + }, + onData: (cb) => { + clientDataCallbacks.push(cb) + }, + onClose: () => {} + } + dispatcher = new RelayDispatcher((data: Buffer) => { + setImmediate(() => { + for (const cb of clientDataCallbacks) { + cb(data) + } + }) + }) + relayFeedFn = (data: Buffer) => dispatcher.feed(data) + fsHandler = new FsHandler(dispatcher, new RelayContext()) + mux = new SshChannelMultiplexer(clientTransport) + }) + + afterEach(async () => { + mux.dispose() + dispatcher.dispose() + fsHandler.dispose() + await rm(tmpDir, { recursive: true, force: true }) + }) + + it('serves fs.readDir while a full-tree scan is in flight', async () => { + writeFileSync(path.join(tmpDir, 'a.txt'), 'a') + + const scanPromise = mux.request('fs.listFiles', { rootPath: '/big/workspace' }) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + + // The interactive request must complete while the scan is still pending. + const entries = (await mux.request('fs.readDir', { dirPath: tmpDir })) as { name: string }[] + expect(entries.map((e) => e.name)).toEqual(['a.txt']) + + fakeListFiles.scans[0].resolve(['src/index.ts']) + await expect(scanPromise).resolves.toEqual(['src/index.ts']) + }) + + it('client abort sends rpc.cancel and stops the relay-side scan', async () => { + const controller = new AbortController() + const scanPromise = mux.request( + 'fs.listFiles', + { rootPath: '/big/workspace' }, + { signal: controller.signal } + ) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + expect(fakeListFiles.scans[0].signal?.aborted).toBe(false) + + controller.abort() + await expect(scanPromise).rejects.toThrow('was cancelled') + await flushPipe() + + // The rpc.cancel notification must have aborted the scan on the relay. + expect(fakeListFiles.scans[0].signal?.aborted).toBe(true) + }) + + it('a scan for a different workspace supersedes the previous scan', async () => { + const first = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + // Attach the rejection handler up front: the error response arrives on a + // macrotask inside flushPipe, before any later `await expect` could. + const firstOutcome = first.then( + () => null, + (err: Error) => err + ) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + + const second = mux.request('fs.listFiles', { rootPath: '/workspace/b' }) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(2) + + // The stale scan is aborted and its request fails fast — it does not run + // to completion behind the new one and does not hit the 30s timeout. + expect(fakeListFiles.scans[0].signal?.aborted).toBe(true) + const firstError = await firstOutcome + expect(firstError?.message).toContain(LIST_FILES_SUPERSEDED_MESSAGE) + + fakeListFiles.scans[1].resolve(['b.ts']) + await expect(second).resolves.toEqual(['b.ts']) + }) + + it('identical concurrent requests coalesce into a single scan', async () => { + const first = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + const second = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + await flushPipe() + + expect(fakeListFiles.scans).toHaveLength(1) + fakeListFiles.scans[0].resolve(['shared.ts']) + await expect(first).resolves.toEqual(['shared.ts']) + await expect(second).resolves.toEqual(['shared.ts']) + }) + + it('cancelling one coalesced requester keeps the scan alive for the other', async () => { + const controller = new AbortController() + const first = mux.request( + 'fs.listFiles', + { rootPath: '/workspace/a' }, + { signal: controller.signal } + ) + const second = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + + controller.abort() + await expect(first).rejects.toThrow('was cancelled') + await flushPipe() + expect(fakeListFiles.scans[0].signal?.aborted).toBe(false) + + fakeListFiles.scans[0].resolve(['still.ts']) + await expect(second).resolves.toEqual(['still.ts']) + }) +}) diff --git a/src/relay/fs-list-files-scan-coordinator.test.ts b/src/relay/fs-list-files-scan-coordinator.test.ts new file mode 100644 index 000000000..a142c120c --- /dev/null +++ b/src/relay/fs-list-files-scan-coordinator.test.ts @@ -0,0 +1,222 @@ +import { describe, expect, it, vi } from 'vitest' +import { + LIST_FILES_SUPERSEDED_MESSAGE, + ListFilesScanCoordinator +} from './fs-list-files-scan-coordinator' +import { + FileListingCancelledError, + isFileListingCancellation +} from '../shared/file-listing-cancellation' + +type Deferred = { + promise: Promise + resolve: (files: string[]) => void + reject: (error: Error) => void +} + +function deferred(): Deferred { + let resolve!: (files: string[]) => void + let reject!: (error: Error) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +/** Scan runner that resolves/rejects on demand and rejects when aborted. */ +function controllableScan(): { + start: (signal: AbortSignal) => Promise + starts: AbortSignal[] + finish: (files: string[]) => void +} { + const starts: AbortSignal[] = [] + let current: Deferred | null = null + return { + starts, + start: (signal: AbortSignal) => { + starts.push(signal) + const scan = deferred() + current = scan + signal.addEventListener( + 'abort', + () => { + scan.reject( + signal.reason instanceof Error ? signal.reason : new FileListingCancelledError() + ) + }, + { once: true } + ) + return scan.promise + }, + finish: (files: string[]) => current?.resolve(files) + } +} + +describe('ListFilesScanCoordinator', () => { + it('coalesces same-key concurrent requests into one scan', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + const second = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + + expect(scan.starts).toHaveLength(1) + scan.finish(['x.ts']) + await expect(first).resolves.toEqual(['x.ts']) + await expect(second).resolves.toEqual(['x.ts']) + }) + + it('supersedes a different-key scan: aborts the old one and rejects it fast', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'workspace-a', start: scan.start }) + const second = coordinator.run({ clientId: 1, key: 'workspace-b', start: scan.start }) + + expect(scan.starts).toHaveLength(2) + expect(scan.starts[0].aborted).toBe(true) + await expect(first).rejects.toThrow(LIST_FILES_SUPERSEDED_MESSAGE) + await first.catch((err) => expect(isFileListingCancellation(err)).toBe(true)) + + expect(scan.starts[1].aborted).toBe(false) + scan.finish(['b.ts']) + await expect(second).resolves.toEqual(['b.ts']) + }) + + it('keeps scans from different clients independent', async () => { + const coordinator = new ListFilesScanCoordinator() + const scanA = controllableScan() + const scanB = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'workspace-a', start: scanA.start }) + const second = coordinator.run({ clientId: 2, key: 'workspace-b', start: scanB.start }) + + expect(scanA.starts[0].aborted).toBe(false) + scanA.finish(['a.ts']) + scanB.finish(['b.ts']) + await expect(first).resolves.toEqual(['a.ts']) + await expect(second).resolves.toEqual(['b.ts']) + }) + + it('aborts the scan when its only requester cancels', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const requester = new AbortController() + + const result = coordinator.run({ + clientId: 1, + key: 'a', + signal: requester.signal, + start: scan.start + }) + + requester.abort() + expect(scan.starts[0].aborted).toBe(true) + await expect(result).rejects.toSatisfy(isFileListingCancellation) + }) + + it('keeps a coalesced scan alive while another requester still waits', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const first = new AbortController() + const second = new AbortController() + + const firstResult = coordinator.run({ + clientId: 1, + key: 'a', + signal: first.signal, + start: scan.start + }) + const secondResult = coordinator.run({ + clientId: 1, + key: 'a', + signal: second.signal, + start: scan.start + }) + + first.abort() + expect(scan.starts[0].aborted).toBe(false) + // The aborting requester observes its own cancellation immediately, + // while the shared scan keeps running for the sibling. + await expect(firstResult).rejects.toSatisfy(isFileListingCancellation) + + second.abort() + expect(scan.starts[0].aborted).toBe(true) + await expect(secondResult).rejects.toSatisfy(isFileListingCancellation) + }) + + it('rejects an aborted coalesced requester while the sibling still resolves', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const first = new AbortController() + + const firstResult = coordinator.run({ + clientId: 1, + key: 'a', + signal: first.signal, + start: scan.start + }) + const secondResult = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + + first.abort() + scan.finish(['kept.ts']) + + await expect(firstResult).rejects.toSatisfy(isFileListingCancellation) + await expect(secondResult).resolves.toEqual(['kept.ts']) + }) + + it('rejects immediately when the requester is already cancelled', async () => { + const coordinator = new ListFilesScanCoordinator() + const start = vi.fn() + const requester = new AbortController() + requester.abort() + + await expect( + coordinator.run({ + clientId: 1, + key: 'a', + signal: requester.signal, + start: start as unknown as (signal: AbortSignal) => Promise + }) + ).rejects.toSatisfy(isFileListingCancellation) + expect(start).not.toHaveBeenCalled() + }) + + it('starts a fresh scan for the same key after the previous one settled', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + scan.finish(['old.ts']) + await expect(first).resolves.toEqual(['old.ts']) + + const second = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + expect(scan.starts).toHaveLength(2) + scan.finish(['new.ts']) + await expect(second).resolves.toEqual(['new.ts']) + }) + + it('does not join a scan that is already aborted; starts a replacement', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const requester = new AbortController() + + const first = coordinator.run({ + clientId: 1, + key: 'a', + signal: requester.signal, + start: scan.start + }) + requester.abort() + await expect(first).rejects.toSatisfy(isFileListingCancellation) + + // The aborted entry may still be in the map until its promise settles; + // a new same-key request must get a live scan, not the dead one. + const second = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + expect(scan.starts).toHaveLength(2) + expect(scan.starts[1].aborted).toBe(false) + scan.finish(['fresh.ts']) + await expect(second).resolves.toEqual(['fresh.ts']) + }) +}) diff --git a/src/relay/fs-list-files-scan-coordinator.ts b/src/relay/fs-list-files-scan-coordinator.ts new file mode 100644 index 000000000..6e6e30c5f --- /dev/null +++ b/src/relay/fs-list-files-scan-coordinator.ts @@ -0,0 +1,104 @@ +/** + * Single-flight coordinator for fs.listFiles full-tree scans (#7721). + * + * Why: rapid workspace switching used to stack N concurrent full-tree scans + * on the single-threaded relay and its one SSH channel, starving small + * interactive fs.readDir/fs.stat requests past their 30s timeout. This + * coordinator guarantees at most one scan in flight per client: + * - a request for the same root/excludes joins the in-flight scan + * (Quick Open + file-explorer filter share one scan), + * - a request for a different root supersedes it — the old scan is aborted + * and its request fails fast instead of running to completion (this also + * protects against older Orca clients that never send rpc.cancel), + * - when every joined requester cancels (rpc.cancel / client detach), the + * scan is aborted so abandoned work stops immediately. + */ +import { + FileListingCancelledError, + fileListingCancellationError +} from '../shared/file-listing-cancellation' + +export const LIST_FILES_SUPERSEDED_MESSAGE = 'File listing superseded by a newer request' + +type ScanEntry = { + key: string + controller: AbortController + promise: Promise + attachedCount: number +} + +export class ListFilesScanCoordinator { + private readonly scansByClient = new Map() + + run(opts: { + clientId: number + key: string + signal?: AbortSignal + start: (signal: AbortSignal) => Promise + }): Promise { + const { clientId, key, signal, start } = opts + if (signal?.aborted) { + return Promise.reject(fileListingCancellationError(signal)) + } + + const existing = this.scansByClient.get(clientId) + if (existing && existing.key === key && !existing.controller.signal.aborted) { + return this.attach(existing, signal) + } + if (existing) { + existing.controller.abort(new FileListingCancelledError(LIST_FILES_SUPERSEDED_MESSAGE)) + } + + const controller = new AbortController() + const entry: ScanEntry = { + key, + controller, + promise: Promise.resolve([]), + attachedCount: 0 + } + this.scansByClient.set(clientId, entry) + entry.promise = start(controller.signal).finally(() => { + if (this.scansByClient.get(clientId) === entry) { + this.scansByClient.delete(clientId) + } + }) + return this.attach(entry, signal) + } + + private attach(entry: ScanEntry, signal?: AbortSignal): Promise { + entry.attachedCount++ + if (!signal) { + return entry.promise + } + // Why: an aborting requester must see its own cancellation even though + // the shared scan keeps running (and may later resolve) for coalesced + // siblings — so each attachment gets its own promise. + return new Promise((resolve, reject) => { + let settled = false + const settle = (complete: () => void): void => { + if (settled) { + return + } + settled = true + signal.removeEventListener('abort', onAbort) + complete() + } + const onAbort = (): void => + settle(() => { + entry.attachedCount-- + const cancellation = fileListingCancellationError(signal) + // Why: only stop the shared scan when nobody is left waiting on it — + // one requester cancelling must not break a coalesced sibling. + if (entry.attachedCount <= 0) { + entry.controller.abort(cancellation) + } + reject(cancellation) + }) + signal.addEventListener('abort', onAbort, { once: true }) + entry.promise.then( + (files) => settle(() => resolve(files)), + (error) => settle(() => reject(error)) + ) + }) + } +} diff --git a/src/relay/relay-diagnostic-log.test.ts b/src/relay/relay-diagnostic-log.test.ts new file mode 100644 index 000000000..38adbcb76 --- /dev/null +++ b/src/relay/relay-diagnostic-log.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it, vi } from 'vitest' +import { relayLogLine } from './relay-diagnostic-log' + +describe('relayLogLine', () => { + it('prefixes each log line with an ISO timestamp', () => { + const writeSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true) + try { + relayLogLine('[relay] Grace started (stdin ended)') + + expect(writeSpy).toHaveBeenCalledTimes(1) + const line = writeSpy.mock.calls[0][0] as string + // Why: relay.log correlation depends on a grep-stable + // " " shape (#7773). + expect(line).toMatch( + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z \[relay\] Grace started \(stdin ended\)\n$/ + ) + } finally { + writeSpy.mockRestore() + } + }) +}) diff --git a/src/relay/relay-diagnostic-log.ts b/src/relay/relay-diagnostic-log.ts new file mode 100644 index 000000000..a42106101 --- /dev/null +++ b/src/relay/relay-diagnostic-log.ts @@ -0,0 +1,7 @@ +// Why: the relay daemon's stderr is redirected to relay.log on the remote +// host. Without timestamps, reconnect flaps in that log cannot be correlated +// with user activity or sleep/wake windows during diagnosis (#7773). Keep the +// format grep-stable: ISO timestamp, single space, then the original line. +export function relayLogLine(message: string): void { + process.stderr.write(`${new Date().toISOString()} ${message}\n`) +} diff --git a/src/relay/relay-handshake.ts b/src/relay/relay-handshake.ts index 6db263bcc..fb64c57ec 100644 --- a/src/relay/relay-handshake.ts +++ b/src/relay/relay-handshake.ts @@ -17,6 +17,7 @@ import { parseHandshakeMessage, type DecodedFrame } from './protocol' +import { relayLogLine } from './relay-diagnostic-log' // Why: a unique exit code reserved for the wire-level version-mismatch terminal // condition. The client (waitForSentinel + ssh.ts) maps this exit code to a @@ -132,22 +133,18 @@ function handleDaemonHandshakeFrame( try { msg = parseHandshakeMessage(frame.payload) } catch (err) { - process.stderr.write( - `[relay] Could not parse handshake: ${(err as Error).message}; closing socket\n` - ) + relayLogLine(`[relay] Could not parse handshake: ${(err as Error).message}; closing socket`) sock.destroy() return false } if (msg.type !== 'orca-relay-handshake') { - process.stderr.write( - `[relay] Unexpected handshake type from client: ${msg.type}; closing socket\n` - ) + relayLogLine(`[relay] Unexpected handshake type from client: ${msg.type}; closing socket`) sock.destroy() return false } if (msg.version !== launchVersion) { - process.stderr.write( - `[relay] Handshake mismatch: own=${launchVersion}, client=${msg.version}; closing socket\n` + relayLogLine( + `[relay] Handshake mismatch: own=${launchVersion}, client=${msg.version}; closing socket` ) try { sock.write( diff --git a/src/relay/relay.ts b/src/relay/relay.ts index 992252279..65f90e886 100644 --- a/src/relay/relay.ts +++ b/src/relay/relay.ts @@ -59,6 +59,7 @@ import { resolveOpenCodeSourceConfigDir, resolvePiSourceAgentDir } from './plugi import { detectPiAgentKindFromCommand } from '../shared/pi-agent-kind' import { resolveSetupAgentSequenceLaunchCommand } from '../shared/setup-agent-sequencing' import { pickRemoteCliEnv } from './remote-cli-env' +import { relayLogLine } from './relay-diagnostic-log' import { remoteCliRequestTimeoutMs } from './remote-cli-timeout' import { shouldReadRemoteCliStdin } from './remote-cli-stdin' @@ -358,13 +359,13 @@ async function main(): Promise { // would risk silent data corruption or zombie PTYs. We log for diagnostics // and then exit so the client can detect the disconnect and reconnect cleanly. process.on('uncaughtException', (err) => { - process.stderr.write(`[relay] Uncaught exception: ${err.message}\n${err.stack}\n`) + relayLogLine(`[relay] Uncaught exception: ${err.message}\n${err.stack}`) cleanupOwnedSocket() process.exit(1) }) process.on('unhandledRejection', (reason) => { - process.stderr.write(`[relay] Unhandled rejection: ${reason}\n`) + relayLogLine(`[relay] Unhandled rejection: ${reason}`) }) // Why: stdoutAlive tracks whether process.stdout is still writable. @@ -529,8 +530,8 @@ async function main(): Promise { try { await hookServer.start({ publishEndpoint: false }) } catch (err) { - process.stderr.write( - `[relay] agent-hook server failed to start: ${err instanceof Error ? err.message : String(err)}\n` + relayLogLine( + `[relay] agent-hook server failed to start: ${err instanceof Error ? err.message : String(err)}` ) } @@ -688,7 +689,7 @@ async function main(): Promise { function cancelGrace(reason: string): void { if (ptyHandler.graceTimerActive) { - process.stderr.write(`[relay] Grace canceled: ${reason}\n`) + relayLogLine(`[relay] Grace canceled: ${reason}`) } graceDeadlineAt = null graceReason = null @@ -704,8 +705,8 @@ async function main(): Promise { hasAcceptedSocketClient = true acceptedSocketConnections++ - process.stderr.write( - `[relay] Socket client accepted (clients=${socketClients.size + 1}, accepted=${acceptedSocketConnections})\n` + relayLogLine( + `[relay] Socket client accepted (clients=${socketClients.size + 1}, accepted=${acceptedSocketConnections})` ) cancelGrace('socket client accepted') @@ -779,7 +780,7 @@ async function main(): Promise { if (clientId !== undefined) { dispatcher.detachClient(clientId) } - process.stderr.write(`[relay] Socket client closed (clients=${socketClients.size})\n`) + relayLogLine(`[relay] Socket client closed (clients=${socketClients.size})`) if (!stdoutAlive && socketClients.size === 0) { startGrace('socket client closed') } @@ -821,9 +822,9 @@ async function main(): Promise { ownsSocketPath = true ownedSocketIdentity = readSocketIdentity(sockPath) server.on('error', (err) => { - process.stderr.write(`[relay] Socket server error: ${err.message}\n`) + relayLogLine(`[relay] Socket server error: ${err.message}`) }) - process.stderr.write(`[relay] Socket server listening: ${sockPath}\n`) + relayLogLine(`[relay] Socket server listening: ${sockPath}`) resolve() } @@ -831,11 +832,11 @@ async function main(): Promise { removeStartupListeners() restoreUmask() if (err.code === 'EADDRINUSE') { - process.stderr.write( - `[relay] Socket path already in use: ${sockPath}; another relay is likely active. Use --connect instead of starting a new daemon.\n` + relayLogLine( + `[relay] Socket path already in use: ${sockPath}; another relay is likely active. Use --connect instead of starting a new daemon.` ) } else { - process.stderr.write(`[relay] Socket server error before listen: ${err.message}\n`) + relayLogLine(`[relay] Socket server error before listen: ${err.message}`) } reject(err) } @@ -903,9 +904,7 @@ async function main(): Promise { failInitial(err) return } - process.stderr.write( - `[relay] Removed stale socket at ${sockPath} and retrying listen\n` - ) + relayLogLine(`[relay] Removed stale socket at ${sockPath} and retrying listen`) removeStartupListeners() listenForStartupError(failInitial) }) @@ -958,11 +957,11 @@ async function main(): Promise { : graceTimeMs graceDeadlineAt = timeoutMs === 0 ? null : Date.now() + timeoutMs graceReason = reason - process.stderr.write( - `[relay] Grace started (${reason}): timeoutMs=${timeoutMs}, startupEmptyDetached=${startupEmptyDetached}, ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}\n` + relayLogLine( + `[relay] Grace started (${reason}): timeoutMs=${timeoutMs}, startupEmptyDetached=${startupEmptyDetached}, ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}` ) ptyHandler.startGraceTimer(() => { - process.stderr.write(`[relay] Grace expired (${reason}); shutting down\n`) + relayLogLine(`[relay] Grace expired (${reason}); shutting down`) shutdown() }, timeoutMs) } @@ -1006,8 +1005,8 @@ async function main(): Promise { } function shutdown(): void { - process.stderr.write( - `[relay] Shutdown: ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}, ownsSocket=${ownsSocketPath}\n` + relayLogLine( + `[relay] Shutdown: ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}, ownsSocket=${ownsSocketPath}` ) graceDeadlineAt = null graceReason = null @@ -1034,10 +1033,10 @@ async function main(): Promise { // window — a reconnecting client can then bridge to the live relay via // --connect and reattach to the still-running PTY sessions. process.on('SIGHUP', () => { - process.stderr.write('[relay] Received SIGHUP (SSH session dropped), ignoring\n') + relayLogLine('[relay] Received SIGHUP (SSH session dropped), ignoring') }) process.on('exit', (code) => { - process.stderr.write(`[relay] Process exiting with code ${code}\n`) + relayLogLine(`[relay] Process exiting with code ${code}`) }) // Signal readiness to the client — the client watches for this exact @@ -1059,8 +1058,8 @@ function cleanupSocket(sockPath: string): void { } void main().catch((err) => { - process.stderr.write( - `[relay] Fatal startup error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n` + relayLogLine( + `[relay] Fatal startup error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}` ) process.exit(1) }) diff --git a/src/relay/remote-cli-env.test.ts b/src/relay/remote-cli-env.test.ts index 844055a83..1546230a5 100644 --- a/src/relay/remote-cli-env.test.ts +++ b/src/relay/remote-cli-env.test.ts @@ -7,6 +7,8 @@ describe('pickRemoteCliEnv', () => { pickRemoteCliEnv({ ORCA_TERMINAL_HANDLE: 'term_ssh', ORCA_WORKTREE_ID: 'repo::remote', + ORCA_PANE_KEY: 'pane-1', + ORCA_WORKSPACE_ID: 'workspace-1', ORCA_USER_DATA_PATH: '/tmp/orca', PATH: '/usr/bin', SECRET_TOKEN: 'nope' @@ -14,6 +16,8 @@ describe('pickRemoteCliEnv', () => { ).toEqual({ ORCA_TERMINAL_HANDLE: 'term_ssh', ORCA_WORKTREE_ID: 'repo::remote', + ORCA_PANE_KEY: 'pane-1', + ORCA_WORKSPACE_ID: 'workspace-1', ORCA_USER_DATA_PATH: '/tmp/orca', PATH: '/usr/bin' }) diff --git a/src/relay/remote-cli-env.ts b/src/relay/remote-cli-env.ts index 360b6074b..d8bc800c6 100644 --- a/src/relay/remote-cli-env.ts +++ b/src/relay/remote-cli-env.ts @@ -3,6 +3,8 @@ export function pickRemoteCliEnv(env: NodeJS.ProcessEnv): Record for (const key of [ 'ORCA_TERMINAL_HANDLE', 'ORCA_WORKTREE_ID', + 'ORCA_PANE_KEY', + 'ORCA_WORKSPACE_ID', 'ORCA_USER_DATA_PATH', 'PATH', 'Path' diff --git a/src/relay/remote-cli-stdin.test.ts b/src/relay/remote-cli-stdin.test.ts index 62fde790a..494ad94e5 100644 --- a/src/relay/remote-cli-stdin.test.ts +++ b/src/relay/remote-cli-stdin.test.ts @@ -15,4 +15,16 @@ describe('shouldReadRemoteCliStdin', () => { false ) }) + + it('reads stdin for *-stdin payload flags bridged to the full host CLI', () => { + expect(shouldReadRemoteCliStdin(['computer', 'action', '--app', 'Notes', '--text-stdin'])).toBe( + true + ) + expect(shouldReadRemoteCliStdin(['computer', 'action', '--app', 'Notes', '--text', 'hi'])).toBe( + false + ) + expect( + shouldReadRemoteCliStdin(['computer', 'action', '--app', 'Notes', '--text-stdin', '--help']) + ).toBe(false) + }) }) diff --git a/src/relay/remote-cli-stdin.ts b/src/relay/remote-cli-stdin.ts index 23ca20897..f9ab8c56d 100644 --- a/src/relay/remote-cli-stdin.ts +++ b/src/relay/remote-cli-stdin.ts @@ -2,6 +2,12 @@ export function shouldReadRemoteCliStdin(argv: string[]): boolean { if (argv.includes('--help') || argv.includes('-h')) { return false } + // Why: computer-use style flags (`--text-stdin`, ...) declare a stdin + // payload directly in the flag name; the full-CLI bridge (#7716) must + // forward stdin for them the same way local shells provide it. + if (argv.some((part) => /^--[a-z0-9][a-z0-9-]*-stdin(?:=|$)/.test(part))) { + return true + } const commandPath = parseRemoteCliCommandPath(argv) if (!isLinearBodyWriteCommand(commandPath)) { return false diff --git a/src/relay/remote-cli-timeout.test.ts b/src/relay/remote-cli-timeout.test.ts index 58a62ac5a..c09a0ccfe 100644 --- a/src/relay/remote-cli-timeout.test.ts +++ b/src/relay/remote-cli-timeout.test.ts @@ -2,58 +2,64 @@ import { describe, expect, it } from 'vitest' import { remoteCliRequestTimeoutMs } from './remote-cli-timeout' describe('remoteCliRequestTimeoutMs', () => { - it('extends SSH remote CLI timeout for Linear issue context reads', () => { + it('gives Linear issue context reads the general CLI budget', () => { expect( remoteCliRequestTimeoutMs({ argv: ['linear', 'issue', 'ENG-123', '--json'] }) - ).toBe(120_000) + ).toBe(300_000) }) - it('extends the timeout when global flags appear before the Linear command', () => { + it('gives ordinary remote CLI requests the general CLI budget instead of the 30s relay default', () => { + // Why: mutation commands bridged through the full host CLI (worktree + // create, orchestration dispatch, ...) can legitimately exceed 30s. + expect(remoteCliRequestTimeoutMs({ argv: ['status'] })).toBe(300_000) + expect(remoteCliRequestTimeoutMs({ argv: ['worktree', 'create', '--repo', 'r'] })).toBe(300_000) + }) + + it('extends the timeout for wait-style commands', () => { + expect(remoteCliRequestTimeoutMs({ argv: ['terminal', 'wait', '--for', 'exit'] })).toBe(600_000) expect( remoteCliRequestTimeoutMs({ - argv: ['--json', 'linear', 'issue', 'ENG-123', '--workspace', 'workspace-1', '--full'] + argv: ['orchestration', 'check', '--wait', '--json'] }) - ).toBe(120_000) - }) - - it('extends SSH remote CLI timeout for Linear search', () => { + ).toBe(600_000) expect( remoteCliRequestTimeoutMs({ - argv: ['linear', 'search', 'auth', '--limit', '1'] + argv: ['orchestration', 'ask', '--to', 'term_x', '--question', 'ok?'] }) - ).toBe(120_000) + ).toBe(600_000) }) - it('extends the timeout when boolean flags appear between Linear and search', () => { + it('extends past an explicit --timeout-ms waiter budget', () => { expect( remoteCliRequestTimeoutMs({ - argv: ['linear', '--json', 'search', 'auth', '--limit', '1'] + argv: ['terminal', 'wait', '--for', 'exit', '--timeout-ms', '1800000'] }) - ).toBe(120_000) - }) - - it('extends the timeout when boolean flags appear between Linear and issue', () => { + ).toBe(1_860_000) expect( remoteCliRequestTimeoutMs({ - argv: ['linear', '--json', 'issue', 'ENG-123', '--full'] + argv: ['orchestration', 'check', '--wait', '--timeout-ms=1800000'] }) - ).toBe(120_000) + ).toBe(1_860_000) }) - it('extends SSH remote CLI timeout for Linear writes', () => { - for (const argv of [ - ['linear', 'status', 'set', 'ENG-123', '--to', 'Done'], - ['linear', 'comment', 'add', 'ENG-123', '--body', 'Done'], - ['linear', 'attach', 'ENG-123', '--url', 'https://example.invalid/review'], - ['linear', 'create', '--team', 'ENG', '--title', 'Follow up'] - ]) { - expect(remoteCliRequestTimeoutMs({ argv })).toBe(120_000) - } + it('keeps the wait base budget when --timeout-ms is small', () => { + expect( + remoteCliRequestTimeoutMs({ + argv: ['terminal', 'wait', '--for', 'exit', '--timeout-ms', '5000'] + }) + ).toBe(600_000) }) - it('keeps ordinary remote CLI requests on the relay default timeout', () => { - expect(remoteCliRequestTimeoutMs({ argv: ['status'] })).toBeUndefined() + it('does not treat a flag value named wait as a command path element', () => { + expect(remoteCliRequestTimeoutMs({ argv: ['terminal', 'read', '--terminal', 'wait'] })).toBe( + 300_000 + ) + }) + + it('falls back to the relay default for malformed argv', () => { + expect(remoteCliRequestTimeoutMs({ argv: 'status' })).toBeUndefined() + expect(remoteCliRequestTimeoutMs({})).toBeUndefined() }) }) diff --git a/src/relay/remote-cli-timeout.ts b/src/relay/remote-cli-timeout.ts index a7f73e0bf..b28ef0ee3 100644 --- a/src/relay/remote-cli-timeout.ts +++ b/src/relay/remote-cli-timeout.ts @@ -1,4 +1,13 @@ -const LINEAR_ISSUE_CONTEXT_TIMEOUT_MS = 120_000 +// Why: the host bridges the full Orca CLI over the relay (#7716), so mutation +// commands (worktree create, orchestration dispatch, Linear writes, ...) can +// legitimately outlive the relay's 30 s default request timeout. Long-poll +// commands carry their waiter budget in --timeout-ms; extend past it so the +// host-side CLI produces its proper timeout error instead of the relay +// cutting the request short. +const REMOTE_CLI_DEFAULT_TIMEOUT_MS = 5 * 60_000 +const REMOTE_CLI_WAIT_TIMEOUT_MS = 10 * 60_000 +const REMOTE_CLI_TIMEOUT_GRACE_MS = 60_000 + const REMOTE_TIMEOUT_BOOLEAN_FLAGS = new Set([ 'all', 'attachments', @@ -15,30 +24,54 @@ const REMOTE_TIMEOUT_BOOLEAN_FLAGS = new Set([ ]) export function remoteCliRequestTimeoutMs(params: Record): number | undefined { - return isLinearCliRequest(params) ? LINEAR_ISSUE_CONTEXT_TIMEOUT_MS : undefined + const argv = getStringArgv(params) + if (!argv) { + return undefined + } + const base = isWaitStyleCliRequest(argv) + ? REMOTE_CLI_WAIT_TIMEOUT_MS + : REMOTE_CLI_DEFAULT_TIMEOUT_MS + const explicit = parseTimeoutMsFlag(argv) + if (explicit !== null && explicit > 0) { + return Math.max(base, explicit + REMOTE_CLI_TIMEOUT_GRACE_MS) + } + return base } -function isLinearCliRequest(params: Record): boolean { - const argv = params.argv - if (!Array.isArray(argv) || !argv.every((part) => typeof part === 'string')) { - return false +function isWaitStyleCliRequest(argv: string[]): boolean { + if (argv.includes('--wait')) { + return true } const commandPath = parseRemoteCommandPath(argv) - return commandPath.some( - (part, index) => - part === 'linear' && isExtendedLinearCliCommand(commandPath.slice(index + 1, index + 4)) + return ( + (commandPath[0] === 'terminal' && commandPath[1] === 'wait') || + (commandPath[0] === 'orchestration' && commandPath[1] === 'ask') ) } -function isExtendedLinearCliCommand(command: string[]): boolean { - const [first, second] = command - if (first === 'issue' || first === 'search' || first === 'attach' || first === 'create') { - return true +function parseTimeoutMsFlag(argv: string[]): number | null { + for (let index = 0; index < argv.length; index += 1) { + const token = argv[index] + let raw: string | undefined + if (token === '--timeout-ms') { + raw = argv[index + 1] + } else if (token.startsWith('--timeout-ms=')) { + raw = token.slice('--timeout-ms='.length) + } else { + continue + } + const parsed = raw === undefined ? Number.NaN : Number(raw) + return Number.isFinite(parsed) ? parsed : null } - if (first === 'status' && second === 'set') { - return true + return null +} + +function getStringArgv(params: Record): string[] | null { + const argv = params.argv + if (!Array.isArray(argv) || !argv.every((part) => typeof part === 'string')) { + return null } - return first === 'comment' && second === 'add' + return argv } function parseRemoteCommandPath(argv: string[]): string[] { diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index b77b58a5c..c0abe44de 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -1971,6 +1971,16 @@ pointer-events: auto; } +/* Why: Monaco leaves the peek preview container `inline-block` and only sizes the + editor child, so the container shrink-wraps the child in BOTH axes while the + inherited automaticLayout ResizeObserver measures the container — a feedback + loop that ratchets the preview to blank at fractional zoom/DPI (issue #7405). + Pinning both dimensions to the splitview slot severs the loop. */ +.monaco-editor .reference-zone-widget .preview.inline { + height: 100%; + width: 100%; +} + /* ── Git conflict decorations ───────────────────────────────────── */ .monaco-editor .orca-conflict-marker-line { diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 5d45f1f78..fd1eb44a8 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -166,6 +166,7 @@ import { import { lookupGitHubWorkItemDetailsForSource } from '@/lib/github-work-item-source-lookup' import { canUseGitHubRepoContext, + getGitHubMutationRoutingSettings, getGitHubRuntimeRepoId, getGitHubSourceRuntimeHost } from '@/lib/github-source-runtime-context' @@ -3848,21 +3849,11 @@ function PRActionsPanel({ const actionItem = { ...item, state: localState } const mergePresentation = presentGitHubPRMergeState(actionItem) const mergeMethods = resolveGitHubPRMergeMethods(actionItem.mergeMethodSettings) - const repoOwnerSettings = useAppStore( - useShallow((s) => getSettingsForRepoRuntimeOwner(s, repoId ?? item.repoId ?? null)) + const sourceSettings = useAppStore( + useShallow((s) => + getGitHubMutationRoutingSettings(s, item.repoId ?? repoId ?? null, sourceContext) + ) ) - const sourceSettings = useMemo(() => { - if (sourceContext?.provider !== 'github') { - return repoOwnerSettings - } - const sourceRuntimeSettings = getTaskSourceRuntimeSettings(sourceContext) - return sourceRuntimeSettings.activeRuntimeEnvironmentId - ? ({ - ...repoOwnerSettings, - ...sourceRuntimeSettings - } as typeof repoOwnerSettings) - : repoOwnerSettings - }, [repoOwnerSettings, sourceContext]) const mergeTarget = getActiveRuntimeTarget(sourceSettings) const canMutateWithRepoContext = !!repoPath || !!projectOrigin || mergeTarget.kind === 'environment' @@ -5465,32 +5456,36 @@ async function runPullRequestStateUpdate(args: { } return } - const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) - if (!args.repoPath && !runtimeHost) { + // Why: close/reopen must route by the repo owner host like merge (#6957). + const target = getActiveRuntimeTarget( + getGitHubMutationRoutingSettings(useAppStore.getState(), args.repoId, args.sourceContext) + ) + if (!args.repoPath && target.kind !== 'environment') { throw new Error('No repo context available for this pull request.') } - const res = runtimeHost - ? await callRuntimeRpc>>( - { kind: 'environment', environmentId: runtimeHost.environmentId }, - 'github.updatePRState', - { - repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + const res = + target.kind === 'environment' + ? await callRuntimeRpc>>( + target, + 'github.updatePRState', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + prNumber: args.number, + updates: args.updates + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.updatePRState({ + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, prNumber: args.number, updates: args.updates - }, - { timeoutMs: 30_000 } - ) - : await window.api.gh.updatePRState({ - repoPath: args.repoPath ?? '', - repoId: args.repoId ?? undefined, - sourceContext: args.sourceContext, - prNumber: args.number, - updates: args.updates - }) + }) if (!res.ok) { throw new Error(res.error) } - if (runtimeHost) { + if (target.kind === 'environment') { notifyWorkItemDetailsMutation( { repoPath: args.repoPath ?? '', diff --git a/src/renderer/src/components/PullRequestPage.tsx b/src/renderer/src/components/PullRequestPage.tsx index aa1a23707..9114000a4 100644 --- a/src/renderer/src/components/PullRequestPage.tsx +++ b/src/renderer/src/components/PullRequestPage.tsx @@ -169,6 +169,7 @@ import { import { lookupGitHubWorkItemDetailsForSource } from '@/lib/github-work-item-source-lookup' import { canUseGitHubRepoContext, + getGitHubMutationRoutingSettings, getGitHubRuntimeRepoId, getGitHubSourceRuntimeHost } from '@/lib/github-source-runtime-context' @@ -3841,7 +3842,11 @@ function PRActionsPanel({ const actionItem = { ...item, state: localState } const mergePresentation = presentGitHubPRMergeState(actionItem) const mergeMethods = resolveGitHubPRMergeMethods(actionItem.mergeMethodSettings) - const sourceSettings = getTaskSourceRuntimeSettings(sourceContext) + const sourceSettings = useAppStore( + useShallow((s) => + getGitHubMutationRoutingSettings(s, item.repoId ?? repoId ?? null, sourceContext) + ) + ) const mergeTarget = getActiveRuntimeTarget(sourceSettings) const canMutateWithRepoContext = !!repoPath || !!projectOrigin || mergeTarget.kind === 'environment' @@ -5731,32 +5736,36 @@ async function runPullRequestStateUpdate(args: { } return } - const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) - if (!args.repoPath && !runtimeHost) { + // Why: close/reopen must route by the repo owner host like merge (#6957). + const target = getActiveRuntimeTarget( + getGitHubMutationRoutingSettings(useAppStore.getState(), args.repoId, args.sourceContext) + ) + if (!args.repoPath && target.kind !== 'environment') { throw new Error('No repo context available for this pull request.') } - const res = runtimeHost - ? await callRuntimeRpc>>( - { kind: 'environment', environmentId: runtimeHost.environmentId }, - 'github.updatePRState', - { - repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + const res = + target.kind === 'environment' + ? await callRuntimeRpc>>( + target, + 'github.updatePRState', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + prNumber: args.number, + updates: args.updates + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.updatePRState({ + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, prNumber: args.number, updates: args.updates - }, - { timeoutMs: 30_000 } - ) - : await window.api.gh.updatePRState({ - repoPath: args.repoPath ?? '', - repoId: args.repoId ?? undefined, - sourceContext: args.sourceContext, - prNumber: args.number, - updates: args.updates - }) + }) if (!res.ok) { throw new Error(res.error) } - if (runtimeHost) { + if (target.kind === 'environment') { notifyWorkItemDetailsMutation( { repoPath: args.repoPath ?? '', diff --git a/src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx b/src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx new file mode 100644 index 000000000..fec2f84c0 --- /dev/null +++ b/src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx @@ -0,0 +1,105 @@ +import React from 'react' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it, vi } from 'vitest' +import { BrowserAnnotationSendMenuContent } from './BrowserAnnotationSendMenuContent' + +type ReactElementLike = { + type: unknown + props: Record +} + +vi.mock('@/components/editor/ReviewNotesSendMenuContent', () => ({ + ReviewNotesSendMenuContent: function ReviewNotesSendMenuContent(props: Record) { + return { type: 'ReviewNotesSendMenuContent', props } + } +})) + +function expand(node: unknown): unknown { + if (node == null || typeof node === 'string' || typeof node === 'number') { + return node + } + if (Array.isArray(node)) { + return node.map((entry) => expand(entry)) + } + if (!React.isValidElement(node)) { + if (typeof node === 'object' && 'props' in node) { + const element = node as ReactElementLike + return { + ...element, + props: { + ...element.props, + children: expand(element.props.children) + } + } + } + return node + } + const element = node as React.ReactElement> + if (typeof element.type === 'function') { + const Component = element.type as (props: Record) => unknown + return expand(Component(element.props)) + } + return { + type: element.type, + props: { + ...element.props, + children: expand(element.props.children) + } + } +} + +function findByType(node: unknown, type: string): ReactElementLike { + if (node && typeof node === 'object' && 'type' in node) { + const element = node as ReactElementLike + if (element.type === type) { + return element + } + const children = element.props.children + if (Array.isArray(children)) { + for (const child of children) { + try { + return findByType(child, type) + } catch { + // Continue searching siblings. + } + } + } else if (children) { + return findByType(children, type) + } + } + throw new Error(`Unable to find ${type}`) +} + +describe('BrowserAnnotationSendMenuContent', () => { + it('uses the review notes send content so existing agent sessions are selectable', () => { + const onPromptDelivered = vi.fn() + const tree = expand( + + ) + + expect(findByType(tree, 'ReviewNotesSendMenuContent').props).toMatchObject({ + worktreeId: 'wt-1', + groupId: 'group-1', + prompt: 'browser annotation prompt', + promptDelivery: 'submit-after-ready', + launchSource: 'notes_send', + onPromptDelivered + }) + }) + + it('is wired into both browser annotation send surfaces', () => { + const browserPaneSource = readFileSync( + fileURLToPath(new URL('./BrowserPane.tsx', import.meta.url)), + 'utf8' + ) + + expect(browserPaneSource.match(/ void +} + +export function BrowserAnnotationSendMenuContent({ + worktreeId, + groupId, + prompt, + onPromptDelivered +}: BrowserAnnotationSendMenuContentProps): React.JSX.Element { + return ( + + ) +} diff --git a/src/renderer/src/components/browser-pane/BrowserPane.tsx b/src/renderer/src/components/browser-pane/BrowserPane.tsx index 6931cf214..0d75bc980 100644 --- a/src/renderer/src/components/browser-pane/BrowserPane.tsx +++ b/src/renderer/src/components/browser-pane/BrowserPane.tsx @@ -45,8 +45,7 @@ import { } from 'lucide-react' import { Button } from '@/components/ui/button' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' -import { QuickLaunchAgentMenuItems } from '@/components/tab-bar/QuickLaunchButton' -import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { BrowserAnnotationSendMenuContent } from './BrowserAnnotationSendMenuContent' import { DropdownMenu, DropdownMenuContent, @@ -5297,7 +5296,7 @@ function BrowserPagePane({ {translate( 'auto.components.browser.pane.BrowserPane.95af781091', - 'Send feedback to a new agent' + 'Send feedback to an agent' )} @@ -5307,13 +5306,10 @@ function BrowserPagePane({ onInteractOutside={preventAgentSendTargetOutsideDismiss} onPointerDownOutside={preventAgentSendTargetOutsideDismiss} > - @@ -5571,7 +5567,7 @@ function BrowserPagePane({ {translate( 'auto.components.browser.pane.BrowserPane.95af781091', - 'Send feedback to a new agent' + 'Send feedback to an agent' )} @@ -5581,13 +5577,10 @@ function BrowserPagePane({ onInteractOutside={preventAgentSendTargetOutsideDismiss} onPointerDownOutside={preventAgentSendTargetOutsideDismiss} > - diff --git a/src/renderer/src/components/editor/EditorAutosaveController.tsx b/src/renderer/src/components/editor/EditorAutosaveController.tsx index 0ba4358d7..d96556166 100644 --- a/src/renderer/src/components/editor/EditorAutosaveController.tsx +++ b/src/renderer/src/components/editor/EditorAutosaveController.tsx @@ -1,13 +1,21 @@ import { useEffect } from 'react' import { useAppStore } from '@/store' import { attachEditorAutosaveController } from './editor-autosave-controller' +import { attachRestoredTabConflictScan } from './editor-restored-tab-conflict-scan' export default function EditorAutosaveController(): null { useEffect(() => { // Why: autosave and quit coordination need to survive editor tab switches, // but keeping the full EditorPanel mounted while hidden widened the restart // surface too far. Keep only this narrow controller alive between mounts. - return attachEditorAutosaveController(useAppStore) + const detachAutosave = attachEditorAutosaveController(useAppStore) + // Why: restored dirty tabs must be conflict-checked app-level, before any + // panel mounts — autosave can otherwise write over an offline agent edit. + const detachConflictScan = attachRestoredTabConflictScan(useAppStore) + return () => { + detachAutosave() + detachConflictScan() + } }, []) return null diff --git a/src/renderer/src/components/editor/EditorContent.test.tsx b/src/renderer/src/components/editor/EditorContent.test.tsx index d1507dd2a..130c92abe 100644 --- a/src/renderer/src/components/editor/EditorContent.test.tsx +++ b/src/renderer/src/components/editor/EditorContent.test.tsx @@ -1,6 +1,14 @@ import { renderToStaticMarkup } from 'react-dom/server' import { afterEach, describe, expect, it, vi } from 'vitest' import type { OpenFile } from '@/store/slices/editor' + +// Why: EditorContent's mode renderers (Monaco, DiffViewer, ...) are lazy(); +// renderToStaticMarkup cannot resolve them. Stubbing them keeps the banner +// branch structure renderable so its placement is pinned by tests. +vi.mock('@/lib/lazy-with-retry', () => ({ + lazyWithRetry: () => () => null +})) + import { EditorContent, getMarkdownSourceLineOffset } from './EditorContent' function createOpenFile(overrides: Partial = {}): OpenFile { @@ -67,7 +75,7 @@ describe('EditorContent', () => { handleDirtyStateHint={vi.fn()} handleSave={vi.fn()} handleSaveForFile={vi.fn()} - reloadFileContent={vi.fn()} + reloadContent={vi.fn()} /> ) @@ -75,4 +83,137 @@ describe('EditorContent', () => { expect(html).toContain('Access denied') expect(html).not.toContain('Unable to render notebook') }) + + it('shows the changed-on-disk banner above a dirty edit tab', () => { + const activeFile = createOpenFile({ + id: '/repo/file.ts', + filePath: '/repo/file.ts', + relativePath: 'file.ts', + language: 'typescript', + isDirty: true, + externalMutation: 'changed' + }) + const html = renderToStaticMarkup( + + ) + + expect(html).toContain('role="alert"') + expect(html).toContain('changed on disk') + expect(html).toContain('Reload from Disk') + }) + + it('shows the changed-on-disk banner above a dirty unstaged diff without collapsing it', () => { + const activeFile = createOpenFile({ + id: 'diff:/repo/file.ts', + filePath: '/repo/file.ts', + relativePath: 'file.ts', + language: 'typescript', + mode: 'diff', + diffSource: 'unstaged', + isDirty: true, + externalMutation: 'changed' + }) + const html = renderToStaticMarkup( + + ) + + expect(html).toContain('role="alert"') + expect(html).toContain('changed on disk') + // Why: the diff-mode wrapper must give the viewer its height back — a + // flex-1-only wrapper collapsed the DiffViewer to 0px (found live). + expect(html).toContain('flex h-full min-h-0 flex-col') + }) + + it('shows the changed-on-disk banner on a dirty markdown diff in preview mode', () => { + const activeFile = createOpenFile({ + id: 'diff:/repo/notes.md', + filePath: '/repo/notes.md', + relativePath: 'notes.md', + language: 'markdown', + mode: 'diff', + diffSource: 'unstaged', + isDirty: true, + externalMutation: 'changed' + }) + const html = renderToStaticMarkup( + + ) + + expect(html).toContain('role="alert"') + expect(html).toContain('changed on disk') + expect(html).toContain('Previewing the modified version of this diff') + }) }) diff --git a/src/renderer/src/components/editor/EditorContent.tsx b/src/renderer/src/components/editor/EditorContent.tsx index ed813e0ec..76996c0ac 100644 --- a/src/renderer/src/components/editor/EditorContent.tsx +++ b/src/renderer/src/components/editor/EditorContent.tsx @@ -33,6 +33,7 @@ import { import { getDiffContentSignature } from './diff-content-signature' import { translate } from '@/i18n/i18n' import { CheckRunDetailsPanel } from './CheckRunDetailsPanel' +import { ExternalFileChangeBanner } from './ExternalFileChangeBanner' const MonacoEditor = lazy(() => import('./MonacoEditor')) const DiffViewer = lazy(() => import('./DiffViewer')) @@ -139,7 +140,7 @@ export function EditorContent({ handleDirtyStateHint, handleSave, handleSaveForFile, - reloadFileContent + reloadContent }: { activeFile: OpenFile viewStateScopeId: string @@ -166,7 +167,7 @@ export function EditorContent({ handleDirtyStateHint: (dirty: boolean) => void handleSave: (content: string) => Promise handleSaveForFile: (file: OpenFile, content: string) => Promise - reloadFileContent: (file: OpenFile) => void + reloadContent: (file: OpenFile) => void }): React.JSX.Element { const editorViewStateKey = viewStateScopeId === activeFile.id @@ -505,10 +506,7 @@ export function EditorContent({ if (fc.loadError) { return (
- reloadFileContent(contentFile)} - /> + reloadContent(contentFile)} />
) } @@ -709,9 +707,7 @@ export function EditorContent({ ) } if (fc.loadError) { - return ( - reloadFileContent(activeFile)} /> - ) + return reloadContent(activeFile)} /> } if (fc.isBinary) { return ( @@ -758,9 +754,7 @@ export function EditorContent({ ) } if (fc.loadError) { - return ( - reloadFileContent(activeFile)} /> - ) + return reloadContent(activeFile)} /> } if (fc.isBinary) { if (fc.isImage) { @@ -777,8 +771,16 @@ export function EditorContent({ ) } + const externalChangeBanner = + activeFile.externalMutation === 'changed' ? ( + + ) : null if (isChangesMode) { - return ( + const changesView = ( ) + if (!externalChangeBanner) { + return changesView + } + return ( +
+ {externalChangeBanner} +
{changesView}
+
+ ) } return (
+ {externalChangeBanner} {activeFile.conflict && ( + ) : null if (isMarkdown && mdViewMode === 'preview' && dc.largeDiffRenderLimit?.limited !== true) { return (
+ {diffExternalChangeBanner}
{/* Why: a rendered markdown preview cannot express additions and deletions simultaneously, so preview mode intentionally shows the @@ -927,7 +950,7 @@ export function EditorContent({ const diffReloadNonce = activeFile.diffContentReloadNonce ?? 0 const originalModelKey = `${diffViewStateKey}:original:${getDiffContentSignature(dc.originalContent)}` const modifiedModelKey = `${diffViewStateKey}:modified:${getDiffContentSignature(dc.modifiedContent)}:${diffReloadNonce}` - return ( + const diffViewer = ( ) + // Why: editable unstaged diffs can hold unsaved edits, so they get the same + // changed-on-disk recovery banner as edit tabs; its reload refetches the + // diff body rather than plain file content. + if (activeFile.externalMutation !== 'changed') { + return diffViewer + } + return ( + // Why: h-full (not flex-1) — the diff-mode container is not a flex parent, + // so flex-1 resolves to zero height and collapses this wrapper. The inner + // div must itself be a flex column because DiffViewer's root sizes with + // flex-1 and collapses to 0px inside a block parent. +
+ {diffExternalChangeBanner} +
{diffViewer}
+
+ ) } // Why: a minimal read-only banner that shows the raw front-matter content diff --git a/src/renderer/src/components/editor/EditorPanel.tsx b/src/renderer/src/components/editor/EditorPanel.tsx index 8af1758a1..03fde8425 100644 --- a/src/renderer/src/components/editor/EditorPanel.tsx +++ b/src/renderer/src/components/editor/EditorPanel.tsx @@ -92,7 +92,7 @@ function EditorPanelInner({ activeFile.mode === 'edit' && canUseChangesModeForFile(activeFile) && editorViewMode[activeFile.id] === 'changes' - const { fileContents, diffContents, reloadFileContent } = useEditorPanelContentState({ + const { fileContents, diffContents, reloadContent } = useEditorPanelContentState({ activeFile, isChangesMode: requestedChangesMode, openFiles, @@ -377,7 +377,7 @@ function EditorPanelInner({ onDirtyStateHint={handleDirtyStateHint} onSave={handleSave} onSaveForFile={handleSaveForFile} - onReloadFileContent={reloadFileContent} + onReloadContent={reloadContent} onCloseMarkdownTableOfContents={() => setMarkdownTableOfContentsVisible(markdownDocumentStateFileId, false) } diff --git a/src/renderer/src/components/editor/EditorPanelShell.tsx b/src/renderer/src/components/editor/EditorPanelShell.tsx index 89d2a2a8a..de63cd78b 100644 --- a/src/renderer/src/components/editor/EditorPanelShell.tsx +++ b/src/renderer/src/components/editor/EditorPanelShell.tsx @@ -46,7 +46,7 @@ type EditorPanelShellProps = { onDirtyStateHint: (dirty: boolean) => void onSave: (content: string) => Promise onSaveForFile: (file: OpenFile, content: string) => Promise - onReloadFileContent: (file: OpenFile) => void + onReloadContent: (file: OpenFile) => void onCloseMarkdownTableOfContents: () => void onCloseRenameDialog: () => void onRenameConfirm: (newRelPath: string) => Promise @@ -86,7 +86,7 @@ export function EditorPanelShell({ onDirtyStateHint, onSave, onSaveForFile, - onReloadFileContent, + onReloadContent, onCloseMarkdownTableOfContents, onCloseRenameDialog, onRenameConfirm, @@ -152,7 +152,7 @@ export function EditorPanelShell({ handleDirtyStateHint={onDirtyStateHint} handleSave={onSave} handleSaveForFile={onSaveForFile} - reloadFileContent={onReloadFileContent} + reloadContent={onReloadContent} showMarkdownTableOfContents={showMarkdownTableOfContents} showMarkdownFrontmatter={markdownFrontmatterVisible} onCloseMarkdownTableOfContents={onCloseMarkdownTableOfContents} diff --git a/src/renderer/src/components/editor/ExternalFileChangeBanner.test.tsx b/src/renderer/src/components/editor/ExternalFileChangeBanner.test.tsx new file mode 100644 index 000000000..eae2909be --- /dev/null +++ b/src/renderer/src/components/editor/ExternalFileChangeBanner.test.tsx @@ -0,0 +1,231 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { OpenFile } from '@/store/slices/editor' + +const toastMock = vi.hoisted(() => vi.fn()) +const readRuntimeFileContentMock = vi.hoisted(() => vi.fn()) +vi.mock('sonner', () => ({ + toast: toastMock +})) +vi.mock('@/store', () => ({ + useAppStore: { + getState: vi.fn() + } +})) +vi.mock('@/runtime/runtime-file-client', () => ({ + readRuntimeFileContent: readRuntimeFileContentMock +})) +vi.mock('@/runtime/runtime-rpc-client', () => ({ + settingsForRuntimeOwner: () => null +})) +vi.mock('@/lib/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) + +import { + ExternalFileChangeBanner, + keepTabEditsOverExternalChange, + reloadTabContentFromDisk +} from './ExternalFileChangeBanner' +import { getDiskBaselineSignature } from './diff-content-signature' +import { useAppStore } from '@/store' + +const file = { + id: 'file-1', + filePath: '/repo/notes.md', + relativePath: 'notes.md', + worktreeId: 'wt-1', + mode: 'edit', + isDirty: true, + externalMutation: 'changed' +} as OpenFile + +describe('ExternalFileChangeBanner', () => { + const clearEditorDraft = vi.fn() + const markFileDirty = vi.fn() + const setExternalMutation = vi.fn() + const setEditorDraft = vi.fn() + const setLastKnownDiskSignature = vi.fn() + + function mockStoreState(editorDrafts: Record, openFiles: OpenFile[] = [file]) { + vi.mocked(useAppStore.getState).mockReturnValue({ + clearEditorDraft, + markFileDirty, + setExternalMutation, + setEditorDraft, + setLastKnownDiskSignature, + editorDrafts, + openFiles, + settings: {} + } as never) + } + + beforeEach(() => { + vi.clearAllMocks() + readRuntimeFileContentMock.mockResolvedValue({ content: 'disk content', isBinary: false }) + mockStoreState({}) + }) + + it('renders the overwrite warning, all three actions, and an alert role', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('role="alert"') + expect(html).toContain('changed on disk') + expect(html).toContain('Saving will overwrite') + expect(html).toContain('Compare') + expect(html).toContain('Reload from Disk') + expect(html).toContain('Keep My Edits') + }) + + it('reload clears the draft, dirty flag, and mark before refetching content', () => { + mockStoreState({ 'file-1': 'unsaved text' }) + const calls: string[] = [] + clearEditorDraft.mockImplementation(() => calls.push('clearEditorDraft')) + markFileDirty.mockImplementation(() => calls.push('markFileDirty')) + setExternalMutation.mockImplementation(() => calls.push('setExternalMutation')) + const reloadContent = vi.fn(() => calls.push('reloadContent')) + + reloadTabContentFromDisk(file, reloadContent) + + expect(clearEditorDraft).toHaveBeenCalledWith('file-1') + expect(markFileDirty).toHaveBeenCalledWith('file-1', false) + expect(setExternalMutation).toHaveBeenCalledWith('file-1', null) + expect(reloadContent).toHaveBeenCalledWith(file) + // Why: the draft shadows loaded content (editBuffers ?? fileContents), so + // the refetch must come last or the stale unsaved text stays visible. + expect(calls).toEqual([ + 'clearEditorDraft', + 'markFileDirty', + 'setExternalMutation', + 'reloadContent' + ]) + }) + + it('reload offers an undo toast that restores the discarded draft and the conflict', () => { + mockStoreState({ 'file-1': 'discarded draft' }) + + reloadTabContentFromDisk(file, vi.fn()) + + expect(toastMock).toHaveBeenCalledTimes(1) + const options = toastMock.mock.calls[0][1] as { + action: { label: string; onClick: () => void } + } + vi.clearAllMocks() + // Why: after a real reload the tab is clean with no draft — the undo + // guard only restores over that untouched state. + mockStoreState({}, [{ ...file, isDirty: false, externalMutation: undefined } as OpenFile]) + + options.action.onClick() + + expect(setEditorDraft).toHaveBeenCalledWith('file-1', 'discarded draft') + expect(markFileDirty).toHaveBeenCalledWith('file-1', true) + // Why: disk still differs from the restored draft — the conflict (and its + // autosave suspension) must return with the edits. + expect(setExternalMutation).toHaveBeenCalledWith('file-1', 'changed') + }) + + it('undo is a no-op when the tab closed while the toast was up', () => { + mockStoreState({ 'file-1': 'discarded draft' }) + + reloadTabContentFromDisk(file, vi.fn()) + + const options = toastMock.mock.calls[0][1] as { + action: { label: string; onClick: () => void } + } + vi.clearAllMocks() + mockStoreState({}, []) + + options.action.onClick() + + expect(setEditorDraft).not.toHaveBeenCalled() + expect(markFileDirty).not.toHaveBeenCalled() + expect(setExternalMutation).not.toHaveBeenCalled() + }) + + it('undo is a no-op when the user typed or saved after the reload', () => { + mockStoreState({ 'file-1': 'discarded draft' }) + + reloadTabContentFromDisk(file, vi.fn()) + + const options = toastMock.mock.calls[0][1] as { + action: { label: string; onClick: () => void } + } + vi.clearAllMocks() + // Why: post-reload edits are newer intent than the discarded draft — + // undoing over them would be a second silent discard. + mockStoreState({ 'file-1': 'newer post-reload edits' }, [ + { ...file, isDirty: true, externalMutation: undefined } as OpenFile + ]) + + options.action.onClick() + + expect(setEditorDraft).not.toHaveBeenCalled() + expect(setExternalMutation).not.toHaveBeenCalled() + }) + + it('does not toast when there was no draft to restore', () => { + mockStoreState({}) + + reloadTabContentFromDisk(file, vi.fn()) + + expect(toastMock).not.toHaveBeenCalled() + }) + + it('undo restores the pre-reload disk signature with the draft', async () => { + // Why: the reload re-stamps the baseline to the new disk content; without + // restoring the old signature the restart scan sees disk == baseline and + // silently drops the conflict the undo just brought back. + mockStoreState({ 'file-1': 'discarded draft' }, [ + { ...file, lastKnownDiskSignature: 'pre-reload-signature' } as OpenFile + ]) + + reloadTabContentFromDisk(file, vi.fn()) + + const options = toastMock.mock.calls[0][1] as { + action: { label: string; onClick: () => void } + } + vi.clearAllMocks() + mockStoreState({}, [{ ...file, isDirty: false, externalMutation: undefined } as OpenFile]) + + options.action.onClick() + + expect(setLastKnownDiskSignature).toHaveBeenCalledWith('file-1', 'pre-reload-signature') + }) + + it('keep-my-edits clears the mark without touching the draft or dirty flag', () => { + keepTabEditsOverExternalChange(file) + + expect(setExternalMutation).toHaveBeenCalledWith('file-1', null) + expect(clearEditorDraft).not.toHaveBeenCalled() + expect(markFileDirty).not.toHaveBeenCalled() + }) + + it('keep-my-edits advances the disk baseline so the dismissal survives restart', async () => { + readRuntimeFileContentMock.mockResolvedValue({ content: 'agent content', isBinary: false }) + mockStoreState({}, [{ ...file, externalMutation: undefined } as OpenFile]) + + keepTabEditsOverExternalChange(file) + await Promise.resolve() + await Promise.resolve() + + expect(setLastKnownDiskSignature).toHaveBeenCalledWith( + 'file-1', + getDiskBaselineSignature('agent content') + ) + }) + + it('keep-my-edits does not stamp a baseline over a newer conflict', async () => { + // Why: if the file changed again before the read resolved, the fresh + // 'changed' mark owns the baseline — stamping would hide that conflict + // from the restart scan. + readRuntimeFileContentMock.mockResolvedValue({ content: 'even newer', isBinary: false }) + mockStoreState({}, [{ ...file, externalMutation: 'changed' } as OpenFile]) + + keepTabEditsOverExternalChange(file) + await Promise.resolve() + await Promise.resolve() + + expect(setLastKnownDiskSignature).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/editor/ExternalFileChangeBanner.tsx b/src/renderer/src/components/editor/ExternalFileChangeBanner.tsx new file mode 100644 index 000000000..d23421605 --- /dev/null +++ b/src/renderer/src/components/editor/ExternalFileChangeBanner.tsx @@ -0,0 +1,185 @@ +import React, { useState } from 'react' +import { TriangleAlert } from 'lucide-react' +import { toast } from 'sonner' +import { Button } from '@/components/ui/button' +import { getConnectionIdForFile } from '@/lib/connection-context' +import { readRuntimeFileContent } from '@/runtime/runtime-file-client' +import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' +import { useAppStore } from '@/store' +import { translate } from '@/i18n/i18n' +import type { OpenFile } from '@/store/slices/editor' +import { ExternalFileChangeCompareDialog } from './ExternalFileChangeCompareDialog' +import { getDiskBaselineSignature } from './diff-content-signature' +import { trackExternalChangeConflictAction } from './editor-external-change-telemetry' + +// Why: when an external process (usually an agent) rewrites a file while the +// tab holds unsaved edits, the reload pipeline preserves the buffer and marks +// the tab externalMutation='changed' (issue #7265). This banner is the +// recovery path — without it the tab is silently stale until close/reopen and +// the next save clobbers the newer disk content unannounced. + +const RELOAD_UNDO_TOAST_DURATION_MS = 8_000 + +export function reloadTabContentFromDisk( + file: OpenFile, + reloadContent: (file: OpenFile) => void +): void { + const state = useAppStore.getState() + const discardedDraft = state.editorDrafts[file.id] + const discardedDiskSignature = state.openFiles.find( + (openFile) => openFile.id === file.id + )?.lastKnownDiskSignature + // Why: drop the draft before reloading — the buffer shadows loaded content + // (editBuffers ?? fileContents), so a reload alone would keep showing the + // stale unsaved text. + state.clearEditorDraft(file.id) + state.markFileDirty(file.id, false) + state.setExternalMutation(file.id, null) + reloadContent(file) + if (discardedDraft === undefined) { + return + } + // Why: on diff tabs the reload rotates the Monaco model, destroying the undo + // stack — without this toast a mistaken click is an unrecoverable discard. + toast( + translate('auto.components.editor.ExternalFileChangeBanner.5c02de9b31', 'Reloaded from disk'), + { + description: file.relativePath, + duration: RELOAD_UNDO_TOAST_DURATION_MS, + action: { + label: translate('auto.components.editor.ExternalFileChangeBanner.d1e830fa22', 'Undo'), + onClick: () => { + const current = useAppStore.getState() + const liveFile = current.openFiles.find((openFile) => openFile.id === file.id) + // Why: the tab may have closed while the toast was up; restoring a + // draft for a dead fileId would strand an orphan buffer. And if the + // user already typed after the reload (dirty), that newer work wins + // — undoing over it would be a second silent discard. isDirty is the + // signal: the editor content-sync repopulates editorDrafts with the + // reloaded content itself, so draft existence proves nothing. + if (!liveFile || liveFile.isDirty) { + return + } + current.setEditorDraft(file.id, discardedDraft) + current.markFileDirty(file.id, true) + // Why: the disk still differs from the restored draft, so the + // conflict (and its autosave suspension) must come back with it. + current.setExternalMutation(file.id, 'changed') + if (discardedDiskSignature !== undefined) { + // Why: the reload re-stamped the baseline to the new disk content; + // restoring the pre-reload signature with the draft keeps the + // restart scan re-deriving the conflict the undo just brought back. + current.setLastKnownDiskSignature(file.id, discardedDiskSignature) + } + trackExternalChangeConflictAction(file, 'undo_reload') + } + } + } + ) +} + +export function keepTabEditsOverExternalChange(file: OpenFile): void { + const state = useAppStore.getState() + state.setExternalMutation(file.id, null) + // Why: the dismissal must survive restart — without advancing the baseline + // to the current disk content, the restored-tab conflict scan re-derives + // the dismissed conflict from the stale signature on every launch. + // Best-effort: a failed read leaves the old signature, which can only + // re-surface the banner — never lose data. + void readRuntimeFileContent({ + settings: settingsForRuntimeOwner(state.settings, file.runtimeEnvironmentId), + filePath: file.filePath, + relativePath: file.relativePath, + worktreeId: file.worktreeId, + connectionId: getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined + }) + .then((result) => { + if (result.isBinary) { + return + } + const current = useAppStore.getState() + const liveFile = current.openFiles.find((openFile) => openFile.id === file.id) + // Why: only stamp while the dismissal still stands — a save or a newer + // conflict marked in the interim owns the baseline. + if (!liveFile || liveFile.externalMutation === 'changed') { + return + } + current.setLastKnownDiskSignature(file.id, getDiskBaselineSignature(result.content)) + }) + .catch(() => undefined) +} + +export function ExternalFileChangeBanner({ + file, + currentContent, + reloadContent +}: { + file: OpenFile + /** The tab's live buffer (draft if dirty) — what "Keep My Edits" keeps. */ + currentContent: string + /** Refetches the tab's content — file body for edit tabs, diff body for + * unstaged diff tabs. */ + reloadContent: (file: OpenFile) => void +}): React.JSX.Element { + const [compareOpen, setCompareOpen] = useState(false) + + const handleReload = (): void => { + trackExternalChangeConflictAction(file, 'reload') + reloadTabContentFromDisk(file, reloadContent) + } + const handleKeepEdits = (): void => { + trackExternalChangeConflictAction(file, 'keep') + keepTabEditsOverExternalChange(file) + } + const handleCompare = (): void => { + trackExternalChangeConflictAction(file, 'compare') + setCompareOpen(true) + } + + return ( + // Why: role=alert because the banner appears asynchronously (an agent + // rewrote the file) — screen readers must announce it unprompted. +
+
+
+ + {/* Why: wraps instead of truncating — the overwrite warning at the + end of the sentence is the part the user must not lose. */} + + {translate( + 'auto.components.editor.ExternalFileChangeBanner.7c41e90d12', + 'This file changed on disk while you have unsaved edits. Saving will overwrite the newer disk content.' + )} + +
+
+ + + +
+
+ {compareOpen && ( + + )} +
+ ) +} diff --git a/src/renderer/src/components/editor/ExternalFileChangeCompareDialog.test.tsx b/src/renderer/src/components/editor/ExternalFileChangeCompareDialog.test.tsx new file mode 100644 index 000000000..2a9060055 --- /dev/null +++ b/src/renderer/src/components/editor/ExternalFileChangeCompareDialog.test.tsx @@ -0,0 +1,142 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OpenFile } from '@/store/slices/editor' + +const mocks = vi.hoisted(() => ({ + readRuntimeFileContent: vi.fn(), + getConnectionIdForFile: vi.fn(), + getState: vi.fn() +})) + +vi.mock('@/runtime/runtime-file-client', () => ({ + readRuntimeFileContent: mocks.readRuntimeFileContent +})) +vi.mock('@/runtime/runtime-rpc-client', () => ({ + settingsForRuntimeOwner: () => null +})) +vi.mock('@/lib/connection-context', () => ({ + getConnectionIdForFile: mocks.getConnectionIdForFile +})) +vi.mock('@/store', () => ({ + useAppStore: { getState: mocks.getState } +})) +// Why: the lazy DiffViewer chunk cannot resolve under happy-dom; a stub that +// echoes its props pins the disk-left/buffer-right wiring instead. +vi.mock('@/lib/lazy-with-retry', () => ({ + lazyWithRetry: () => (props: { originalContent: string; modifiedContent: string }) => ( +
+ original:{props.originalContent}|modified:{props.modifiedContent} +
+ ) +})) + +import { ExternalFileChangeCompareDialog } from './ExternalFileChangeCompareDialog' + +const file = { + id: 'file-1', + filePath: '/repo/notes.ts', + relativePath: 'notes.ts', + worktreeId: 'wt-1', + mode: 'edit', + isDirty: true, + externalMutation: 'changed' +} as OpenFile + +describe('ExternalFileChangeCompareDialog', () => { + let root: Root | null = null + let container: HTMLElement | null = null + + beforeEach(() => { + mocks.readRuntimeFileContent.mockReset() + mocks.getConnectionIdForFile.mockReset() + mocks.getConnectionIdForFile.mockReturnValue(undefined) + mocks.getState.mockReturnValue({ settings: null }) + container = document.createElement('div') + document.body.appendChild(container) + }) + + afterEach(async () => { + await act(async () => { + root?.unmount() + }) + container?.remove() + document.body.innerHTML = '' + }) + + async function render(element: React.JSX.Element): Promise { + await act(async () => { + root = createRoot(container!) + root.render(element) + }) + } + + it('shows the disk version left and the buffer right once the read resolves', async () => { + mocks.readRuntimeFileContent.mockResolvedValue({ content: 'disk version', isBinary: false }) + + await render( + + ) + + expect(document.body.textContent).toContain('File changed on disk') + expect(document.body.textContent).toContain('original:disk version|modified:buffer version') + expect(document.body.textContent).toContain('Reload from Disk') + expect(document.body.textContent).toContain('Keep My Edits') + }) + + it('surfaces a read failure instead of a blank comparison', async () => { + mocks.readRuntimeFileContent.mockRejectedValue(new Error('transport down')) + + await render( + + ) + + expect(document.body.textContent).toContain('Could not read the file from disk') + expect(document.body.textContent).toContain('transport down') + }) + + it('wires the footer actions and closes the dialog around them', async () => { + mocks.readRuntimeFileContent.mockResolvedValue({ content: 'disk version', isBinary: false }) + const onReload = vi.fn() + const onKeepEdits = vi.fn() + const onOpenChange = vi.fn() + + await render( + + ) + + const buttons = Array.from(document.body.querySelectorAll('button')) + await act(async () => { + buttons.find((b) => b.textContent === 'Reload from Disk')?.click() + }) + expect(onOpenChange).toHaveBeenCalledWith(false) + expect(onReload).toHaveBeenCalledTimes(1) + + await act(async () => { + buttons.find((b) => b.textContent === 'Keep My Edits')?.click() + }) + expect(onKeepEdits).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/components/editor/ExternalFileChangeCompareDialog.tsx b/src/renderer/src/components/editor/ExternalFileChangeCompareDialog.tsx new file mode 100644 index 000000000..eb6611abe --- /dev/null +++ b/src/renderer/src/components/editor/ExternalFileChangeCompareDialog.tsx @@ -0,0 +1,191 @@ +import React, { Suspense, useEffect, useState } from 'react' +import { Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { getConnectionIdForFile } from '@/lib/connection-context' +import { detectLanguage } from '@/lib/language-detect' +import { readRuntimeFileContent } from '@/runtime/runtime-file-client' +import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' +import { useAppStore } from '@/store' +import type { OpenFile } from '@/store/slices/editor' +import { translate } from '@/i18n/i18n' + +const DiffViewer = lazy(() => import('./DiffViewer')) + +type DiskReadState = + | { kind: 'loading' } + | { kind: 'error'; message: string } + | { kind: 'binary' } + | { kind: 'ready'; content: string } + +// Why: choosing between "Reload from Disk" and "Keep My Edits" blind is the +// sharpest edge of the changed-on-disk banner — this dialog shows exactly +// what each choice discards before the user commits (issue #7265 follow-up). +export function ExternalFileChangeCompareDialog({ + file, + currentContent, + open, + onOpenChange, + onReload, + onKeepEdits +}: { + file: OpenFile + /** The tab's live buffer — the unsaved edits the user would keep. */ + currentContent: string + open: boolean + onOpenChange: (open: boolean) => void + onReload: () => void + onKeepEdits: () => void +}): React.JSX.Element { + const [diskState, setDiskState] = useState({ kind: 'loading' }) + + useEffect(() => { + if (!open) { + return + } + let cancelled = false + setDiskState({ kind: 'loading' }) + // Why: read at open time — the banner can be minutes old and the agent + // may have written again since; the comparison must show current disk. + void readRuntimeFileContent({ + settings: settingsForRuntimeOwner(useAppStore.getState().settings, file.runtimeEnvironmentId), + filePath: file.filePath, + relativePath: file.relativePath, + worktreeId: file.worktreeId, + connectionId: getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined + }) + .then((result) => { + if (cancelled) { + return + } + setDiskState( + result.isBinary ? { kind: 'binary' } : { kind: 'ready', content: result.content } + ) + }) + .catch((err: unknown) => { + if (cancelled) { + return + } + setDiskState({ + kind: 'error', + message: err instanceof Error ? err.message : String(err) + }) + }) + return () => { + cancelled = true + } + }, [open, file.filePath, file.relativePath, file.worktreeId, file.runtimeEnvironmentId]) + + const language = detectLanguage(file.relativePath) + + return ( + + + + + {translate( + 'auto.components.editor.ExternalFileChangeCompareDialog.4b8de20a11', + 'File changed on disk' + )} + + + {translate( + 'auto.components.editor.ExternalFileChangeCompareDialog.90cc31e4d7', + 'Disk version on the left, your unsaved edits on the right.' + )} + + +
+ {diskState.kind === 'loading' ? ( +
+ + {translate( + 'auto.components.editor.ExternalFileChangeCompareDialog.8fe30ab254', + 'Reading file from disk...' + )} +
+ ) : diskState.kind === 'error' ? ( +
+ {translate( + 'auto.components.editor.ExternalFileChangeCompareDialog.e2b1cd0393', + 'Could not read the file from disk: {{value0}}', + { value0: diskState.message } + )} +
+ ) : diskState.kind === 'binary' ? ( +
+ {translate( + 'auto.components.editor.ExternalFileChangeCompareDialog.b6cf20d514', + 'The file on disk is binary — no text comparison available.' + )} +
+ ) : ( + + + {translate( + 'auto.components.editor.ExternalFileChangeCompareDialog.2c8f1e07b9', + 'Loading comparison...' + )} +
+ } + > +
+ +
+ + )} +
+ + + + + + + ) +} diff --git a/src/renderer/src/components/editor/diff-content-signature.ts b/src/renderer/src/components/editor/diff-content-signature.ts index 927d9711d..ba5bc26fc 100644 --- a/src/renderer/src/components/editor/diff-content-signature.ts +++ b/src/renderer/src/components/editor/diff-content-signature.ts @@ -9,3 +9,19 @@ export function getDiffContentSignature(content: string): string { } return (hash >>> 0).toString(16) } + +// Why: the disk baseline guards against silently overwriting external writes +// (issue #7265), where a hash collision means a missed conflict — so it gets +// two independent FNV lanes plus the length instead of the single 32-bit lane +// that suffices for cosmetic model rotation above. +export function getDiskBaselineSignature(content: string): string { + let hashA = 2166136261 + let hashB = 84696351 + for (let i = 0; i < content.length; i += 1) { + const code = content.charCodeAt(i) + hashA ^= code + hashA = Math.imul(hashA, 16777619) + hashB = Math.imul(hashB ^ code, 1099511627) + } + return `${(hashA >>> 0).toString(16)}-${(hashB >>> 0).toString(16)}-${content.length.toString(16)}` +} diff --git a/src/renderer/src/components/editor/editor-autosave-conflict-flow.test.ts b/src/renderer/src/components/editor/editor-autosave-conflict-flow.test.ts new file mode 100644 index 000000000..753836b65 --- /dev/null +++ b/src/renderer/src/components/editor/editor-autosave-conflict-flow.test.ts @@ -0,0 +1,191 @@ +// Why: the changed-on-disk conflict flow (issue #7265) — draft preservation, +// echo-aware backstop marking, autosave suspension, and baseline settling — +// in the headless autosave controller. Split from +// editor-autosave-controller.test.ts to stay under max-lines. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, requestEditorFileSave } from './editor-autosave' +import { attachEditorAutosaveController } from './editor-autosave-controller' +import { __clearSelfWriteRegistryForTests, recordSelfWrite } from './editor-self-write-registry' +import { createEditorStore, stubEditorWindow } from './editor-autosave-controller-test-fixture' + +const mocks = vi.hoisted(() => ({ + getConnectionIdForFile: vi.fn() +})) + +vi.mock('@/lib/connection-context', () => ({ + getConnectionIdForFile: mocks.getConnectionIdForFile +})) + +function openDirtyFile(store: ReturnType, draft = 'unsaved edit'): void { + store.getState().openFile({ + filePath: '/repo/file.ts', + relativePath: 'file.ts', + worktreeId: 'wt-1', + language: 'typescript', + mode: 'edit' + }) + store.getState().setEditorDraft('/repo/file.ts', draft) + store.getState().markFileDirty('/repo/file.ts', true) +} + +function dispatchExternalChange(): void { + window.dispatchEvent( + new CustomEvent(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, { + detail: { worktreeId: 'wt-1', worktreePath: '/repo', relativePath: 'file.ts' } + }) + ) +} + +describe('editor autosave changed-on-disk conflict flow', () => { + beforeEach(() => { + vi.useFakeTimers() + mocks.getConnectionIdForFile.mockReset() + mocks.getConnectionIdForFile.mockReturnValue(undefined) + }) + + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + __clearSelfWriteRegistryForTests() + }) + + it('preserves dirty drafts and marks the tab changed-on-disk on external file change', () => { + stubEditorWindow() + const store = createEditorStore() + openDirtyFile(store) + + const cleanup = attachEditorAutosaveController(store) + try { + dispatchExternalChange() + + const file = store.getState().openFiles[0] + expect(file?.isDirty).toBe(true) + expect(file?.externalMutation).toBe('changed') + expect(store.getState().editorDrafts['/repo/file.ts']).toBe('unsaved edit') + } finally { + cleanup() + } + }) + + it('clears drafts and a stale changed-on-disk mark for clean tabs on external file change', () => { + stubEditorWindow() + const store = createEditorStore() + store.getState().openFile({ + filePath: '/repo/file.ts', + relativePath: 'file.ts', + worktreeId: 'wt-1', + language: 'typescript', + mode: 'edit' + }) + store.getState().setExternalMutation('/repo/file.ts', 'changed') + + const cleanup = attachEditorAutosaveController(store) + try { + dispatchExternalChange() + + const file = store.getState().openFiles[0] + expect(file?.isDirty).toBe(false) + expect(file?.externalMutation).toBeUndefined() + } finally { + cleanup() + } + }) + + it('does not backstop-mark a dirty tab for the echo of its own save', () => { + stubEditorWindow() + const store = createEditorStore() + openDirtyFile(store, 'typed during save') + // Why: the combined-Changes reload notification routes through the + // controller for the saved path — a fresh self-write stamp means the + // event is Orca's own echo, not an external change. + recordSelfWrite('/repo/file.ts', 'orca save') + + const cleanup = attachEditorAutosaveController(store) + try { + dispatchExternalChange() + + const file = store.getState().openFiles[0] + expect(file?.externalMutation).toBeUndefined() + expect(file?.isDirty).toBe(true) + expect(store.getState().editorDrafts['/repo/file.ts']).toBe('typed during save') + } finally { + cleanup() + } + }) + + it('suspends autosave while a tab is marked changed-on-disk and resumes when cleared', async () => { + const writeFile = stubEditorWindow() + const store = createEditorStore() + openDirtyFile(store, 'user edit') + store.getState().setExternalMutation('/repo/file.ts', 'changed') + + const cleanup = attachEditorAutosaveController(store) + try { + await vi.advanceTimersByTimeAsync(1500) + expect(writeFile).not.toHaveBeenCalled() + + // Keep My Edits clears the mark — autosave resumes and overwrites. + store.getState().setExternalMutation('/repo/file.ts', null) + await vi.advanceTimersByTimeAsync(1500) + expect(writeFile).toHaveBeenCalledWith({ + filePath: '/repo/file.ts', + content: 'user edit' + }) + } finally { + cleanup() + } + }) + + it('suspends autosave while a restored tab awaits disk baseline verification', async () => { + const writeFile = stubEditorWindow() + const store = createEditorStore() + openDirtyFile(store, 'restored draft') + // Why: mimic hydration — the scan has not yet compared disk against the + // persisted baseline, so autosave must hold off (a slow remote read must + // not lose a race to this timer). + store.setState({ + openFiles: store + .getState() + .openFiles.map((f) => + f.id === '/repo/file.ts' ? { ...f, pendingDiskBaselineVerification: true } : f + ) + } as never) + + const cleanup = attachEditorAutosaveController(store) + try { + await vi.advanceTimersByTimeAsync(1500) + expect(writeFile).not.toHaveBeenCalled() + + store.getState().clearPendingDiskBaselineVerification('/repo/file.ts') + await vi.advanceTimersByTimeAsync(1500) + expect(writeFile).toHaveBeenCalledWith({ + filePath: '/repo/file.ts', + content: 'restored draft' + }) + } finally { + cleanup() + } + }) + + it('clears the changed-on-disk mark after a successful save', async () => { + const writeFile = stubEditorWindow() + const store = createEditorStore() + openDirtyFile(store, 'user version') + store.getState().setExternalMutation('/repo/file.ts', 'changed') + + const cleanup = attachEditorAutosaveController(store) + try { + await requestEditorFileSave({ fileId: '/repo/file.ts' }) + + expect(writeFile).toHaveBeenCalledWith({ + filePath: '/repo/file.ts', + content: 'user version' + }) + const file = store.getState().openFiles[0] + expect(file?.isDirty).toBe(false) + expect(file?.externalMutation).toBeUndefined() + } finally { + cleanup() + } + }) +}) diff --git a/src/renderer/src/components/editor/editor-autosave-controller-test-fixture.ts b/src/renderer/src/components/editor/editor-autosave-controller-test-fixture.ts new file mode 100644 index 000000000..6ecf88409 --- /dev/null +++ b/src/renderer/src/components/editor/editor-autosave-controller-test-fixture.ts @@ -0,0 +1,52 @@ +// Why: shared rig for autosave-controller suites — the controller needs a +// real editor store slice plus a window stub (event target, timers, fs +// bridge), and duplicating that per test file bloats suites past max-lines. +import { vi } from 'vitest' +import { createStore, type StoreApi } from 'zustand/vanilla' +import { createEditorSlice } from '@/store/slices/editor' +import type { AppState } from '@/store' + +export type EditorWindowStub = { + addEventListener: Window['addEventListener'] + removeEventListener: Window['removeEventListener'] + dispatchEvent: Window['dispatchEvent'] + setTimeout: Window['setTimeout'] + clearTimeout: Window['clearTimeout'] + api: { + fs: { + writeFile: ReturnType + } + } +} + +/** Stubs the global window with an isolated event target and fs bridge; + * returns the writeFile mock for assertions. */ +export function stubEditorWindow(): ReturnType { + const writeFile = vi.fn().mockResolvedValue(undefined) + const eventTarget = new EventTarget() + vi.stubGlobal('window', { + addEventListener: eventTarget.addEventListener.bind(eventTarget), + removeEventListener: eventTarget.removeEventListener.bind(eventTarget), + dispatchEvent: eventTarget.dispatchEvent.bind(eventTarget), + setTimeout: globalThis.setTimeout.bind(globalThis), + clearTimeout: globalThis.clearTimeout.bind(globalThis), + api: { + fs: { + writeFile + } + } + } satisfies EditorWindowStub) + return writeFile +} + +export function createEditorStore(): StoreApi { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createStore()((...args: any[]) => ({ + activeWorktreeId: 'wt-1', + settings: { + editorAutoSave: true, + editorAutoSaveDelayMs: 1000 + }, + ...createEditorSlice(...(args as Parameters)) + })) as unknown as StoreApi +} diff --git a/src/renderer/src/components/editor/editor-autosave-controller.ts b/src/renderer/src/components/editor/editor-autosave-controller.ts index 23de3fecd..7c6f043bd 100644 --- a/src/renderer/src/components/editor/editor-autosave-controller.ts +++ b/src/renderer/src/components/editor/editor-autosave-controller.ts @@ -16,6 +16,7 @@ import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' import { canAutoSaveOpenFile, getOpenFilesForExternalFileChange, + isAutosaveSuspendedForFile, normalizeAutoSaveDelayMs, ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, ORCA_EDITOR_FILE_SAVED_EVENT, @@ -27,8 +28,16 @@ import { type EditorSaveFileDetail, type EditorSaveQuiesceDetail } from './editor-autosave' +import { markFileChangedOnDisk } from './editor-changed-on-disk-mark' import { flushPendingEditorChange } from './editor-pending-flush' -import { clearSelfWrite, recordSelfWrite } from './editor-self-write-registry' +import { + clearSelfWrite, + hasRecentSelfWrite, + recordSelfWrite, + SELF_WRITE_REMOTE_TTL_MS +} from './editor-self-write-registry' +import { getDiskBaselineSignature } from './diff-content-signature' +import { trackExternalChangeConflictAction } from './editor-external-change-telemetry' import { autosaveSubscriberInputsEqual, getAutosaveSubscriberInputs, @@ -62,7 +71,11 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { saveGeneration.set(fileId, (saveGeneration.get(fileId) ?? 0) + 1) } - const queueSave = (file: OpenFile, fallbackContent: string): Promise => { + const queueSave = ( + file: OpenFile, + fallbackContent: string, + trigger: 'autosave' | 'user' = 'user' + ): Promise => { clearAutoSaveTimer(file.id) const queuedGeneration = saveGeneration.get(file.id) ?? 0 @@ -80,6 +93,12 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { return } + // Why: explicit user saves proceed even while suspended (the banner + // warned) and clear both suspension flags below. + if (trigger === 'autosave' && isAutosaveSuspendedForFile(liveFile)) { + return + } + const contentToSave = state.editorDrafts[file.id] ?? fallbackContent const connectionId = getConnectionIdForFile(liveFile.worktreeId, liveFile.filePath) ?? undefined @@ -91,7 +110,14 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { // round-tripping back into a setContent that jumps the cursor to the // end (and, under round-trip drift, can drop keystrokes typed in the // debounce window). See editor-self-write-registry. - recordSelfWrite(liveFile.filePath, contentToSave, liveFile.runtimeEnvironmentId) + recordSelfWrite( + liveFile.filePath, + contentToSave, + liveFile.runtimeEnvironmentId, + connectionId || liveFile.runtimeEnvironmentId?.trim() + ? SELF_WRITE_REMOTE_TTL_MS + : undefined + ) try { await writeRuntimeFile( { @@ -122,6 +148,21 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { if (!stillDirty) { nextState.clearEditorDraft(file.id) } + // Why: disk now holds contentToSave — future edits baseline on it, and + // a restore must not flag our own save as an external change. An + // explicit save also settles any pending baseline verification: the + // user chose to write, so there is nothing left to verify against. + nextState.setLastKnownDiskSignature(file.id, getDiskBaselineSignature(contentToSave)) + nextState.clearPendingDiskBaselineVerification(file.id) + // Why: the write just made disk match the buffer, resolving any + // changed-on-disk conflict in favor of the user's content. The banner + // warned before this point; keeping the mark would show a stale + // conflict for a file that no longer diverges. + const savedFile = nextState.openFiles.find((openFile) => openFile.id === file.id) + if (savedFile?.externalMutation === 'changed') { + trackExternalChangeConflictAction(savedFile, 'save_overwrite') + nextState.setExternalMutation(file.id, null) + } window.dispatchEvent( new CustomEvent(ORCA_EDITOR_FILE_SAVED_EVENT, { @@ -171,6 +212,9 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { file && file.isDirty && canAutoSaveOpenFile(file) && + // Why: suspension holds until the user picks a side via the banner + // (or saves manually) — see the queueSave guard. + !isAutosaveSuspendedForFile(file) && draft !== undefined if (!shouldKeepTimer) { clearAutoSaveTimer(fileId) @@ -184,7 +228,12 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { const autoSaveDelayMs = normalizeAutoSaveDelayMs(state.settings.editorAutoSaveDelayMs) for (const file of state.openFiles) { const draft = state.editorDrafts[file.id] - if (!file.isDirty || draft === undefined || !canAutoSaveOpenFile(file)) { + if ( + !file.isDirty || + draft === undefined || + !canAutoSaveOpenFile(file) || + isAutosaveSuspendedForFile(file) + ) { clearAutoSaveTimer(file.id) continue } @@ -198,7 +247,7 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { const timerId = window.setTimeout(() => { autoSaveTimers.delete(file.id) autoSaveScheduledContent.delete(file.id) - void queueSave(file, draft) + void queueSave(file, draft, 'autosave') }, autoSaveDelayMs) autoSaveTimers.set(file.id, timerId) } @@ -377,12 +426,35 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { return } + // Why: dirty files must keep their draft — destroying unsaved edits on an + // external write is the data-loss half of issue #7265. Mark them + // changed-on-disk instead (backstop for tabs that became dirty during the + // notify debounce; the watch hook marks the ones dirty at event time). + const reloadingFiles = matchingFiles.filter((file) => !file.isDirty) for (const file of matchingFiles) { + if (file.isDirty) { + // Why: the self-write check keeps this backstop from marking on the + // echo of Orca's own save (the combined-Changes reload notification + // routes through here and would otherwise bypass the watch hook's + // echo verification). + if (!hasRecentSelfWrite(file.filePath, file.runtimeEnvironmentId)) { + markFileChangedOnDisk(state, file, { + connectionId: getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined, + origin: 'live' + }) + } + continue + } clearAutoSaveTimer(file.id) bumpSaveGeneration(file.id) state.markFileDirty(file.id, false) + // Why: this file is about to reload fresh disk content, so a stale + // changed-on-disk mark (set while it was dirty) is resolved. + if (file.externalMutation === 'changed') { + state.setExternalMutation(file.id, null) + } } - state.clearEditorDrafts(matchingFiles.map((file) => file.id)) + state.clearEditorDrafts(reloadingFiles.map((file) => file.id)) } // Why: the root store subscriber fires for every terminal title/focus tick. diff --git a/src/renderer/src/components/editor/editor-autosave.ts b/src/renderer/src/components/editor/editor-autosave.ts index 09d0ae866..c36f91e8a 100644 --- a/src/renderer/src/components/editor/editor-autosave.ts +++ b/src/renderer/src/components/editor/editor-autosave.ts @@ -77,6 +77,16 @@ export function canAutoSaveOpenFile(file: OpenFile): boolean { return file.mode === 'edit' || (file.mode === 'diff' && file.diffSource === 'unstaged') } +// Why: autosave must not resolve a changed-on-disk conflict by overwriting +// the newer external content, nor write over a restored tab whose disk +// baseline is still unverified (the conflict may simply not be marked YET). +// One predicate so the save-queue gate and the timer scheduler cannot drift. +export function isAutosaveSuspendedForFile( + file: Pick +): boolean { + return file.externalMutation === 'changed' || file.pendingDiskBaselineVerification === true +} + export function normalizeAutoSaveDelayMs(value: unknown): number { // Why: settings are persisted locally and can be missing or hand-edited. // Clamp the delay at the write site so autosave never degenerates into an @@ -176,6 +186,9 @@ export function requestEditorFileClose(fileId: string): void { ) } +// CONTRACT: this event fires even when some tabs of the path are dirty — +// every consumer MUST skip dirty files per-file. Reloading a dirty tab's +// content destroys its unsaved draft (the data-loss half of issue #7265). export function notifyEditorExternalFileChange(target: EditorPathMutationTarget): void { window.dispatchEvent( new CustomEvent(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, { diff --git a/src/renderer/src/components/editor/editor-changed-on-disk-mark.ts b/src/renderer/src/components/editor/editor-changed-on-disk-mark.ts new file mode 100644 index 000000000..06e726bd2 --- /dev/null +++ b/src/renderer/src/components/editor/editor-changed-on-disk-mark.ts @@ -0,0 +1,26 @@ +import type { OpenFile } from '@/store/slices/editor' +import { canAutoSaveOpenFile } from './editor-autosave' +import { trackExternalChangeConflictShown } from './editor-external-change-telemetry' + +type ChangedOnDiskMarkState = { + setExternalMutation: (fileId: string, mutation: 'deleted' | 'renamed' | 'changed' | null) => void +} + +// Why: the changed-on-disk mark has one rule — dirty, banner-capable tab, +// telemetry only on the first surfacing — but three writers (the watch hook +// at fs-event time, the autosave controller's notification backstop, and the +// restored-tab conflict scan). Centralizing keeps the rule from drifting; +// each writer keeps its own echo/eligibility guard at the call site. +export function markFileChangedOnDisk( + state: ChangedOnDiskMarkState, + file: OpenFile, + options: { connectionId: string | undefined; origin: 'live' | 'restore' } +): void { + if (!file.isDirty || !canAutoSaveOpenFile(file)) { + return + } + if (file.externalMutation !== 'changed') { + trackExternalChangeConflictShown(file, options) + } + state.setExternalMutation(file.id, 'changed') +} diff --git a/src/renderer/src/components/editor/editor-external-change-telemetry.ts b/src/renderer/src/components/editor/editor-external-change-telemetry.ts new file mode 100644 index 000000000..f9752147c --- /dev/null +++ b/src/renderer/src/components/editor/editor-external-change-telemetry.ts @@ -0,0 +1,62 @@ +// Why: one place derives the path-free analytics shape for the changed-on-disk +// conflict flow (issue #7265), so the three marking sites and the banner +// actions cannot drift on enum values. Measures false-banner rates per +// transport and which resolution users actually pick. +import { track } from '@/lib/telemetry' +import { getConnectionIdForFile } from '@/lib/connection-context' +import type { OpenFile } from '@/store/slices/editor' + +type ConflictSurface = 'edit' | 'unstaged-diff' +type ConflictTransport = 'local' | 'ssh' | 'runtime' + +export type ExternalChangeConflictAction = + | 'reload' + | 'keep' + | 'compare' + | 'undo_reload' + | 'save_overwrite' + +function conflictSurface(file: Pick): ConflictSurface { + return file.mode === 'edit' ? 'edit' : 'unstaged-diff' +} + +export function conflictTransport( + connectionId: string | undefined, + runtimeEnvironmentId: string | null | undefined +): ConflictTransport { + if (connectionId) { + return 'ssh' + } + if (runtimeEnvironmentId?.trim()) { + return 'runtime' + } + return 'local' +} + +export function trackExternalChangeConflictShown( + file: Pick, + options: { connectionId: string | undefined; origin: 'live' | 'restore' } +): void { + track('editor_external_change_conflict_shown', { + surface: conflictSurface(file), + transport: conflictTransport(options.connectionId, file.runtimeEnvironmentId), + origin: options.origin + }) +} + +export function trackExternalChangeConflictAction( + file: Pick, + action: ExternalChangeConflictAction +): void { + track('editor_external_change_conflict_action', { + action, + surface: conflictSurface(file), + // Why: shown-vs-action cross-tabs per transport are the point of the + // metric — false-banner detection needs to see WHICH transports' banners + // users dismiss versus act on. + transport: conflictTransport( + getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined, + file.runtimeEnvironmentId + ) + }) +} diff --git a/src/renderer/src/components/editor/editor-restored-tab-conflict-scan.test.ts b/src/renderer/src/components/editor/editor-restored-tab-conflict-scan.test.ts new file mode 100644 index 000000000..8c50887a0 --- /dev/null +++ b/src/renderer/src/components/editor/editor-restored-tab-conflict-scan.test.ts @@ -0,0 +1,273 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createStore, type StoreApi } from 'zustand/vanilla' +import { createEditorSlice } from '@/store/slices/editor' +import type { AppState } from '@/store' +import { attachRestoredTabConflictScan } from './editor-restored-tab-conflict-scan' +import { getDiskBaselineSignature } from './diff-content-signature' + +const mocks = vi.hoisted(() => ({ + readRuntimeFileContent: vi.fn(), + getConnectionIdForFile: vi.fn(), + pathExists: vi.fn() +})) + +vi.mock('@/runtime/runtime-file-client', () => ({ + readRuntimeFileContent: mocks.readRuntimeFileContent +})) +vi.mock('@/runtime/runtime-rpc-client', () => ({ + settingsForRuntimeOwner: () => null +})) +vi.mock('@/lib/connection-context', () => ({ + getConnectionIdForFile: mocks.getConnectionIdForFile +})) + +function createEditorStore(): StoreApi { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createStore()((...args: any[]) => ({ + settings: {}, + ...createEditorSlice(...(args as Parameters)) + })) as unknown as StoreApi +} + +function openRestoredDirtyTab( + store: StoreApi, + filePath: string, + baselineContent: string +): void { + store.getState().openFile({ + filePath, + relativePath: filePath.slice(1), + worktreeId: 'wt-1', + language: 'typescript', + mode: 'edit' + }) + store.getState().setEditorDraft(filePath, 'restored draft') + store.getState().markFileDirty(filePath, true) + store.getState().setLastKnownDiskSignature(filePath, getDiskBaselineSignature(baselineContent)) + // Why: hydration flags restored dirty tabs for verification; tests mimic it. + store.setState({ + openFiles: store + .getState() + .openFiles.map((f) => + f.id === filePath ? { ...f, pendingDiskBaselineVerification: true } : f + ) + } as never) +} + +describe('attachRestoredTabConflictScan', () => { + beforeEach(() => { + vi.useFakeTimers() + mocks.readRuntimeFileContent.mockReset() + mocks.getConnectionIdForFile.mockReset() + mocks.getConnectionIdForFile.mockReturnValue(undefined) + mocks.pathExists.mockReset() + mocks.pathExists.mockResolvedValue(true) + vi.stubGlobal('window', { api: { fs: { pathExists: mocks.pathExists } } }) + }) + + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + it('marks a restored dirty tab whose file changed while the app was closed', async () => { + mocks.readRuntimeFileContent.mockResolvedValue({ + content: 'agent rewrote this offline', + isBinary: false + }) + const store = createEditorStore() + openRestoredDirtyTab(store, '/repo/file.ts', 'original baseline') + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + expect(store.getState().openFiles[0]?.externalMutation).toBe('changed') + } finally { + detach() + } + }) + + it('leaves a restored dirty tab unmarked when disk still matches its baseline', async () => { + mocks.readRuntimeFileContent.mockResolvedValue({ + content: 'original baseline', + isBinary: false + }) + const store = createEditorStore() + openRestoredDirtyTab(store, '/repo/file.ts', 'original baseline') + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + expect(store.getState().openFiles[0]?.externalMutation).toBeUndefined() + expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(1) + } finally { + detach() + } + }) + + it('does not read files for clean tabs or tabs without a baseline', async () => { + const store = createEditorStore() + store.getState().openFile({ + filePath: '/repo/clean.ts', + relativePath: 'clean.ts', + worktreeId: 'wt-1', + language: 'typescript', + mode: 'edit' + }) + store.getState().openFile({ + filePath: '/repo/dirty-no-baseline.ts', + relativePath: 'dirty-no-baseline.ts', + worktreeId: 'wt-1', + language: 'typescript', + mode: 'edit' + }) + store.getState().setEditorDraft('/repo/dirty-no-baseline.ts', 'draft') + store.getState().markFileDirty('/repo/dirty-no-baseline.ts', true) + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + expect(mocks.readRuntimeFileContent).not.toHaveBeenCalled() + } finally { + detach() + } + }) + + it('retries a failed read and marks once the file becomes readable', async () => { + // Why: SSH/runtime connections come up after launch; the first reads fail. + mocks.readRuntimeFileContent + .mockRejectedValueOnce(new Error('connection not ready')) + .mockResolvedValue({ content: 'agent rewrote this offline', isBinary: false }) + const store = createEditorStore() + openRestoredDirtyTab(store, '/repo/file.ts', 'original baseline') + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + expect(store.getState().openFiles[0]?.externalMutation).toBeUndefined() + await vi.advanceTimersByTimeAsync(2_100) + expect(store.getState().openFiles[0]?.externalMutation).toBe('changed') + } finally { + detach() + } + }) + + it('clears the pending-verification flag on both verification outcomes', async () => { + mocks.readRuntimeFileContent.mockResolvedValue({ + content: 'original baseline', + isBinary: false + }) + const store = createEditorStore() + openRestoredDirtyTab(store, '/repo/match.ts', 'original baseline') + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + // Why: the flag suspends autosave — leaving it set after a clean + // verification would strand the tab's autosave forever. + expect(store.getState().openFiles[0]?.pendingDiskBaselineVerification).toBeUndefined() + + mocks.readRuntimeFileContent.mockResolvedValue({ + content: 'agent rewrote this offline', + isBinary: false + }) + openRestoredDirtyTab(store, '/repo/mismatch.ts', 'original baseline') + await vi.advanceTimersByTimeAsync(10) + const mismatchTab = store.getState().openFiles.find((f) => f.id === '/repo/mismatch.ts') + expect(mismatchTab?.externalMutation).toBe('changed') + expect(mismatchTab?.pendingDiskBaselineVerification).toBeUndefined() + } finally { + detach() + } + }) + + it('does not re-verify live dirty tabs that were never flagged at hydration', async () => { + const store = createEditorStore() + store.getState().openFile({ + filePath: '/repo/live.ts', + relativePath: 'live.ts', + worktreeId: 'wt-1', + language: 'typescript', + mode: 'edit' + }) + store.getState().setEditorDraft('/repo/live.ts', 'live edits') + store.getState().markFileDirty('/repo/live.ts', true) + store.getState().setLastKnownDiskSignature('/repo/live.ts', getDiskBaselineSignature('base')) + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + // Why: in-session drift is the live watcher's job; re-reading here would + // turn the scan into a poller and skew the 'restore' telemetry origin. + expect(mocks.readRuntimeFileContent).not.toHaveBeenCalled() + } finally { + detach() + } + }) + + it('resolves verification with a deleted mark when the file is definitively gone', async () => { + // Why: a file deleted while the app was closed can never verify — without + // a terminal state the retry loop keeps the tab's autosave silently + // suspended for the whole session. + mocks.readRuntimeFileContent.mockRejectedValue(new Error('ENOENT')) + mocks.pathExists.mockResolvedValue(false) + const store = createEditorStore() + openRestoredDirtyTab(store, '/repo/deleted.ts', 'original baseline') + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + const tab = store.getState().openFiles[0] + expect(tab?.pendingDiskBaselineVerification).toBeUndefined() + expect(tab?.externalMutation).toBe('deleted') + // Why: the verification is resolved — no further retries may fire. + await vi.advanceTimersByTimeAsync(60_000) + expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(1) + } finally { + detach() + } + }) + + it('keeps retrying with the suspension intact when the existence probe fails', async () => { + // Why: a transport that is down cannot disprove existence — lifting the + // suspension unverified would reopen the clobber window the moment the + // transport recovers. + mocks.readRuntimeFileContent.mockRejectedValue(new Error('connection not ready')) + mocks.pathExists.mockRejectedValue(new Error('connection not ready')) + const store = createEditorStore() + openRestoredDirtyTab(store, '/repo/unreachable.ts', 'original baseline') + + const detach = attachRestoredTabConflictScan(store) + try { + await vi.advanceTimersByTimeAsync(10) + await vi.advanceTimersByTimeAsync(2_100) + const tab = store.getState().openFiles[0] + expect(tab?.pendingDiskBaselineVerification).toBe(true) + expect(tab?.externalMutation).toBeUndefined() + expect(mocks.readRuntimeFileContent.mock.calls.length).toBeGreaterThan(1) + } finally { + detach() + } + }) + + it('does not mark a tab that was saved while the read was in flight', async () => { + let resolveRead: (value: { content: string; isBinary: boolean }) => void = () => {} + mocks.readRuntimeFileContent.mockReturnValue( + new Promise((resolve) => { + resolveRead = resolve + }) + ) + const store = createEditorStore() + openRestoredDirtyTab(store, '/repo/file.ts', 'original baseline') + + const detach = attachRestoredTabConflictScan(store) + try { + store.getState().markFileDirty('/repo/file.ts', false) + resolveRead({ content: 'agent rewrote this offline', isBinary: false }) + await vi.advanceTimersByTimeAsync(10) + expect(store.getState().openFiles[0]?.externalMutation).toBeUndefined() + } finally { + detach() + } + }) +}) diff --git a/src/renderer/src/components/editor/editor-restored-tab-conflict-scan.ts b/src/renderer/src/components/editor/editor-restored-tab-conflict-scan.ts new file mode 100644 index 000000000..bc4029321 --- /dev/null +++ b/src/renderer/src/components/editor/editor-restored-tab-conflict-scan.ts @@ -0,0 +1,186 @@ +// Why: a dirty tab restored from a workspace session carries edits based on +// disk content that may have changed while the app was closed (an agent write, +// a sync tool). The in-memory changed-on-disk mark does not survive restarts, +// so without this scan a resumed autosave would silently overwrite that newer +// content (issue #7265 follow-up). The scan re-derives the conflict from +// ground truth: it reads each restored dirty tab's file and compares the disk +// signature against the persisted edit baseline. Autosave is hard-suspended +// for those tabs (pendingDiskBaselineVerification, set at hydration) until a +// verification resolves — otherwise the read would merely race the autosave +// timer and a slow remote read would lose. +import type { StoreApi } from 'zustand' +import type { AppState } from '@/store' +import type { OpenFile } from '@/store/slices/editor' +import { getConnectionIdForFile } from '@/lib/connection-context' +import { readRuntimeFileContent } from '@/runtime/runtime-file-client' +import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' +import { canAutoSaveOpenFile } from './editor-autosave' +import { getDiskBaselineSignature } from './diff-content-signature' +import { markFileChangedOnDisk } from './editor-changed-on-disk-mark' + +type AppStoreApi = Pick, 'getState' | 'subscribe'> + +// Why: SSH/runtime reads fail while the connection is still coming up after +// launch. Retry fast for the first minute, then keep probing slowly — +// giving up on a transport error would either strand the tab's autosave +// suspension or lift it unverified right as the transport comes back up. +// Only a definitive not-found (file deleted while the app was closed) ends +// the loop early; see probeFileMissing. +const VERIFY_RETRY_MS = 2_000 +const VERIFY_SLOW_RETRY_MS = 15_000 +const VERIFY_FAST_ATTEMPTS = 30 + +export function attachRestoredTabConflictScan(store: AppStoreApi): () => void { + // Why: dedupes in-flight verifications; the store's pending flag is the + // durable "needs verification" signal. + const inFlightFileIds = new Set() + const attemptsByFileId = new Map() + const retryTimers = new Set>() + let disposed = false + + // Why: distinguishes "file was deleted while the app was closed" (a + // definitive not-found) from a transport still coming up. Only local/SSH + // paths can be probed — for runtime-owned files window.api.fs would stat + // the client-local path and misreport a remote file as gone. + const probeFileMissing = async (file: OpenFile): Promise => { + const settings = settingsForRuntimeOwner(store.getState().settings, file.runtimeEnvironmentId) + if (settings?.activeRuntimeEnvironmentId?.trim()) { + return false + } + try { + const exists = await globalThis.window?.api?.fs?.pathExists?.({ + filePath: file.filePath, + connectionId: getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined + }) + return exists === false + } catch { + // Why: a failed probe can't disprove existence — keep retrying. + return false + } + } + + const verify = async (file: OpenFile): Promise => { + // Why: OpenFile ids are file paths — a marker left behind by an early + // exit would silently skip every future verification of a reopened + // same-path tab. Only a scheduled retry may keep the marker set. + let retryScheduled = false + try { + const state = store.getState() + const result = await readRuntimeFileContent({ + settings: settingsForRuntimeOwner(state.settings, file.runtimeEnvironmentId), + filePath: file.filePath, + relativePath: file.relativePath, + worktreeId: file.worktreeId, + connectionId: getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined + }) + if (disposed) { + return + } + const liveFile = store.getState().openFiles.find((f) => f.id === file.id) + if (!liveFile) { + return + } + // Why: verification resolved — lift the autosave suspension regardless + // of outcome. If a save raced the read, the save already re-baselined + // and cleared the flag itself; wasPending distinguishes that case. + const wasPending = liveFile.pendingDiskBaselineVerification === true + store.getState().clearPendingDiskBaselineVerification(file.id) + if ( + !wasPending || + result.isBinary || + !liveFile.isDirty || + liveFile.externalMutation === 'changed' + ) { + return + } + if (getDiskBaselineSignature(result.content) !== file.lastKnownDiskSignature) { + markFileChangedOnDisk(store.getState(), liveFile, { + connectionId: getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined, + origin: 'restore' + }) + } + } catch { + if (disposed) { + return + } + if (await probeFileMissing(file)) { + if (disposed) { + return + } + // Why: a definitive not-found IS ground truth — there is no newer + // disk content for a save to clobber, so verification is resolved. + // Converge to the live delete affordance (tombstone mark) instead of + // retrying forever with the tab's autosave silently suspended. + const liveFile = store.getState().openFiles.find((f) => f.id === file.id) + if (!liveFile) { + return + } + const wasPending = liveFile.pendingDiskBaselineVerification === true + store.getState().clearPendingDiskBaselineVerification(file.id) + if (wasPending && liveFile.isDirty && liveFile.externalMutation !== 'changed') { + store.getState().setExternalMutation(file.id, 'deleted') + } + return + } + if (disposed) { + return + } + const attempts = (attemptsByFileId.get(file.id) ?? 0) + 1 + attemptsByFileId.set(file.id, attempts) + retryScheduled = true + const timer = setTimeout( + () => { + retryTimers.delete(timer) + inFlightFileIds.delete(file.id) + scan() + }, + attempts < VERIFY_FAST_ATTEMPTS ? VERIFY_RETRY_MS : VERIFY_SLOW_RETRY_MS + ) + retryTimers.add(timer) + } finally { + if (!retryScheduled) { + inFlightFileIds.delete(file.id) + } + } + } + + const scan = (): void => { + if (disposed) { + return + } + for (const file of store.getState().openFiles) { + if ( + !file.pendingDiskBaselineVerification || + !file.isDirty || + !file.lastKnownDiskSignature || + file.externalMutation === 'changed' || + !canAutoSaveOpenFile(file) || + inFlightFileIds.has(file.id) + ) { + continue + } + inFlightFileIds.add(file.id) + void verify(file) + } + } + + let previousOpenFiles = store.getState().openFiles + const unsubscribe = store.subscribe(() => { + const nextOpenFiles = store.getState().openFiles + if (nextOpenFiles === previousOpenFiles) { + return + } + previousOpenFiles = nextOpenFiles + scan() + }) + scan() + + return () => { + disposed = true + unsubscribe() + for (const timer of retryTimers) { + clearTimeout(timer) + } + retryTimers.clear() + } +} diff --git a/src/renderer/src/components/editor/editor-self-write-registry.test.ts b/src/renderer/src/components/editor/editor-self-write-registry.test.ts index d05a98a40..e2eacaca9 100644 --- a/src/renderer/src/components/editor/editor-self-write-registry.test.ts +++ b/src/renderer/src/components/editor/editor-self-write-registry.test.ts @@ -4,7 +4,8 @@ import { __getSelfWriteRegistrySizeForTests, clearSelfWrite, hasRecentSelfWrite, - recordSelfWrite + recordSelfWrite, + SELF_WRITE_REMOTE_TTL_MS } from './editor-self-write-registry' describe('editor self-write registry', () => { @@ -77,4 +78,15 @@ describe('editor self-write registry', () => { expect(hasRecentSelfWrite('/repo/0.md')).toBe(false) expect(hasRecentSelfWrite('/repo/259.md')).toBe(true) }) + + it('keeps remote-TTL stamps alive past the local window', () => { + // Why: SSH/runtime watcher echoes can land seconds after the write; the + // longer TTL keeps them recognized as Orca's own save. + recordSelfWrite('/repo/remote.md', 'content', 'env-1', SELF_WRITE_REMOTE_TTL_MS) + + vi.advanceTimersByTime(751) + expect(hasRecentSelfWrite('/repo/remote.md', 'env-1')).toBe(true) + vi.advanceTimersByTime(SELF_WRITE_REMOTE_TTL_MS) + expect(hasRecentSelfWrite('/repo/remote.md', 'env-1')).toBe(false) + }) }) diff --git a/src/renderer/src/components/editor/editor-self-write-registry.ts b/src/renderer/src/components/editor/editor-self-write-registry.ts index 561f4ec61..0bf0b1150 100644 --- a/src/renderer/src/components/editor/editor-self-write-registry.ts +++ b/src/renderer/src/components/editor/editor-self-write-registry.ts @@ -12,6 +12,11 @@ import { normalizeAbsolutePathForComparison } from '@/components/right-sidebar/f // path, bounded by a short TTL so a genuinely external edit that lands after // the window still gets picked up. const SELF_WRITE_TTL_MS = 750 +// Why: SSH/runtime watcher echoes travel a poll-plus-network path and can +// land seconds after the write. A local-sized TTL lets the echo arrive after +// the stamp expired, which raises a false changed-on-disk banner on remote +// tabs while typing with autosave on. +export const SELF_WRITE_REMOTE_TTL_MS = 3000 const SELF_WRITE_MAX_STAMPS = 256 export type RecentSelfWrite = { @@ -49,7 +54,8 @@ function enforceSelfWriteStampLimit(): void { export function recordSelfWrite( absolutePath: string, content?: string, - runtimeEnvironmentId?: string | null + runtimeEnvironmentId?: string | null, + ttlMs: number = SELF_WRITE_TTL_MS ): void { const now = Date.now() pruneExpiredSelfWrites(now) @@ -59,7 +65,7 @@ export function recordSelfWrite( stamps.delete(key) stamps.set(key, { content: content ?? null, - expiresAt: now + SELF_WRITE_TTL_MS + expiresAt: now + ttlMs }) enforceSelfWriteStampLimit() } diff --git a/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx index 8a932eb36..15cd29adb 100644 --- a/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx @@ -47,6 +47,7 @@ vi.mock('@/store', () => ({ })) import { useEditorPanelContentState } from './useEditorPanelContentState' +import { getDiskBaselineSignature } from './diff-content-signature' import { ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT } from './editor-autosave' type Deferred = { @@ -87,6 +88,7 @@ type ProbeProps = { let latestFileContents: Record = {} let latestDiffContents: Record = {} +let latestReloadContent: (file: OpenFile) => void = () => {} const EMPTY_GIT_STATUS_BY_WORKTREE: Record = {} function HookProbe({ @@ -103,6 +105,7 @@ function HookProbe({ }) latestFileContents = state.fileContents latestDiffContents = state.diffContents + latestReloadContent = state.reloadContent return null } @@ -135,7 +138,11 @@ describe('useEditorPanelContentState', () => { mocks.isWorktreeConnectionResolved.mockReset() mocks.isWorktreeConnectionResolved.mockReturnValue(true) mocks.getState.mockReset() - mocks.getState.mockReturnValue({ settings: null }) + mocks.getState.mockReturnValue({ + settings: null, + openFiles: [], + setLastKnownDiskSignature: vi.fn() + }) }) afterEach(() => { @@ -564,4 +571,124 @@ describe('useEditorPanelContentState', () => { }) expect(latestDiffContents[activeFile.id]?.modifiedContent).toBe('fresh diff content') }) + + it('routes reloadContent for a diff tab to a forced diff refetch, not a file read', async () => { + // Why: the changed-on-disk banner's "Reload from Disk" on an unstaged + // diff tab must refetch the diff body — routing it to the file store + // would leave the visible diff stale (and vice versa for edit tabs). + const activeFile = createOpenFile({ + id: 'wt-1::diff::unstaged::file.ts', + mode: 'diff', + diffSource: 'unstaged' + }) + mocks.getRuntimeGitDiff + .mockResolvedValueOnce({ + kind: 'text', + originalContent: 'old', + modifiedContent: 'first diff content', + originalIsBinary: false, + modifiedIsBinary: false + }) + .mockResolvedValueOnce({ + kind: 'text', + originalContent: 'old', + modifiedContent: 'reloaded diff content', + originalIsBinary: false, + modifiedIsBinary: false + }) + + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + await act(async () => { + root?.render() + }) + await vi.waitFor(() => + expect(latestDiffContents[activeFile.id]?.modifiedContent).toBe('first diff content') + ) + + await act(async () => { + latestReloadContent(activeFile) + }) + + await vi.waitFor(() => + expect(latestDiffContents[activeFile.id]?.modifiedContent).toBe('reloaded diff content') + ) + expect(mocks.getRuntimeGitDiff).toHaveBeenCalledTimes(2) + expect(mocks.readRuntimeFileContent).not.toHaveBeenCalled() + }) + + it('routes reloadContent for an edit tab to a forced file read, not a diff refetch', async () => { + const activeFile = createOpenFile() + mocks.readRuntimeFileContent + .mockResolvedValueOnce({ content: 'old content', isBinary: false }) + .mockResolvedValueOnce({ content: 'reloaded content', isBinary: false }) + + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + await act(async () => { + root?.render() + }) + await vi.waitFor(() => expect(latestFileContents[activeFile.id]?.content).toBe('old content')) + + await act(async () => { + latestReloadContent(activeFile) + }) + + await vi.waitFor(() => + expect(latestFileContents[activeFile.id]?.content).toBe('reloaded content') + ) + expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(2) + expect(mocks.getRuntimeGitDiff).not.toHaveBeenCalled() + }) + + it('stamps the disk baseline when a clean tab load resolves', async () => { + const activeFile = createOpenFile() + const setLastKnownDiskSignature = vi.fn() + mocks.getState.mockReturnValue({ + settings: null, + openFiles: [activeFile], + setLastKnownDiskSignature + }) + mocks.readRuntimeFileContent.mockResolvedValue({ content: 'disk content', isBinary: false }) + + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + await act(async () => { + root?.render() + }) + + await vi.waitFor(() => + expect(setLastKnownDiskSignature).toHaveBeenCalledWith( + activeFile.id, + getDiskBaselineSignature('disk content') + ) + ) + }) + + it('keeps a dirty tab baseline untouched by content loads', async () => { + // Why: a dirty tab's draft still derives from the OLD content — moving + // the baseline on load would hide the conflict its restore check exists + // to catch. + const activeFile = createOpenFile({ isDirty: true }) + const setLastKnownDiskSignature = vi.fn() + mocks.getState.mockReturnValue({ + settings: null, + openFiles: [activeFile], + setLastKnownDiskSignature + }) + mocks.readRuntimeFileContent.mockResolvedValue({ content: 'disk content', isBinary: false }) + + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + await act(async () => { + root?.render() + }) + + await vi.waitFor(() => expect(latestFileContents[activeFile.id]?.content).toBe('disk content')) + expect(setLastKnownDiskSignature).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/components/editor/useEditorPanelContentState.ts b/src/renderer/src/components/editor/useEditorPanelContentState.ts index 152b8974f..ae05de954 100644 --- a/src/renderer/src/components/editor/useEditorPanelContentState.ts +++ b/src/renderer/src/components/editor/useEditorPanelContentState.ts @@ -10,6 +10,7 @@ import { } from '@/lib/connection-context' import { joinPath } from '@/lib/path' import { useAppStore } from '@/store' +import { getDiskBaselineSignature } from './diff-content-signature' import { getRuntimeFileReadScope, readRuntimeFileContent } from '@/runtime/runtime-file-client' import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' import { @@ -51,7 +52,26 @@ type UseEditorPanelContentStateParams = { type UseEditorPanelContentStateResult = { fileContents: Record diffContents: Record - reloadFileContent: (file: OpenFile) => void + reloadContent: (file: OpenFile) => void +} + +// Why: a clean load re-baselines what this tab's future edits are based on; a +// dirty tab keeps its baseline (its draft still derives from the older content +// the signature was taken over). Best-effort metadata — a failure here must +// not convert an already-delivered load into an error view, hence the guard. +function stampCleanTabDiskBaseline(id: string, result: FileContent): void { + if (result.isBinary || result.loadError) { + return + } + try { + const state = useAppStore.getState() + const loadedFile = state.openFiles.find((file) => file.id === id) + if (loadedFile && !loadedFile.isDirty) { + state.setLastKnownDiskSignature(id, getDiskBaselineSignature(result.content)) + } + } catch (err) { + console.warn('[editor] failed to stamp disk baseline', err) + } } function inFlightReadKey(connectionId: string | undefined, filePath: string): string { @@ -171,6 +191,7 @@ export function useEditorPanelContentState({ } delete fileLoadRetryAttemptsRef.current[id] setFileContents((prev) => ({ ...prev, [id]: result })) + stampCleanTabDiskBaseline(id, result) } catch (err) { if (fileReadGenerationRef.current[id] !== generation) { return @@ -304,8 +325,23 @@ export function useEditorPanelContentState({ [] ) - const reloadFileContent = useCallback( + // Why: the changed-on-disk banner's explicit reload on an unstaged diff tab + // must refetch the diff body, not the plain file content — one entry point + // branches on the tab mode so every consumer reloads the right store. + const reloadContent = useCallback( (file: OpenFile): void => { + if (file.mode === 'diff') { + setDiffContents((prev) => { + if (!prev[file.id]) { + return prev + } + const next = { ...prev } + delete next[file.id] + return next + }) + void loadDiffContent(file, { force: true }) + return + } delete fileLoadRetryAttemptsRef.current[file.id] setFileContents((prev) => { if (!prev[file.id]) { @@ -319,7 +355,7 @@ export function useEditorPanelContentState({ force: true }) }, - [loadFileContent] + [loadDiffContent, loadFileContent] ) useEffect(() => { @@ -507,5 +543,5 @@ export function useEditorPanelContentState({ setDiffContents ) - return { fileContents, diffContents, reloadFileContent } + return { fileContents, diffContents, reloadContent } } diff --git a/src/renderer/src/components/editor/useEditorPanelExternalContentEvents.ts b/src/renderer/src/components/editor/useEditorPanelExternalContentEvents.ts index 3b70c27b4..19650b1cd 100644 --- a/src/renderer/src/components/editor/useEditorPanelExternalContentEvents.ts +++ b/src/renderer/src/components/editor/useEditorPanelExternalContentEvents.ts @@ -43,6 +43,12 @@ export function useEditorPanelExternalContentEvents({ return } for (const file of getOpenFilesForExternalFileChange(openFilesRef.current, detail)) { + // Why: a dirty file keeps its unsaved buffer (issue #7265) — it is + // marked changed-on-disk upstream and resolves via the editor banner, + // a save, or a later clean reload. Reloading here would clobber it. + if (file.isDirty) { + continue + } if (file.mode === 'edit' || file.mode === 'markdown-preview') { // Why: external writes must replace any in-flight pre-change read so // the tab shows the new on-disk content, not a stale dedupe result. diff --git a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.test.tsx b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.test.tsx index 5b7f7bc94..7709c4f95 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.test.tsx @@ -159,7 +159,7 @@ describe('useEditorPanelFileLoadRetry — owner-not-ready bounding (#6648)', () }) expect(loadFileContent.mock.calls.length).toBe(callsAfterTerminal) - // Retry (reloadFileContent) clears the attempt budget for a fresh start. + // Retry (reloadContent) clears the attempt budget for a fresh start. delete attemptsRef.current[file.id] expect(attemptsRef.current[file.id]).toBeUndefined() }) diff --git a/src/renderer/src/components/github-item-dialog-merge-routing.test.ts b/src/renderer/src/components/github-item-dialog-merge-routing.test.ts deleted file mode 100644 index 8374fe94b..000000000 --- a/src/renderer/src/components/github-item-dialog-merge-routing.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - getSettingsForRepoRuntimeOwner, - type RepoRuntimeOwnerState -} from '../lib/repo-runtime-owner' -import { getActiveRuntimeTarget } from '../runtime/runtime-rpc-client' -import type { TaskSourceContext } from '../../../shared/task-source-context' -import { getTaskSourceRuntimeSettings } from '../../../shared/task-source-context' - -// Why: mirrors the merge-routing decision inside GitHubItemDialog's -// PRActionsPanel so a revert to source-only routing (issue #6957) fails here. -// A runtime-owned repo whose GitHub source view is local must still merge on -// the owner runtime, not fall back to local `gh:mergePR`. -function resolveMergeTarget( - state: RepoRuntimeOwnerState, - repoId: string | null, - sourceContext: TaskSourceContext | null -): ReturnType { - const repoOwnerSettings = getSettingsForRepoRuntimeOwner(state, repoId) - const sourceSettings = - sourceContext?.provider !== 'github' - ? repoOwnerSettings - : (() => { - const sourceRuntimeSettings = getTaskSourceRuntimeSettings(sourceContext) - return sourceRuntimeSettings.activeRuntimeEnvironmentId - ? { ...repoOwnerSettings, ...sourceRuntimeSettings } - : repoOwnerSettings - })() - return getActiveRuntimeTarget(sourceSettings) -} - -function githubSource(hostId: TaskSourceContext['hostId']): TaskSourceContext { - return { kind: 'task-source', provider: 'github', projectId: 'p', hostId, repoId: 'repo-1' } -} - -describe('GitHubItemDialog PR merge routing', () => { - const runtimeOwnedRepo: RepoRuntimeOwnerState = { - settings: { activeRuntimeEnvironmentId: null }, - repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'runtime:owner-runtime' }] - } - - it('routes a runtime-owned repo to its owner runtime when the source view is local (#6957)', () => { - expect(resolveMergeTarget(runtimeOwnedRepo, 'repo-1', githubSource('local'))).toEqual({ - kind: 'environment', - environmentId: 'owner-runtime' - }) - }) - - it('routes a runtime-owned repo to its owner runtime when there is no source context', () => { - expect(resolveMergeTarget(runtimeOwnedRepo, 'repo-1', null)).toEqual({ - kind: 'environment', - environmentId: 'owner-runtime' - }) - }) - - it('lets a runtime source override the repo owner when both are runtimes', () => { - expect( - resolveMergeTarget(runtimeOwnedRepo, 'repo-1', githubSource('runtime:source-runtime')) - ).toEqual({ kind: 'environment', environmentId: 'source-runtime' }) - }) - - it('keeps an explicitly-local repo on local IPC even while a runtime is focused', () => { - const localRepo: RepoRuntimeOwnerState = { - settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, - repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'local' }] - } - expect(resolveMergeTarget(localRepo, 'repo-1', githubSource('local'))).toEqual({ - kind: 'local' - }) - }) -}) diff --git a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts b/src/renderer/src/components/github-item-dialog-source-boundary.test.ts index 740d65f67..951e22d66 100644 --- a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts +++ b/src/renderer/src/components/github-item-dialog-source-boundary.test.ts @@ -67,6 +67,9 @@ describe('GitHubItemDialog source host boundaries', () => { expect(helperSection).toContain("'github.project.updatePullRequestBySlug'") expect(helperSection).toContain("args.sourceContext?.provider === 'github'") expect(helperSection).toContain('getTaskSourceRuntimeSettings(args.sourceContext)') + expect(helperSection).toContain( + 'getGitHubMutationRoutingSettings(useAppStore.getState(), args.repoId, args.sourceContext)' + ) expect(helperSection).toContain('notifyWorkItemDetailsMutation(') expect(helperSection).toContain( "repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? '')" @@ -91,8 +94,8 @@ describe('GitHubItemDialog source host boundaries', () => { expect(source).toContain('sourceContext,') expect(cacheKeySection).toContain('sourceCacheScope') expect(source).toContain('getTaskSourceCacheScope(sourceContext)') - expect(matchInvalidationSection).toMatch( - /if \(removed\) {\s+workItemDetailsCacheGeneration \+= 1/ + expect(matchInvalidationSection).toContain( + 'if (removed) {\n workItemDetailsCacheGeneration += 1' ) }) @@ -182,7 +185,7 @@ describe('GitHubItemDialog source host boundaries', () => { expect(source).toContain('notifyWorkItemMutated({') }) - it('routes merge actions through the task source context', () => { + it('routes merge actions through the repo owner host (#6957)', () => { const source = componentSource('GitHubItemDialog.tsx') const actionsSection = sourceBetween( source, @@ -190,13 +193,9 @@ describe('GitHubItemDialog source host boundaries', () => { 'function CommentReactions' ) - expect(actionsSection).toContain('getSettingsForRepoRuntimeOwner(s, repoId ?? item.repoId') - expect(actionsSection).toContain('...repoOwnerSettings') expect(actionsSection).toContain( - 'const sourceRuntimeSettings = getTaskSourceRuntimeSettings(sourceContext)' + 'getGitHubMutationRoutingSettings(s, item.repoId ?? repoId ?? null, sourceContext)' ) - expect(actionsSection).toContain('sourceRuntimeSettings.activeRuntimeEnvironmentId') - expect(actionsSection).toContain('...sourceRuntimeSettings') expect(actionsSection).toContain('getActiveRuntimeTarget(sourceSettings)') expect(actionsSection).toContain( 'const canMergeWithRepoContext = !!repoPath || mergeTarget.kind ===' diff --git a/src/renderer/src/components/mobile/mobile-platform-copy.ts b/src/renderer/src/components/mobile/mobile-platform-copy.ts index 057a20f49..378aa6018 100644 --- a/src/renderer/src/components/mobile/mobile-platform-copy.ts +++ b/src/renderer/src/components/mobile/mobile-platform-copy.ts @@ -20,7 +20,7 @@ const IOS_CHANNEL_COPY: Record = { const ANDROID_COPY: InstallCopy = { ctaLabel: 'Download APK', - url: 'https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk' + url: 'https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk' } export function getInstallCopy(platform: Platform, iosChannel: IosChannel): InstallCopy { diff --git a/src/renderer/src/components/pull-request-page-host-boundary.test.ts b/src/renderer/src/components/pull-request-page-host-boundary.test.ts index 888225aa3..89d0dc14f 100644 --- a/src/renderer/src/components/pull-request-page-host-boundary.test.ts +++ b/src/renderer/src/components/pull-request-page-host-boundary.test.ts @@ -270,6 +270,9 @@ describe('PullRequestPage host boundaries', () => { expect(editHelperSection).toContain('sourceContext?: TaskSourceContext | null') expect(editHelperSection).toContain("args.sourceContext?.provider === 'github'") expect(editHelperSection).toContain('getTaskSourceRuntimeSettings(args.sourceContext)') + expect(editHelperSection).toContain( + 'getGitHubMutationRoutingSettings(useAppStore.getState(), args.repoId, args.sourceContext)' + ) expect(editHelperSection).toContain( "repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? '')" ) @@ -278,7 +281,7 @@ describe('PullRequestPage host boundaries', () => { expect(editSection).toContain('sourceContext,') }) - it('routes merge actions through the PR source context', () => { + it('routes merge actions through the repo owner host (#6957)', () => { const source = componentSource('PullRequestPage.tsx') const actionsSection = sourceBetween( source, @@ -286,7 +289,9 @@ describe('PullRequestPage host boundaries', () => { 'function CommentReactions' ) - expect(actionsSection).toContain('getTaskSourceRuntimeSettings(sourceContext)') + expect(actionsSection).toContain( + 'getGitHubMutationRoutingSettings(s, item.repoId ?? repoId ?? null, sourceContext)' + ) expect(actionsSection).toContain('getActiveRuntimeTarget(sourceSettings)') expect(actionsSection).toContain( 'const canMergeWithRepoContext = !!repoPath || mergeTarget.kind ===' diff --git a/src/renderer/src/components/quick-open-file-list.react.test.tsx b/src/renderer/src/components/quick-open-file-list.react.test.tsx index ff76e4305..4a2305e06 100644 --- a/src/renderer/src/components/quick-open-file-list.react.test.tsx +++ b/src/renderer/src/components/quick-open-file-list.react.test.tsx @@ -10,9 +10,11 @@ import type { AppState } from '@/store/types' import { useRuntimeFileListForWorktree, type RuntimeFileListState } from './quick-open-file-list' const listRuntimeFilesMock = vi.hoisted(() => vi.fn()) +const cancelRuntimeFileListMock = vi.hoisted(() => vi.fn()) vi.mock('@/runtime/runtime-file-client', () => ({ - listRuntimeFiles: listRuntimeFilesMock + listRuntimeFiles: listRuntimeFilesMock, + cancelRuntimeFileList: cancelRuntimeFileListMock })) const initialAppState = useAppStore.getInitialState() @@ -104,6 +106,7 @@ async function renderProbe(args: { beforeEach(() => { useAppStore.setState(initialAppState, true) listRuntimeFilesMock.mockReset().mockResolvedValue(['packages/app/package.json']) + cancelRuntimeFileListMock.mockReset() }) afterEach(async () => { @@ -155,9 +158,37 @@ describe('useRuntimeFileListForWorktree', () => { }), { rootPath: '/srv/platform', - excludePaths: undefined + excludePaths: undefined, + requestToken: expect.any(String) } ) expect(states.at(-1)?.files).toEqual(['packages/app/package.json']) }) + + it('cancels the in-flight scan with the same request token on unmount (#7721)', async () => { + const workspaceKey = folderWorkspaceKey('folder-workspace-1') + + useAppStore.setState({ + folderWorkspaces: [makeFolderWorkspace({ connectionId: 'ssh-1' })], + projectGroups: [makeProjectGroup({ connectionId: 'ssh-1' })], + repos: [], + worktreesByRepo: {} + } as Partial) + + const root = await renderProbe({ + enabled: true, + onState: () => {}, + worktreeId: workspaceKey + }) + await waitForListRuntimeFilesCall() + + const [listContext, listRequest] = listRuntimeFilesMock.mock.calls[0] + expect(cancelRuntimeFileListMock).not.toHaveBeenCalled() + + await act(async () => { + root.unmount() + }) + + expect(cancelRuntimeFileListMock).toHaveBeenCalledWith(listContext, listRequest.requestToken) + }) }) diff --git a/src/renderer/src/components/quick-open-file-list.ts b/src/renderer/src/components/quick-open-file-list.ts index 9a7ffe8d5..13e3738e2 100644 --- a/src/renderer/src/components/quick-open-file-list.ts +++ b/src/renderer/src/components/quick-open-file-list.ts @@ -3,8 +3,9 @@ import { useEffect, useMemo, useRef, useState } from 'react' import type { Worktree } from '../../../shared/types' import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path' import { getConnectionIdFromState } from '@/lib/connection-context' +import { createBrowserUuid } from '@/lib/browser-uuid' import { getSettingsForWorktreeRuntimeOwner } from '@/lib/worktree-runtime-owner' -import { listRuntimeFiles } from '@/runtime/runtime-file-client' +import { cancelRuntimeFileList, listRuntimeFiles } from '@/runtime/runtime-file-client' import { useAppStore } from '@/store' import { useWorktreesForRepo } from '@/store/selectors' @@ -152,21 +153,21 @@ export function useRuntimeFileListForWorktree({ setLoading(true) const excludePaths = excludeRequest.paths.length > 0 ? excludeRequest.paths : undefined + const requestToken = createBrowserUuid() + const requestContext = { + // Why: Quick Open lists files for the selected workspace. It must + // follow that workspace's owner host, not the globally focused host. + settings: getSettingsForWorktreeRuntimeOwner(useAppStore.getState(), worktreeId), + worktreeId, + worktreePath, + connectionId + } - void listRuntimeFiles( - { - // Why: Quick Open lists files for the selected workspace. It must - // follow that workspace's owner host, not the globally focused host. - settings: getSettingsForWorktreeRuntimeOwner(useAppStore.getState(), worktreeId), - worktreeId, - worktreePath, - connectionId - }, - { - rootPath: worktreePath, - excludePaths - } - ) + void listRuntimeFiles(requestContext, { + rootPath: worktreePath, + excludePaths, + requestToken + }) .then((result) => { if (!cancelled) { setFiles(result) @@ -186,6 +187,11 @@ export function useRuntimeFileListForWorktree({ return () => { cancelled = true + // Why #7721: switching workspaces (or closing the palette) must abort + // the previous full-tree scan host- and relay-side. Over SSH, abandoned + // scans otherwise stack up and starve fs.readDir/fs.stat past their + // 30s timeout ("Could not load files for this workspace"). + cancelRuntimeFileList(requestContext, requestToken) } }, [connectionId, enabled, excludeRequest, requestKey, target.canList, worktreeId, worktreePath]) diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx index 8442e73f5..4a6bccec9 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx @@ -28,7 +28,6 @@ import { import { useAiVaultSessionLaunchActions } from './ai-vault-session-launch-actions' import { useAiVaultSessionWorktreeMap } from './ai-vault-session-worktree' import { useAiVaultOriginalPaneActions } from './ai-vault-original-pane-actions' -import { getAiVaultResumeWorkspaceTargetStatus } from '@/lib/ai-vault-resume-target' import { AI_VAULT_AGENTS, type AiVaultAgent, @@ -41,7 +40,11 @@ import { translate } from '@/i18n/i18n' import { AiVaultPanelHeader } from './AiVaultPanelHeader' import { AiVaultSessionVirtualList } from './AiVaultSessionVirtualList' import { useAiVaultSessionRefresh } from './ai-vault-session-refresh' -import { useAiVaultExecutionHostScope } from './ai-vault-host-scope' +import { + buildAiVaultHostScopeOptions, + buildRuntimeAiVaultHostScopeOptions, + useAiVaultExecutionHostScope +} from './ai-vault-host-scope' export default function AiVaultPanel(): React.JSX.Element { const activeWorktreeId = useActiveWorktreeId() @@ -59,6 +62,7 @@ export default function AiVaultPanel(): React.JSX.Element { })) ) const settings = useAppStore((s) => s.settings) + const runtimeEnvironments = useAppStore((s) => s.runtimeEnvironments) const agentCmdOverrides = settings?.agentCmdOverrides const { getOriginalPaneTarget, jumpToOriginalPane, jumpToWorktree } = useAiVaultOriginalPaneActions() @@ -72,17 +76,28 @@ export default function AiVaultPanel(): React.JSX.Element { const userChangedScopeRef = useRef(false) const preferredScopeRef = useRef(DEFAULT_AI_VAULT_SCOPE) - const isRuntimeWorktree = useMemo( - () => - getAiVaultResumeWorkspaceTargetStatus(resumeTargetState, activeWorktreeId ?? null) === - 'runtime', - [activeWorktreeId, resumeTargetState] + const runtimeHostOptions = useMemo( + () => buildRuntimeAiVaultHostScopeOptions(runtimeEnvironments), + [runtimeEnvironments] ) - const { executionHostScope, activeSshExecutionHostScope, onExecutionHostScopeChange } = + const availableExecutionHostScopes = useMemo( + () => runtimeHostOptions.map((option) => option.id), + [runtimeHostOptions] + ) + const { executionHostScope, activeExecutionHostScope, onExecutionHostScopeChange } = useAiVaultExecutionHostScope({ activeWorktreeId: activeWorktreeId ?? null, - resumeTargetState + resumeTargetState, + availableExecutionHostScopes }) + const hostScopeOptions = useMemo( + () => + buildAiVaultHostScopeOptions({ + activeExecutionHostScope, + runtimeHostOptions + }), + [activeExecutionHostScope, runtimeHostOptions] + ) const activeWorktreePath = activeWorktree?.path ?? null // Why: AI Vault ownership is cwd-based, so we must consider live worktrees across all repos. const activeWorktreePaths = useMemo( @@ -306,7 +321,7 @@ export default function AiVaultPanel(): React.JSX.Element { activeProjectKey={activeProjectKey} scope={scope} executionHostScope={executionHostScope} - activeSshExecutionHostScope={activeSshExecutionHostScope} + hostScopeOptions={hostScopeOptions} agents={agents} sort={sort} group={group} @@ -323,15 +338,6 @@ export default function AiVaultPanel(): React.JSX.Element { onRefresh={() => void refresh({ force: true })} /> - {isRuntimeWorktree ? ( -
- {translate( - 'auto.components.right.sidebar.AiVaultPanel.runtimeBrowseLocalHistory', - 'Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.' - )} -
- ) : null} - {error ? (
{error} diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx index 2b3cc2802..b64308b94 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx @@ -32,14 +32,10 @@ import { type AiVaultScope, type AiVaultSort } from '../../../../shared/ai-vault-types' -import { - ALL_EXECUTION_HOSTS_SCOPE, - getExecutionHostLabel, - LOCAL_EXECUTION_HOST_ID, - type ExecutionHostScope -} from '../../../../shared/execution-host' +import { getExecutionHostLabel, type ExecutionHostScope } from '../../../../shared/execution-host' import { agentLabel, type AiVaultSessionGroup } from './ai-vault-session-filters' import { translate } from '@/i18n/i18n' +import type { AiVaultHostScopeOption } from './ai-vault-host-scope' const VAULT_HEADER_CONTROL_CLASS = 'size-6 shrink-0' @@ -184,19 +180,15 @@ export function VaultScopeSwitch({ export function VaultHostScopeMenu({ executionHostScope, - activeSshExecutionHostScope, + hostOptions, onExecutionHostScopeChange }: { executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + hostOptions: readonly AiVaultHostScopeOption[] onExecutionHostScopeChange: (scope: ExecutionHostScope) => void }): React.JSX.Element { - const hostOptions = [ - LOCAL_EXECUTION_HOST_ID, - ...(activeSshExecutionHostScope ? [activeSshExecutionHostScope] : []), - ALL_EXECUTION_HOSTS_SCOPE - ] as const - const label = getExecutionHostLabel(executionHostScope) + const selectedOption = hostOptions.find((option) => option.id === executionHostScope) + const label = selectedOption?.label ?? getExecutionHostLabel(executionHostScope) return ( @@ -224,9 +216,9 @@ export function VaultHostScopeMenu({ value={executionHostScope} onValueChange={(value) => onExecutionHostScopeChange(value as ExecutionHostScope)} > - {hostOptions.map((scope) => ( - - {getExecutionHostLabel(scope)} + {hostOptions.map((option) => ( + + {option.label} ))} diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx index b463e188a..b3ec2ba36 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx @@ -9,6 +9,7 @@ import type { } from '../../../../shared/ai-vault-types' import type { ExecutionHostScope } from '../../../../shared/execution-host' import { VaultHostScopeMenu, VaultScopeSwitch, VaultViewMenu } from './AiVaultPanelControls' +import type { AiVaultHostScopeOption } from './ai-vault-host-scope' type AiVaultPanelHeaderProps = { query: string @@ -20,7 +21,7 @@ type AiVaultPanelHeaderProps = { activeProjectKey: string | null scope: AiVaultScope executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + hostScopeOptions: readonly AiVaultHostScopeOption[] agents: readonly AiVaultAgent[] sort: AiVaultSort group: AiVaultGroup @@ -47,7 +48,7 @@ export function AiVaultPanelHeader({ activeProjectKey, scope, executionHostScope, - activeSshExecutionHostScope, + hostScopeOptions, agents, sort, group, @@ -108,7 +109,7 @@ export function AiVaultPanelHeader({
{ expect(mocks.toastError).toHaveBeenCalledTimes(1) }) + it('keeps prompt editing available when async auto-start delivery fails', async () => { + mocks.onStart.mockImplementation(async () => { + await Promise.resolve() + return false + }) + renderControlledDialog({ + baseCommandInput: 'Resolve queued comments.', + savedCommandInputTemplate: '{basePrompt}' + }) + expect(container.textContent).not.toContain('Launch agent') + await vi.waitFor(() => expect(mocks.onStart).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(container.textContent).toContain('Launch agent')) + + expect(container.querySelector('textarea')?.value).toContain('{basePrompt}') + expect(container.textContent).toContain('Start agent') + expect(mocks.onLaunched).not.toHaveBeenCalled() + expect(mocks.onOpenChange).not.toHaveBeenCalledWith(false) + }) + it('does not auto-start when a saved receipt appears after the dialog is already open', async () => { let setSavedAgentId: (agent: TuiAgent | null) => void = () => {} diff --git a/src/renderer/src/components/right-sidebar/ai-vault-host-scope.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-host-scope.test.ts index 73af6ab91..bfd98ca51 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-host-scope.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-host-scope.test.ts @@ -5,7 +5,12 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it } from 'vitest' import type { AppState } from '@/store/types' import type { AiVaultSessionResumeTargetState } from './ai-vault-session-resume' -import { useAiVaultExecutionHostScope } from './ai-vault-host-scope' +import { + buildAiVaultHostScopeOptions, + buildRuntimeAiVaultHostScopeOptions, + useAiVaultExecutionHostScope +} from './ai-vault-host-scope' +import type { ExecutionHostScope } from '../../../../shared/execution-host' type HostScopeResult = ReturnType @@ -15,6 +20,7 @@ let latest: HostScopeResult | null = null function HookProbe(props: { activeWorktreeId: string | null resumeTargetState: AiVaultSessionResumeTargetState + availableExecutionHostScopes?: readonly ExecutionHostScope[] }): null { latest = useAiVaultExecutionHostScope(props) return null @@ -23,6 +29,7 @@ function HookProbe(props: { async function renderHook(props: { activeWorktreeId: string | null resumeTargetState: AiVaultSessionResumeTargetState + availableExecutionHostScopes?: readonly ExecutionHostScope[] }): Promise { if (!root) { const container = document.createElement('div') @@ -83,7 +90,7 @@ describe('useAiVaultExecutionHostScope', () => { }) expect(latest?.executionHostScope).toBe('ssh:dev-box') - expect(latest?.activeSshExecutionHostScope).toBe('ssh:dev-box') + expect(latest?.activeExecutionHostScope).toBe('ssh:dev-box') }) it('defaults local worktrees to local history', async () => { @@ -96,7 +103,22 @@ describe('useAiVaultExecutionHostScope', () => { }) expect(latest?.executionHostScope).toBe('local') - expect(latest?.activeSshExecutionHostScope).toBeNull() + expect(latest?.activeExecutionHostScope).toBeNull() + }) + + it('defaults runtime worktrees to their runtime execution host', async () => { + await renderHook({ + activeWorktreeId: 'repo-1::/runtime/repo', + resumeTargetState: stateForWorktree({ + worktreeId: 'repo-1::/runtime/repo', + repoId: 'repo-1', + executionHostId: 'runtime:remote-server' + }), + availableExecutionHostScopes: ['runtime:remote-server'] as const + }) + + expect(latest?.executionHostScope).toBe('runtime:remote-server') + expect(latest?.activeExecutionHostScope).toBe('runtime:remote-server') }) it('preserves manual host scope changes across unrelated rerenders', async () => { @@ -117,4 +139,56 @@ describe('useAiVaultExecutionHostScope', () => { expect(latest?.executionHostScope).toBe('all') }) + + it('preserves manual runtime host scope choices while they are still available', async () => { + const props = { + activeWorktreeId: 'repo-1::/local/repo', + resumeTargetState: stateForWorktree({ + worktreeId: 'repo-1::/local/repo', + repoId: 'repo-1' + }), + availableExecutionHostScopes: ['runtime:remote-server'] as const + } + await renderHook(props) + + await act(async () => { + latest?.onExecutionHostScopeChange('runtime:remote-server') + }) + await renderHook({ ...props, resumeTargetState: { ...props.resumeTargetState } }) + + expect(latest?.executionHostScope).toBe('runtime:remote-server') + }) +}) + +describe('buildAiVaultHostScopeOptions', () => { + it('adds saved runtime hosts between active SSH and all hosts', () => { + const runtimeHostOptions = buildRuntimeAiVaultHostScopeOptions([ + { id: 'remote-server', name: 'VPS Orca Server' } + ]) + + expect( + buildAiVaultHostScopeOptions({ + activeExecutionHostScope: 'ssh:dev-box', + runtimeHostOptions + }) + ).toEqual([ + { id: 'local', label: expect.any(String) }, + { id: 'ssh:dev-box', label: 'dev-box' }, + { id: 'runtime:remote-server', label: 'VPS Orca Server' }, + { id: 'all', label: 'All hosts' } + ]) + }) + + it('keeps a runtime active host visible even before the saved environment list hydrates', () => { + expect( + buildAiVaultHostScopeOptions({ + activeExecutionHostScope: 'runtime:remote-server', + runtimeHostOptions: [] + }) + ).toEqual([ + { id: 'local', label: expect.any(String) }, + { id: 'runtime:remote-server', label: 'remote-server' }, + { id: 'all', label: 'All hosts' } + ]) + }) }) diff --git a/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts b/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts index 8993e8a00..0acb4f546 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts @@ -2,18 +2,28 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { getAiVaultResumeWorkspaceExecutionHostId } from '@/lib/ai-vault-resume-target' import { ALL_EXECUTION_HOSTS_SCOPE, + getExecutionHostLabel, LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, + toRuntimeExecutionHostId, + type ExecutionHostId, type ExecutionHostScope } from '../../../../shared/execution-host' +import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' import type { AiVaultSessionResumeTargetState } from './ai-vault-session-resume' +export type AiVaultHostScopeOption = { + id: ExecutionHostScope + label: string +} + export function useAiVaultExecutionHostScope(args: { activeWorktreeId: string | null resumeTargetState: AiVaultSessionResumeTargetState + availableExecutionHostScopes?: readonly ExecutionHostScope[] }): { executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + activeExecutionHostScope: ExecutionHostId | null onExecutionHostScopeChange: (scope: ExecutionHostScope) => void } { const userChangedHostScopeRef = useRef(false) @@ -22,10 +32,12 @@ export function useAiVaultExecutionHostScope(args: { [args.activeWorktreeId, args.resumeTargetState] ) const activeExecutionHost = parseExecutionHostId(activeExecutionHostId) + const activeExecutionHostScope: ExecutionHostId | null = + activeExecutionHost?.kind === 'ssh' || activeExecutionHost?.kind === 'runtime' + ? activeExecutionHost.id + : null const defaultExecutionHostScope: ExecutionHostScope = - activeExecutionHost?.kind === 'ssh' ? activeExecutionHost.id : LOCAL_EXECUTION_HOST_ID - const activeSshExecutionHostScope: ExecutionHostScope | null = - activeExecutionHost?.kind === 'ssh' ? activeExecutionHost.id : null + activeExecutionHostScope ?? LOCAL_EXECUTION_HOST_ID const [executionHostScope, setExecutionHostScope] = useState(defaultExecutionHostScope) @@ -36,7 +48,8 @@ export function useAiVaultExecutionHostScope(args: { const allowedScopes = new Set([ LOCAL_EXECUTION_HOST_ID, ALL_EXECUTION_HOSTS_SCOPE, - ...(activeSshExecutionHostScope ? [activeSshExecutionHostScope] : []) + ...(activeExecutionHostScope ? [activeExecutionHostScope] : []), + ...(args.availableExecutionHostScopes ?? []) ]) if (!allowedScopes.has(executionHostScope)) { setExecutionHostScope(defaultExecutionHostScope) @@ -46,7 +59,12 @@ export function useAiVaultExecutionHostScope(args: { if (!userChangedHostScopeRef.current && executionHostScope !== defaultExecutionHostScope) { setExecutionHostScope(defaultExecutionHostScope) } - }, [activeSshExecutionHostScope, defaultExecutionHostScope, executionHostScope]) + }, [ + activeExecutionHostScope, + args.availableExecutionHostScopes, + defaultExecutionHostScope, + executionHostScope + ]) const handleExecutionHostScopeChange = useCallback( (nextScope: ExecutionHostScope) => { @@ -58,7 +76,49 @@ export function useAiVaultExecutionHostScope(args: { return { executionHostScope, - activeSshExecutionHostScope, + activeExecutionHostScope, onExecutionHostScopeChange: handleExecutionHostScopeChange } } + +export function buildRuntimeAiVaultHostScopeOptions( + runtimeEnvironments: readonly Pick[] +): AiVaultHostScopeOption[] { + return runtimeEnvironments.map((environment) => { + const id = toRuntimeExecutionHostId(environment.id) + const label = environment.name.trim() || getExecutionHostLabel(id) + return { id, label } + }) +} + +export function buildAiVaultHostScopeOptions(args: { + activeExecutionHostScope: ExecutionHostId | null + runtimeHostOptions: readonly AiVaultHostScopeOption[] +}): AiVaultHostScopeOption[] { + const options: AiVaultHostScopeOption[] = [] + const seen = new Set() + const add = (option: AiVaultHostScopeOption): void => { + if (seen.has(option.id)) { + return + } + seen.add(option.id) + options.push(option) + } + const activeHost = args.activeExecutionHostScope + ? parseExecutionHostId(args.activeExecutionHostScope) + : null + + add({ id: LOCAL_EXECUTION_HOST_ID, label: getExecutionHostLabel(LOCAL_EXECUTION_HOST_ID) }) + if (activeHost?.kind === 'ssh') { + add({ id: activeHost.id, label: getExecutionHostLabel(activeHost.id) }) + } + for (const option of args.runtimeHostOptions) { + add(option) + } + if (activeHost?.kind === 'runtime') { + add({ id: activeHost.id, label: getExecutionHostLabel(activeHost.id) }) + } + add({ id: ALL_EXECUTION_HOSTS_SCOPE, label: getExecutionHostLabel(ALL_EXECUTION_HOSTS_SCOPE) }) + + return options +} diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts index c55acb1e9..78daad963 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts @@ -100,21 +100,40 @@ export function useAiVaultSessionLaunchActions({ return } - launchAiVaultSessionInNewTab({ + const launchResult = launchAiVaultSessionInNewTab({ agent: session.agent, worktreeId: targetId.worktreeId, ...buildResumeStartup(session, targetId.worktreeId) }) + const showQueuedToast = (): void => { + toast.success( + translate( + 'auto.components.right.sidebar.AiVaultPanel.agentSessionQueued', + '{{value0}} session queued', + { value0: agentLabel(session.agent) } + ) + ) + } + if (launchResult.tabId === null) { + void launchResult.runtimeLaunch.then((created) => { + if (!created) { + toast.error( + translate( + 'auto.lib.launch.agent.in.new.tab.11cce5cc77', + 'Could not launch {{value0}} in a new terminal.', + { value0: agentLabel(session.agent) } + ) + ) + return + } + showQueuedToast() + }) + return + } if (useAppStore.getState().activeWorktreeId !== targetId.worktreeId) { activateAiVaultResumeWorkspace(targetId.worktreeId) } - toast.success( - translate( - 'auto.components.right.sidebar.AiVaultPanel.agentSessionQueued', - '{{value0}} session queued', - { value0: agentLabel(session.agent) } - ) - ) + showQueuedToast() }, [activeWorktree?.id, activeWorktreeId, buildResumeStartup, targetState] ) @@ -167,15 +186,9 @@ export function resolveAiVaultSessionLaunchTarget(args: { function aiVaultResumeUnsupportedMessage( targetStatus: ReturnType ): string { - if (targetStatus === 'runtime') { - return translate( - 'auto.components.right.sidebar.AiVaultPanel.runtimeWorkspacesUnsupported', - 'Resume from history is not available in runtime-hosted workspaces.' - ) - } // Why: local and SSH targets can both be valid generally; this branch means // the session's recorded host does not match the selected workspace. - if (targetStatus === 'ssh' || targetStatus === 'local') { + if (targetStatus === 'ssh' || targetStatus === 'local' || targetStatus === 'runtime') { return translate( 'auto.components.right.sidebar.AiVaultPanel.sessionHostMismatchUnsupported', 'This session belongs to a different host. Open a workspace on the same host to resume it.' @@ -183,7 +196,7 @@ function aiVaultResumeUnsupportedMessage( } return translate( 'auto.components.right.sidebar.AiVaultPanel.openSupportedWorkspace', - 'Open a local or SSH workspace before resuming a session.' + 'Open a workspace before resuming a session.' ) } diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts index 5e8bc3f42..381b1d49c 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts @@ -194,10 +194,33 @@ describe('resolveAiVaultSessionResumeState', () => { }) }) - it('blocks runtime-owned targets even when they have no SSH connection', () => { + it('allows runtime-owned targets for matching runtime sessions', () => { expect( resolveAiVaultSessionResumeState({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', + worktreeInfo: makeWorktreeInfo('active'), + activeWorktreeId: null, + worktrees: [makeWorktree()], + repos: [ + makeRepo({ + connectionId: null, + executionHostId: 'runtime:env-1' + }) + ] + }) + ).toEqual({ + blocked: false, + worktreeId: 'repo-1::/repo/orca', + usesSessionWorktree: true + }) + }) + + it('blocks runtime-owned targets for sessions from another host', () => { + expect( + resolveAiVaultSessionResumeState({ + sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'local', worktreeInfo: makeWorktreeInfo('active'), activeWorktreeId: null, worktrees: [makeWorktree()], @@ -215,19 +238,20 @@ describe('resolveAiVaultSessionResumeState', () => { }) }) - it('blocks runtime-stamped worktrees even when the repo owner is local', () => { + it('allows runtime-stamped worktrees even when the repo owner is local', () => { expect( resolveAiVaultSessionResumeState({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', worktreeInfo: makeWorktreeInfo('active'), activeWorktreeId: null, worktrees: [makeWorktree({ hostId: 'runtime:env-1' })], repos: [makeRepo({ connectionId: null, executionHostId: 'local' })] }) ).toEqual({ - blocked: true, - worktreeId: null, - usesSessionWorktree: false + blocked: false, + worktreeId: 'repo-1::/repo/orca', + usesSessionWorktree: true }) }) @@ -319,10 +343,11 @@ describe('resolveAiVaultSessionResumeState', () => { }) }) - it('blocks an active runtime folder workspace', () => { + it('allows an active runtime folder workspace for matching runtime sessions', () => { expect( resolveAiVaultSessionResumeState({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', worktreeInfo: makeWorktreeInfo('archived'), activeWorktreeId: folderWorkspaceKey('folder-1'), worktrees: [], @@ -330,8 +355,8 @@ describe('resolveAiVaultSessionResumeState', () => { targetState: makeFolderTargetState({ id: 'group-1', executionHostId: 'runtime:env-1' }) }) ).toEqual({ - blocked: true, - worktreeId: null, + blocked: false, + worktreeId: folderWorkspaceKey('folder-1'), usesSessionWorktree: false }) }) @@ -461,10 +486,11 @@ describe('resolveAiVaultSessionResumeActions', () => { }) }) - it('disables the active folder workspace action when it is runtime-owned', () => { + it('enables the active folder workspace action when it is a matching runtime host', () => { expect( resolveAiVaultSessionResumeActions({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', worktreeInfo: makeWorktreeInfo('archived'), activeWorktreeId: folderWorkspaceKey('folder-1'), worktrees: [], @@ -473,7 +499,7 @@ describe('resolveAiVaultSessionResumeActions', () => { }) ).toEqual({ worktree: { worktreeId: null, disabled: true }, - newTab: { worktreeId: folderWorkspaceKey('folder-1'), disabled: true } + newTab: { worktreeId: folderWorkspaceKey('folder-1'), disabled: false } }) }) }) @@ -505,10 +531,25 @@ describe('resolveAiVaultSessionLaunchTarget', () => { }) }) - it('blocks direct resume into a runtime folder workspace', () => { + it('allows direct resume into a matching runtime folder workspace', () => { expect( resolveAiVaultSessionLaunchTarget({ sessionFilePath: WSL_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', + activeWorktreeId: folderWorkspaceKey('folder-1'), + targetState: makeFolderTargetState({ id: 'group-1', executionHostId: 'runtime:env-1' }) + }) + ).toEqual({ + status: 'ready', + worktreeId: folderWorkspaceKey('folder-1') + }) + }) + + it('blocks direct resume into a mismatched runtime folder workspace', () => { + expect( + resolveAiVaultSessionLaunchTarget({ + sessionFilePath: WSL_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-2', activeWorktreeId: folderWorkspaceKey('folder-1'), targetState: makeFolderTargetState({ id: 'group-1', executionHostId: 'runtime:env-1' }) }) diff --git a/src/renderer/src/components/right-sidebar/pr-comments-list-selection.test.tsx b/src/renderer/src/components/right-sidebar/pr-comments-list-selection.test.tsx index 619244941..ec89aa872 100644 --- a/src/renderer/src/components/right-sidebar/pr-comments-list-selection.test.tsx +++ b/src/renderer/src/components/right-sidebar/pr-comments-list-selection.test.tsx @@ -326,6 +326,18 @@ describe('PRCommentsList comment resolution selection', () => { expect(container.querySelector('button[role="checkbox"]')).toBeNull() }) + it('keeps queued comments selected when clearRequest is null', () => { + const comments = [comment({ id: 1, threadId: 'thread-1', path: 'src/a.ts', isResolved: false })] + renderList({ comments }) + clickButton('Queue for agent') + + expect(hasButton('Send 1 queued comments to AI')).toBe(true) + + renderList({ comments, clearRequest: null }) + + expect(hasButton('Send 1 queued comments to AI')).toBe(true) + }) + it('keeps a clear request pending until its review context is mounted', () => { const queuedComments = [ comment({ diff --git a/src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.test.ts b/src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.test.ts new file mode 100644 index 000000000..345f1b6a0 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.test.ts @@ -0,0 +1,171 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + focusTerminalTabSurface: vi.fn(), + launchAgentInNewTab: vi.fn(), + onClose: vi.fn(), + onLaunched: vi.fn(), + onSaveAgentDefault: vi.fn(), + onStart: vi.fn(), + toastError: vi.fn() +})) + +vi.mock('@/lib/focus-terminal-tab-surface', () => ({ + focusTerminalTabSurface: mocks.focusTerminalTabSurface +})) + +vi.mock('@/lib/launch-agent-in-new-tab', () => ({ + launchAgentInNewTab: mocks.launchAgentInNewTab +})) + +vi.mock('sonner', () => ({ + toast: { error: mocks.toastError } +})) + +import { runSourceControlAgentActionStart } from './runSourceControlAgentActionStart' + +function buildArgs( + overrides: Partial[0]> = {} +): Parameters[0] { + return { + selectedAgent: 'codex', + trimmedCommandInput: 'Fix the bug', + agentArgs: '--model gpt-5', + commandTemplate: '{basePrompt}', + saveTargetValue: 'none', + actionId: 'resolveComments', + repoId: null, + settings: null, + repo: null, + worktreeId: 'wt-1', + groupId: 'group-1', + promptDelivery: 'submit-after-ready', + launchPlatform: 'linux', + launchSource: 'source_control_recovery', + onStart: undefined, + onSaveAgentDefault: mocks.onSaveAgentDefault, + onLaunched: mocks.onLaunched, + onClose: mocks.onClose, + ...overrides + } +} + +describe('runSourceControlAgentActionStart', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('waits for deferred prompt delivery before confirming a source-control launch', async () => { + mocks.launchAgentInNewTab.mockReturnValue({ + tabId: 'tab-1', + startupPlan: {} as never, + pasteDraftAfterLaunch: true, + promptDeliveryResult: Promise.resolve({ delivered: true, failureNotified: false }) + }) + + await expect(runSourceControlAgentActionStart(buildArgs())).resolves.toBe(true) + + expect(mocks.focusTerminalTabSurface).toHaveBeenCalledWith('tab-1') + expect(mocks.onLaunched).toHaveBeenCalledTimes(1) + expect(mocks.onClose).toHaveBeenCalledTimes(1) + expect(mocks.toastError).not.toHaveBeenCalled() + }) + + it('keeps the source-control dialog open when deferred prompt delivery fails', async () => { + mocks.launchAgentInNewTab.mockReturnValue({ + tabId: 'tab-1', + startupPlan: {} as never, + pasteDraftAfterLaunch: true, + promptDeliveryResult: Promise.resolve({ delivered: false, failureNotified: false }) + }) + + await expect(runSourceControlAgentActionStart(buildArgs())).resolves.toBe(false) + + expect(mocks.focusTerminalTabSurface).toHaveBeenCalledWith('tab-1') + expect(mocks.onLaunched).not.toHaveBeenCalled() + expect(mocks.onClose).not.toHaveBeenCalled() + expect(mocks.onSaveAgentDefault).not.toHaveBeenCalled() + expect(mocks.toastError).toHaveBeenCalledWith('Could not start the selected agent.') + }) + + it('does not show a generic start failure when deferred delivery already notified the user', async () => { + mocks.launchAgentInNewTab.mockReturnValue({ + tabId: 'tab-1', + startupPlan: {} as never, + pasteDraftAfterLaunch: true, + promptDeliveryResult: Promise.resolve({ delivered: false, failureNotified: true }) + }) + + await expect(runSourceControlAgentActionStart(buildArgs())).resolves.toBe(false) + + expect(mocks.focusTerminalTabSurface).toHaveBeenCalledWith('tab-1') + expect(mocks.onLaunched).not.toHaveBeenCalled() + expect(mocks.onClose).not.toHaveBeenCalled() + expect(mocks.toastError).not.toHaveBeenCalled() + }) + + it('logs and treats a rejected promptDeliveryResult as a launch failure', async () => { + const error = new Error('boom') + const originalConsole = console + const consoleError = vi.fn() + vi.stubGlobal('console', { ...originalConsole, error: consoleError }) + mocks.launchAgentInNewTab.mockReturnValue({ + tabId: 'tab-1', + startupPlan: {} as never, + pasteDraftAfterLaunch: true, + promptDeliveryResult: Promise.reject(error) + }) + + try { + await expect(runSourceControlAgentActionStart(buildArgs())).resolves.toBe(false) + + expect(mocks.focusTerminalTabSurface).toHaveBeenCalledWith('tab-1') + expect(consoleError).toHaveBeenCalledWith('promptDeliveryResult rejected', error) + expect(mocks.onLaunched).not.toHaveBeenCalled() + expect(mocks.onClose).not.toHaveBeenCalled() + expect(mocks.toastError).toHaveBeenCalledWith('Could not start the selected agent.') + } finally { + vi.stubGlobal('console', originalConsole) + } + }) + + it('keeps non-deferred tab launches immediate', async () => { + mocks.launchAgentInNewTab.mockReturnValue({ + tabId: 'tab-1', + startupPlan: {} as never, + pasteDraftAfterLaunch: true + }) + + await expect( + runSourceControlAgentActionStart(buildArgs({ promptDelivery: 'draft' })) + ).resolves.toBe(true) + + expect(mocks.focusTerminalTabSurface).toHaveBeenCalledWith('tab-1') + expect(mocks.onLaunched).toHaveBeenCalledTimes(1) + expect(mocks.onClose).toHaveBeenCalledTimes(1) + expect(mocks.toastError).not.toHaveBeenCalled() + }) + + it('keeps injected onStart successes immediate', async () => { + const onStart = vi.fn().mockResolvedValue(true) + + await expect( + runSourceControlAgentActionStart( + buildArgs({ + onStart, + worktreeId: undefined, + groupId: undefined + }) + ) + ).resolves.toBe(true) + + expect(onStart).toHaveBeenCalledWith({ + agent: 'codex', + commandInput: 'Fix the bug', + agentArgs: '--model gpt-5' + }) + expect(mocks.launchAgentInNewTab).not.toHaveBeenCalled() + expect(mocks.onLaunched).toHaveBeenCalledTimes(1) + expect(mocks.onClose).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.ts b/src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.ts index f180cc56d..ee6c24e32 100644 --- a/src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.ts +++ b/src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.ts @@ -62,6 +62,7 @@ export async function runSourceControlAgentActionStart({ onClose }: RunSourceControlAgentActionStartArgs): Promise { let launched = false + let launchFailureNotified = false if (onStart) { launched = await onStart({ agent: selectedAgent, @@ -83,14 +84,26 @@ export async function runSourceControlAgentActionStart({ if (result?.tabId) { focusTerminalTabSurface(result.tabId) } + if (result?.promptDeliveryResult) { + try { + const deliveryResult = await result.promptDeliveryResult + launched = deliveryResult.delivered + launchFailureNotified = deliveryResult.failureNotified + } catch (error) { + console.error('promptDeliveryResult rejected', error) + launched = false + } + } } if (!launched) { - toast.error( - translate( - 'auto.components.right.sidebar.SourceControlAgentActionDialog.8e856842d1', - 'Could not start the selected agent.' + if (!launchFailureNotified) { + toast.error( + translate( + 'auto.components.right.sidebar.SourceControlAgentActionDialog.8e856842d1', + 'Could not start the selected agent.' + ) ) - ) + } return false } diff --git a/src/renderer/src/components/settings/MobileSettingsPane.tsx b/src/renderer/src/components/settings/MobileSettingsPane.tsx index 6e7513fc9..294babb62 100644 --- a/src/renderer/src/components/settings/MobileSettingsPane.tsx +++ b/src/renderer/src/components/settings/MobileSettingsPane.tsx @@ -12,7 +12,7 @@ export { getMobileSettingsPaneSearchEntries } const ORCA_IOS_APP_STORE_URL = 'https://apps.apple.com/app/orca-ide/id6766130217' const ORCA_ANDROID_APK_URL = - 'https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk' + 'https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk' export function MobileSettingsPane(): React.JSX.Element { const showMobileButton = useAppStore((s) => s.settings?.showMobileButton !== false) diff --git a/src/renderer/src/components/settings/SshPane.tsx b/src/renderer/src/components/settings/SshPane.tsx index 1af4ba26f..534383be3 100644 --- a/src/renderer/src/components/settings/SshPane.tsx +++ b/src/renderer/src/components/settings/SshPane.tsx @@ -12,6 +12,10 @@ import { SshTargetDestructiveActions } from './SshTargetDestructiveActions' import { SshTargetForm, EMPTY_FORM, type EditingTarget } from './SshTargetForm' import { getEditingTargetForSshTarget } from './ssh-target-draft' import { buildSshTargetSavePayload } from './ssh-target-save-payload' +import { HostRemoveDialog } from '../sidebar/HostRemoveDialog' +import { resolveSshHostRemoval } from '../sidebar/ssh-host-remove-resolution' +import { getAllWorktreesFromState } from '@/store/selectors' +import { toSshExecutionHostId } from '../../../../shared/execution-host' import { translate } from '@/i18n/i18n' export { getSshPaneSearchEntries } from './ssh-search' @@ -28,6 +32,14 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element { const [editingId, setEditingId] = useState(null) const [form, setForm] = useState(EMPTY_FORM) const [testingIds, setTestingIds] = useState>(new Set()) + // Why: when a target still has workspaces, route removal through the shared + // workspace-aware HostRemoveDialog (same as the sidebar) instead of the plain + // confirm, so the user chooses to delete or keep them rather than silently + // orphaning them. + const [hostRemoveTarget, setHostRemoveTarget] = useState<{ + targetId: string + label: string + } | null>(null) const mountedRef = useMountedRef() const setSshTargetsMetadata = useAppStore((s) => s.setSshTargetsMetadata) @@ -122,6 +134,25 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element { } } + // Route removal through the workspace-aware dialog when the target still owns + // workspaces; otherwise use the plain confirm (which also ends remote PTYs). + const requestRemoveTarget = ( + target: { id: string; label: string }, + requestPlainRemove: (target: { id: string; label: string }) => void + ): void => { + const resolution = resolveSshHostRemoval({ + targetId: target.id, + repos: useAppStore.getState().repos, + worktrees: getAllWorktreesFromState(useAppStore.getState()), + sshConnectionStates: useAppStore.getState().sshConnectionStates + }) + if (resolution.workspaceCount > 0) { + setHostRemoveTarget({ targetId: target.id, label: target.label }) + return + } + requestPlainRemove(target) + } + const handleRemove = async (id: string): Promise => { try { await removeSshTargetWithBestEffortCleanup(window.api.ssh, id) @@ -366,7 +397,9 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element { onResetRelay={(id) => requestResetRelay({ id, label: target.label })} onTest={handleTest} onEdit={handleEdit} - onRemove={(id) => requestRemove({ id, label: target.label })} + onRemove={(id) => + requestRemoveTarget({ id, label: target.label }, requestRemove) + } /> ))}
@@ -385,6 +418,21 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element { )} + + {hostRemoveTarget ? ( + { + if (!open) { + setHostRemoveTarget(null) + void loadTargets() + } + }} + hostId={toSshExecutionHostId(hostRemoveTarget.targetId)} + label={hostRemoveTarget.label} + target={{ kind: 'ssh', targetId: hostRemoveTarget.targetId }} + /> + ) : null}
) } diff --git a/src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.tsx b/src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.tsx new file mode 100644 index 000000000..b8067195b --- /dev/null +++ b/src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.tsx @@ -0,0 +1,195 @@ +import { useState } from 'react' +import { toast } from 'sonner' +import { Loader2, Server, ServerOff } from 'lucide-react' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { useMountedRef } from '@/hooks/useMountedRef' +import { useAppStore } from '@/store' +import { translate } from '@/i18n/i18n' +import { runWorktreeDeleteWithToast } from './delete-worktree-flow' +import type { SshWorkspaceForgetResolution } from './ssh-workspace-forget-resolution' + +type ForgetSshWorkspaceModalData = { + worktreeId: string + displayName: string + resolution: SshWorkspaceForgetResolution +} + +function isForgetModalData(data: unknown): data is ForgetSshWorkspaceModalData { + if (!data || typeof data !== 'object') { + return false + } + const candidate = data as Partial + return typeof candidate.worktreeId === 'string' && candidate.resolution != null +} + +export function ForgetSshWorkspaceDialog(): React.JSX.Element | null { + const modalData = useAppStore((s) => s.modalData) + const closeModal = useAppStore((s) => s.closeModal) + const hostLabel = useAppStore((s) => { + const resolution = isForgetModalData(s.modalData) ? s.modalData.resolution : null + const targetId = resolution && resolution.kind !== 'not-ssh' ? resolution.targetId : undefined + if (!targetId) { + return '' + } + // Prefer the live label, then the removed target's last known label (ghost + // host), then the raw id as a last resort. + return s.sshTargetLabels.get(targetId) ?? s.removedSshTargetLabels.get(targetId) ?? targetId + }) + const [busy, setBusy] = useState(null) + const mountedRef = useMountedRef() + + if (!isForgetModalData(modalData)) { + return null + } + const { worktreeId, displayName, resolution } = modalData + const canReconnect = resolution.kind === 'disconnected' + + const done = (): void => { + if (mountedRef.current) { + setBusy(null) + closeModal() + } + } + + // Reconnect the SSH target, then run the normal remote worktree removal. + const handleReconnectAndDelete = async (): Promise => { + if (resolution.kind !== 'disconnected') { + return + } + setBusy('reconnect') + try { + await window.api.ssh.connect({ targetId: resolution.targetId }) + } catch (err) { + if (mountedRef.current) { + setBusy(null) + } + toast.error( + err instanceof Error + ? err.message + : translate( + 'auto.components.sidebar.ForgetSshWorkspaceDialog.reconnectFailed', + 'Reconnection failed' + ) + ) + return + } + // Close before the delete toast fires so the two don't overlap. + closeModal() + void runWorktreeDeleteWithToast(worktreeId, displayName) + if (mountedRef.current) { + setBusy(null) + } + } + + // Remove Orca's records only — never touches remote files, worktrees, or branches. + const handleForget = async (): Promise => { + setBusy('forget') + try { + const result = await useAppStore + .getState() + .removeWorktree(worktreeId, false, { mode: 'forget-local' }) + if (!result.ok) { + toast.error(result.error) + if (mountedRef.current) { + setBusy(null) + } + return + } + done() + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)) + if (mountedRef.current) { + setBusy(null) + } + } + } + + const forgetDescription = translate( + 'auto.components.sidebar.ForgetSshWorkspaceDialog.forgetBody', + 'Removes this workspace from Orca only. Files, the Git worktree, and branches on {{host}} are left untouched.', + { host: hostLabel } + ) + + return ( + (!open ? closeModal() : undefined)}> + + + + + {translate( + 'auto.components.sidebar.ForgetSshWorkspaceDialog.title', + 'Delete “{{name}}”?', + { + name: displayName + } + )} + + + {canReconnect + ? translate( + 'auto.components.sidebar.ForgetSshWorkspaceDialog.disconnectedBody', + 'The SSH host for this workspace is not connected. Reconnect to delete it on the remote too, or remove it from Orca only.' + ) + : translate( + 'auto.components.sidebar.ForgetSshWorkspaceDialog.ghostBody', + '{{host}} is no longer a saved SSH host, so this workspace is no longer connected to a live host. It can only be removed from Orca — files and branches on the remote are left untouched.', + { host: hostLabel } + )} + + + +
+ + {hostLabel} +
+ + {/* Why: the ghost-host description already states files are untouched, so + only repeat the reassurance on the reconnect (disconnected) path. */} + {canReconnect ? ( +

{forgetDescription}

+ ) : null} + + + + + {canReconnect ? ( + + ) : null} + +
+
+ ) +} + +export default ForgetSshWorkspaceDialog diff --git a/src/renderer/src/components/sidebar/HostRemoveDialog.tsx b/src/renderer/src/components/sidebar/HostRemoveDialog.tsx index 97592d73f..97135f97e 100644 --- a/src/renderer/src/components/sidebar/HostRemoveDialog.tsx +++ b/src/renderer/src/components/sidebar/HostRemoveDialog.tsx @@ -1,6 +1,7 @@ -import React, { useState } from 'react' -import { Loader2 } from 'lucide-react' +import React, { useMemo, useState } from 'react' +import { ChevronDown, Loader2 } from 'lucide-react' import { toast } from 'sonner' +import { cn } from '@/lib/utils' import { Dialog, DialogContent, @@ -12,12 +13,14 @@ import { import { Button } from '@/components/ui/button' import { useMountedRef } from '@/hooks/useMountedRef' import { useAppStore } from '@/store' +import { getAllWorktreesFromState } from '@/store/selectors' import { translate } from '@/i18n/i18n' import type { ExecutionHostId } from '../../../../shared/execution-host' -import { parseExecutionHostId } from '../../../../shared/execution-host' import { removeSshTargetWithBestEffortCleanup } from '../settings/ssh-target-remove' import { clearHostRename } from './host-rename-remove' import type { HostRemovalTarget } from './host-rename-remove' +import { resolveSshHostRemoval } from './ssh-host-remove-resolution' +import { clearSshHostWorkspaces } from './ssh-host-remove-workspaces' type HostRemoveDialogProps = { open: boolean @@ -35,8 +38,35 @@ export function HostRemoveDialog({ target }: HostRemoveDialogProps): React.JSX.Element { const [busy, setBusy] = useState(false) + // Why: removing the host only (keeping workspaces) is the safe, reversible + // default. Deleting the remote workspaces is destructive, so it lives behind + // an Advanced disclosure and must be opted into explicitly. + const [advancedOpen, setAdvancedOpen] = useState(false) + const [deleteWorkspaces, setDeleteWorkspaces] = useState(false) const mountedRef = useMountedRef() + const repos = useAppStore((s) => s.repos) + const worktreesByRepo = useAppStore((s) => s.worktreesByRepo) + const sshConnectionStates = useAppStore((s) => s.sshConnectionStates) + + // Resolve which workspaces live on the target so the dialog can offer to + // delete/forget them alongside the host. + const sshResolution = useMemo(() => { + if (target.kind !== 'ssh') { + return null + } + return resolveSshHostRemoval({ + targetId: target.targetId, + repos, + worktrees: getAllWorktreesFromState({ worktreesByRepo }), + sshConnectionStates + }) + }, [target, repos, worktreesByRepo, sshConnectionStates]) + + const workspaceCount = sshResolution?.workspaceCount ?? 0 + const hasWorkspaces = workspaceCount > 0 + const isConnected = sshResolution?.isConnected ?? false + // Why: dropping a host should also drop its now-orphaned label override so a // future host reusing the same id doesn't inherit a stale rename. const dropOverridesForHost = (): void => { @@ -46,7 +76,7 @@ export function HostRemoveDialog({ }) } - const handleRemoveSsh = async (targetId: string): Promise => { + const removeSshTarget = async (targetId: string): Promise => { await removeSshTargetWithBestEffortCleanup(window.api.ssh, targetId) // Why: clear deferred reconnect metadata so focused SSH tabs stop retrying // the deleted target — mirrors the SSH settings pane removal flow. @@ -64,14 +94,37 @@ export function HostRemoveDialog({ onOpenChange(false) } - const confirm = async (): Promise => { - if (target.kind === 'runtime') { - handleRemoveRuntime(target.environmentId) + const runSshRemoval = async (): Promise => { + if (target.kind !== 'ssh') { return } setBusy(true) try { - await handleRemoveSsh(target.targetId) + if (deleteWorkspaces && sshResolution) { + // Connected → real remote removal; offline/ghost → local forget. + const { failedIds } = await clearSshHostWorkspaces( + sshResolution, + isConnected ? 'delete-remote' : 'forget-local' + ) + // Why: don't remove the SSH target (and report success) while some of its + // workspaces failed to clear — that would strand ghost rows behind a + // now-gone host. Surface the failure and keep the target so the user can + // retry or resolve the blocking workspace first. + if (failedIds.length > 0) { + if (mountedRef.current) { + setBusy(false) + } + toast.error( + translate( + 'auto.components.sidebar.HostRemoveDialog.workspacesFailed', + 'Could not remove {{count}} of this host’s workspaces. The host was kept so you can retry.', + { count: failedIds.length } + ) + ) + return + } + } + await removeSshTarget(target.targetId) if (mountedRef.current) { onOpenChange(false) } @@ -96,7 +149,47 @@ export function HostRemoveDialog({ } } - const isRuntime = parseExecutionHostId(hostId)?.kind === 'runtime' + const workspaceCountLabel = + workspaceCount === 1 + ? translate('auto.components.sidebar.HostRemoveDialog.oneWorkspace', '1 workspace') + : translate( + 'auto.components.sidebar.HostRemoveDialog.manyWorkspaces', + '{{count}} workspaces', + { + count: workspaceCount + } + ) + + const description = + target.kind === 'runtime' + ? translate( + 'auto.components.sidebar.HostRemoveDialog.4d5e6f7a8b', + 'This opens the Orca servers settings where you can remove this server.' + ) + : hasWorkspaces + ? translate( + 'auto.components.sidebar.HostRemoveDialog.hostHasWorkspacesDefault', + 'Removes {{value0}} and its credentials from this computer. Its {{value1}} stay in Orca — remote files are not touched.', + { value0: label, value1: workspaceCountLabel } + ) + : translate( + 'auto.components.sidebar.HostRemoveDialog.5e6f7a8b9c', + 'This removes the saved SSH host and its credentials from this computer. Remote files are not deleted.' + ) + + // The destructive opt-in wording depends on whether we delete remote files or + // only forget Orca's records (offline/ghost host). + const deleteOptionLabel = isConnected + ? translate( + 'auto.components.sidebar.HostRemoveDialog.alsoDeleteRemote', + 'Also delete these {{value0}} on {{value1}}', + { value0: workspaceCountLabel, value1: label } + ) + : translate( + 'auto.components.sidebar.HostRemoveDialog.alsoForgetLocal', + 'Also remove these {{value0}} from Orca', + { value0: workspaceCountLabel } + ) return ( @@ -111,33 +204,106 @@ export function HostRemoveDialog({ } )} - - {isRuntime - ? translate( - 'auto.components.sidebar.HostRemoveDialog.4d5e6f7a8b', - 'This opens the Orca servers settings where you can remove this server.' - ) - : translate( - 'auto.components.sidebar.HostRemoveDialog.5e6f7a8b9c', - 'This removes the saved SSH host and its credentials from this computer. Remote files are not deleted.' - )} - + {description} - - + + {/* Advanced disclosure: deleting the host's workspaces is destructive, so + it's opt-in and hidden by default. Only shown when there are any. + Matches the New Workspace composer's Advanced header + switch. */} + {target.kind === 'ssh' && hasWorkspaces ? ( +
+ +
+
+
+ + + {deleteOptionLabel} + + {isConnected + ? translate( + 'auto.components.sidebar.HostRemoveDialog.alsoDeleteRemoteHint', + 'Permanently deletes the remote Git worktrees and their branches. Cannot be undone.' + ) + : translate( + 'auto.components.sidebar.HostRemoveDialog.alsoForgetLocalHint', + 'Clears them from Orca only. Remote files, worktrees, and branches are left untouched.' + )} + + +
+
+
+
+ ) : null} + + + {target.kind === 'runtime' ? ( + + ) : ( + + )}
diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx index 8e37ecf0a..376ead35e 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx @@ -21,6 +21,22 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { const repoId = typeof modalData.repoId === 'string' ? modalData.repoId : '' const displayName = typeof modalData.displayName === 'string' ? modalData.displayName : '' + // Why: for an SSH project the files live on the remote host's disk, not the + // user's — "still on your disk" would be misleading. Name the host (using the + // removed-target label when it's a ghost) so the user knows where it remains + // and that re-adding that host recovers it. + const sshHostLabel = useAppStore((s) => { + const connectionId = s.repos.find((r) => r.id === repoId)?.connectionId?.trim() + if (!connectionId) { + return null + } + return ( + s.sshTargetLabels.get(connectionId) ?? + s.removedSshTargetLabels.get(connectionId) ?? + connectionId + ) + }) + const handleConfirm = useCallback(() => { if (repoId) { void removeProject(repoId) @@ -50,10 +66,16 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { 'This only removes' )}{' '} {displayName}{' '} - {translate( - 'auto.components.sidebar.RemoveFolderDialog.8c097ef04e', - 'from Orca. It is still on your disk.' - )} + {sshHostLabel + ? translate( + 'auto.components.sidebar.RemoveFolderDialog.fromOrcaSsh', + 'from Orca. Its files stay on {{value0}} — re-add that SSH host to recover it.', + { value0: sshHostLabel } + ) + : translate( + 'auto.components.sidebar.RemoveFolderDialog.8c097ef04e', + 'from Orca. It is still on your disk.' + )} diff --git a/src/renderer/src/components/sidebar/delete-worktree-flow.ts b/src/renderer/src/components/sidebar/delete-worktree-flow.ts index dc81f9a22..cac60ca37 100644 --- a/src/renderer/src/components/sidebar/delete-worktree-flow.ts +++ b/src/renderer/src/components/sidebar/delete-worktree-flow.ts @@ -5,6 +5,8 @@ import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { prepareActiveWorktreeFocusAfterDelete } from './active-worktree-focus-after-delete' import { showDeleteWorktreeFailureToast } from './delete-worktree-failure-toast' import { getWorkspaceDeleteLineage } from './workspace-delete-lineage' +import { resolveSshWorkspaceForget } from './ssh-workspace-forget-resolution' +import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' import { isPathInsideOrEqual, normalizeRuntimePathForComparison @@ -249,6 +251,39 @@ export function runWorktreeDelete(worktreeId: string): void { return } state.clearWorktreeDeleteState(worktreeId) + + // Why: a workspace on a removed/disconnected SSH host cannot go through the + // normal remote removal — its provider is gone, so worktrees:remove throws + // before any cleanup. Route to a dialog that offers reconnect-and-delete + // (when the target still exists) or a local-only forget. + // + // Skip this on paired web/mobile clients: SSH targets/labels/connection state + // are desktop-only, so those clients have empty sshTargetLabels and would + // misclassify every SSH repo as a ghost, routing to a forget dialog whose + // local-only backend is unavailable there. Their normal worktree.rm RPC path + // already handles the delete against the desktop runtime. + const repo = state.repos.find((entry) => entry.id === target.repoId) ?? null + const sshResolution = isPairedWebClientWindow() + ? { kind: 'not-ssh' as const } + : resolveSshWorkspaceForget({ + repo, + sshConnectionStates: state.sshConnectionStates, + sshTargetLabels: state.sshTargetLabels + }) + if (sshResolution.kind === 'ghost' || sshResolution.kind === 'disconnected') { + // Why no lineage-children warning here (unlike the normal path below): + // forget-local is metadata-only and per-worktree, so it can't fail on a + // still-registered child the way a remote git removal would. Any descendants + // live on the same ghost host and remain independently visible/forgettable — + // they are not orphaned unrecoverably. + state.openModal('forget-ssh-workspace', { + worktreeId, + displayName: target.displayName, + resolution: sshResolution + }) + return + } + const hasLineageChildren = getWorkspaceDeleteLineage(target, state.allWorktrees(), state.worktreeLineageById).descendants .length > 0 diff --git a/src/renderer/src/components/sidebar/index.tsx b/src/renderer/src/components/sidebar/index.tsx index 577eaa929..b224e5942 100644 --- a/src/renderer/src/components/sidebar/index.tsx +++ b/src/renderer/src/components/sidebar/index.tsx @@ -21,6 +21,7 @@ const WorktreeMetaDialog = lazyWithRetry(() => import('./WorktreeMetaDialog')) const RemoveFolderDialog = lazyWithRetry(() => import('./RemoveFolderDialog')) const WorktreeVisibilityDialog = lazyWithRetry(() => import('./WorktreeVisibilityDialog')) const OrcaYamlTrustDialog = lazyWithRetry(() => import('./OrcaYamlTrustDialog')) +const ForgetSshWorkspaceDialog = lazyWithRetry(() => import('./ForgetSshWorkspaceDialog')) const MIN_WIDTH = 220 const MAX_WIDTH = 500 @@ -207,6 +208,7 @@ function Sidebar({ {activeModal === 'confirm-remove-folder' ? : null} {activeModal === 'worktree-visibility' ? : null} {activeModal === 'confirm-orca-yaml-hooks' ? : null} + {activeModal === 'forget-ssh-workspace' ? : null} {sidebarOpen ? ( { + return new Map([[id, { targetId: id, status: 'connected', error: null, reconnectAttempt: 0 }]]) +} + +describe('resolveSshHostRemoval', () => { + const repos = [ + { id: 'repo-a', connectionId: 'ssh-1' }, + { id: 'repo-b', connectionId: 'ssh-1' }, + { id: 'repo-local', connectionId: null } + ] + const worktrees = [ + { id: 'repo-a::/wt/main', repoId: 'repo-a', isMainWorktree: true }, + { id: 'repo-a::/wt/feature', repoId: 'repo-a', isMainWorktree: false }, + { id: 'repo-b::/wt/x', repoId: 'repo-b', isMainWorktree: false }, + { id: 'repo-local::/wt/y', repoId: 'repo-local', isMainWorktree: false } + ] + + it('collects non-main worktrees and root repos on the target', () => { + const result = resolveSshHostRemoval({ + targetId: 'ssh-1', + repos, + worktrees, + sshConnectionStates: new Map() + }) + expect(result.workspaceWorktreeIds.sort()).toEqual( + ['repo-a::/wt/feature', 'repo-b::/wt/x'].sort() + ) + expect(result.hostRepoIds.sort()).toEqual(['repo-a', 'repo-b']) + // 2 child worktrees + 2 root repos. + expect(result.workspaceCount).toBe(4) + expect(result.isConnected).toBe(false) + }) + + it('ignores repos and worktrees on other hosts', () => { + const result = resolveSshHostRemoval({ + targetId: 'ssh-1', + repos, + worktrees, + sshConnectionStates: new Map() + }) + expect(result.workspaceWorktreeIds).not.toContain('repo-local::/wt/y') + expect(result.hostRepoIds).not.toContain('repo-local') + }) + + it('reports connected when the target relay is connected', () => { + const result = resolveSshHostRemoval({ + targetId: 'ssh-1', + repos, + worktrees, + sshConnectionStates: connected('ssh-1') + }) + expect(result.isConnected).toBe(true) + }) + + it('reports zero workspaces for a target nothing points at', () => { + const result = resolveSshHostRemoval({ + targetId: 'ssh-unused', + repos, + worktrees, + sshConnectionStates: new Map() + }) + expect(result.workspaceCount).toBe(0) + expect(result.hostRepoIds).toEqual([]) + }) + + it('dedupes duplicate repo and worktree rows so the count is not inflated', () => { + const result = resolveSshHostRemoval({ + // Store transiently holds duplicate rows (e.g. mid host merge). + targetId: 'ssh-1', + repos: [ + { id: 'repo-a', connectionId: 'ssh-1' }, + { id: 'repo-a', connectionId: 'ssh-1' } // duplicate repo row + ], + worktrees: [ + { id: 'repo-a::/wt/x', repoId: 'repo-a', isMainWorktree: false }, + { id: 'repo-a::/wt/x', repoId: 'repo-a', isMainWorktree: false }, // duplicate + { id: 'repo-a::/wt/x', repoId: 'repo-a', isMainWorktree: false } // triplicate + ], + sshConnectionStates: new Map() + }) + expect(result.hostRepoIds).toEqual(['repo-a']) + expect(result.workspaceWorktreeIds).toEqual(['repo-a::/wt/x']) + // 1 root repo + 1 unique child worktree. + expect(result.workspaceCount).toBe(2) + }) +}) diff --git a/src/renderer/src/components/sidebar/ssh-host-remove-resolution.ts b/src/renderer/src/components/sidebar/ssh-host-remove-resolution.ts new file mode 100644 index 000000000..4949ab3db --- /dev/null +++ b/src/renderer/src/components/sidebar/ssh-host-remove-resolution.ts @@ -0,0 +1,55 @@ +import type { Repo, Worktree } from '../../../../shared/types' +import type { SshConnectionState } from '../../../../shared/ssh-types' + +/** + * Classifies what removing an SSH target means for the workspaces still on it, + * so the host-removal dialog can offer the right choice: + * - connected → can delete host AND its remote worktrees (real git removal) + * - offline → target still configured but not connected; delete would need a + * reconnect, so default to forgetting the workspaces locally + * - (no workspaces) → plain host removal, no workspace decision needed + */ +export type SshHostRemoveResolution = { + targetId: string + /** Ids of non-main worktrees on this host that a remote delete would remove. */ + workspaceWorktreeIds: string[] + /** Repo ids whose main/root workspace lives on this host. */ + hostRepoIds: string[] + workspaceCount: number + isConnected: boolean +} + +export function resolveSshHostRemoval(args: { + targetId: string + repos: readonly Pick[] + worktrees: readonly Pick[] + sshConnectionStates: ReadonlyMap +}): SshHostRemoveResolution { + const hostRepoIds = [ + ...new Set( + args.repos + .filter((repo) => repo.connectionId?.trim() === args.targetId) + .map((repo) => repo.id) + ) + ] + const hostRepoIdSet = new Set(hostRepoIds) + // Why: dedupe by id — the store can transiently hold duplicate worktree rows + // (e.g. mid host merge), and a doubled row must not inflate the count shown to + // the user or cause a worktree to be removed twice. + const workspaceWorktreeIds = [ + ...new Set( + args.worktrees + .filter((worktree) => hostRepoIdSet.has(worktree.repoId) && !worktree.isMainWorktree) + .map((worktree) => worktree.id) + ) + ] + const isConnected = args.sshConnectionStates.get(args.targetId)?.status === 'connected' + return { + targetId: args.targetId, + workspaceWorktreeIds, + hostRepoIds, + // A repo's main/root workspace counts too — removing the host drops it. + workspaceCount: workspaceWorktreeIds.length + hostRepoIds.length, + isConnected + } +} diff --git a/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts new file mode 100644 index 000000000..87145f0e4 --- /dev/null +++ b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts @@ -0,0 +1,70 @@ +import { getRepoExecutionHostId, toSshExecutionHostId } from '../../../../shared/execution-host' +import { useAppStore } from '@/store' +import type { SshHostRemoveResolution } from './ssh-host-remove-resolution' + +export type ClearSshHostWorkspacesResult = { + /** Worktree/repo removals that reported failure ({ ok: false }). Non-empty + * means the SSH target should not be reported as fully removed. */ + failedIds: string[] +} + +/** + * Clears the workspaces on an SSH host that is being removed, before the target + * itself is deleted. Two modes: + * - 'delete-remote': the host is connected, so run the normal remote removal + * for each worktree (deletes the remote git worktree) and the host-scoped + * project removal for each root repo. + * - 'forget-local': the host is offline/gone, so only clear Orca's records — + * no remote files, worktrees, or branches are touched. + * + * Worktrees are removed before their root repos so a root removal never races a + * still-registered child. Failures are collected (not thrown) so the caller can + * decide whether to proceed with target removal. + */ +export async function clearSshHostWorkspaces( + resolution: SshHostRemoveResolution, + mode: 'delete-remote' | 'forget-local' +): Promise { + const store = useAppStore.getState() + const forgetLocalOnly = mode === 'forget-local' + const failedIds: string[] = [] + + for (const worktreeId of resolution.workspaceWorktreeIds) { + // Why: sequential, not parallel — deletes on the same repo contend on git + // ref locks, and forget is cheap enough that ordering keeps failures legible. + const result = await store.removeWorktree( + worktreeId, + false, + forgetLocalOnly ? { mode: 'forget-local' } : undefined + ) + if (!result.ok) { + failedIds.push(worktreeId) + } + } + + // Why: removeProject purges renderer state and (in main) is host-scoped. Pass + // the explicit SSH host id so a repo id shared with the local host resolves to + // this host's row instead of falling back to the focused host — otherwise the + // wrong (local) project could be removed and the SSH ghost left behind. For an + // offline/ghost host this hits the local backend path (no live runtime target), + // clearing Orca's records without a successful remote call. + const hostId = toSshExecutionHostId(resolution.targetId) + for (const repoId of resolution.hostRepoIds) { + try { + await store.removeProject(repoId, { hostId }) + } catch { + failedIds.push(repoId) + } + // Why: removeProject swallows its own errors and returns void, so the + // try/catch above can't observe a failure. Verify the host's repo row is + // actually gone; if it lingers, the removal did not succeed. + const stillPresent = useAppStore + .getState() + .repos.some((repo) => repo.id === repoId && getRepoExecutionHostId(repo) === hostId) + if (stillPresent && !failedIds.includes(repoId)) { + failedIds.push(repoId) + } + } + + return { failedIds } +} diff --git a/src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.test.ts b/src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.test.ts new file mode 100644 index 000000000..85f791925 --- /dev/null +++ b/src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.test.ts @@ -0,0 +1,70 @@ +import { describe, it, expect } from 'vitest' +import { resolveSshWorkspaceForget } from './ssh-workspace-forget-resolution' +import type { SshConnectionState } from '../../../../shared/ssh-types' + +function stateMap( + entries: Record +): Map { + return new Map( + Object.entries(entries).map(([id, status]) => [ + id, + { targetId: id, status, error: null, reconnectAttempt: 0 } + ]) + ) +} + +describe('resolveSshWorkspaceForget', () => { + it('returns not-ssh for a repo with no connectionId', () => { + const result = resolveSshWorkspaceForget({ + repo: { connectionId: null }, + sshConnectionStates: new Map(), + sshTargetLabels: new Map() + }) + expect(result.kind).toBe('not-ssh') + }) + + it('returns not-ssh for a runtime-owned target', () => { + const result = resolveSshWorkspaceForget({ + repo: { connectionId: 'runtime-ssh-abc' }, + sshConnectionStates: new Map(), + sshTargetLabels: new Map() + }) + expect(result.kind).toBe('not-ssh') + }) + + it('returns ghost when the target is no longer configured', () => { + const result = resolveSshWorkspaceForget({ + repo: { connectionId: 'ssh-dead' }, + sshConnectionStates: new Map(), + sshTargetLabels: new Map() // ssh-dead not present -> ghost + }) + expect(result).toEqual({ kind: 'ghost', targetId: 'ssh-dead' }) + }) + + it('returns connected when the configured target is connected', () => { + const result = resolveSshWorkspaceForget({ + repo: { connectionId: 'ssh-live' }, + sshConnectionStates: stateMap({ 'ssh-live': 'connected' }), + sshTargetLabels: new Map([['ssh-live', 'Live']]) + }) + expect(result).toEqual({ kind: 'connected', targetId: 'ssh-live' }) + }) + + it('returns disconnected when configured but not connected', () => { + const result = resolveSshWorkspaceForget({ + repo: { connectionId: 'ssh-live' }, + sshConnectionStates: stateMap({ 'ssh-live': 'error' }), + sshTargetLabels: new Map([['ssh-live', 'Live']]) + }) + expect(result).toEqual({ kind: 'disconnected', targetId: 'ssh-live', status: 'error' }) + }) + + it('defaults to disconnected status when configured target has no live state', () => { + const result = resolveSshWorkspaceForget({ + repo: { connectionId: 'ssh-live' }, + sshConnectionStates: new Map(), + sshTargetLabels: new Map([['ssh-live', 'Live']]) + }) + expect(result).toEqual({ kind: 'disconnected', targetId: 'ssh-live', status: 'disconnected' }) + }) +}) diff --git a/src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.ts b/src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.ts new file mode 100644 index 000000000..72243c5f3 --- /dev/null +++ b/src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.ts @@ -0,0 +1,50 @@ +import type { Repo } from '../../../../shared/types' +import type { SshConnectionState } from '../../../../shared/ssh-types' +import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host' + +/** + * How a workspace on an SSH host should be deleted, given the host's live + * state. Drives whether the delete flow can go straight through the normal + * remote removal, must offer a reconnect-first choice, or can only forget the + * workspace from Orca because the SSH target is gone entirely. + */ +export type SshWorkspaceForgetResolution = + | { kind: 'not-ssh' } + // Target exists and the relay is connected — normal remote removal works. + | { kind: 'connected'; targetId: string } + // Target still configured but not connected — offer Reconnect & Delete plus + // a local-only forget fallback. + | { kind: 'disconnected'; targetId: string; status: SshConnectionState['status'] } + // Target was removed; only a project-only "ghost" host remains. Reconnect is + // impossible, so forget-from-Orca is the only path. + | { kind: 'ghost'; targetId: string } + +export function resolveSshWorkspaceForget(args: { + repo: Pick | null | undefined + sshConnectionStates: ReadonlyMap + // Keys are configured SSH target ids (targets that still exist in settings). + sshTargetLabels: ReadonlyMap +}): SshWorkspaceForgetResolution { + const connectionId = args.repo?.connectionId?.trim() + // Why: runtime-owned (ephemeral-VM) SSH targets manage their own lifecycle and + // are never user-facing ghosts, so they take the normal delete path. + if (!connectionId || isRuntimeOwnedSshTargetId(connectionId)) { + return { kind: 'not-ssh' } + } + + const isConfigured = args.sshTargetLabels.has(connectionId) + const status = args.sshConnectionStates.get(connectionId)?.status + + // Why: a target the user removed leaves repos pinned to a dead id with no + // configured target — the grey ghost host. Reconnect can never succeed, so + // the only escape is to forget it from Orca. + if (!isConfigured) { + return { kind: 'ghost', targetId: connectionId } + } + + if (status === 'connected') { + return { kind: 'connected', targetId: connectionId } + } + + return { kind: 'disconnected', targetId: connectionId, status: status ?? 'disconnected' } +} diff --git a/src/renderer/src/components/tab-bar/EditorFileTab.tsx b/src/renderer/src/components/tab-bar/EditorFileTab.tsx index 9de55f9c9..2ce15236f 100644 --- a/src/renderer/src/components/tab-bar/EditorFileTab.tsx +++ b/src/renderer/src/components/tab-bar/EditorFileTab.tsx @@ -80,6 +80,11 @@ export default function EditorFileTab({ const isConflictReview = file.mode === 'conflict-review' const isCheckDetails = file.mode === 'check-details' const isMarkdownPreviewTab = file.mode === 'markdown-preview' + // Why: only deleted/renamed mean the file is gone from its path, which is + // what strikethrough conveys. 'changed' keeps a normal label — its surface + // is the changed-on-disk banner inside the editor. + const isMissingFileMutation = + file.externalMutation === 'deleted' || file.externalMutation === 'renamed' const resolvedLanguage = file.mode === 'diff' ? detectLanguage(file.relativePath) @@ -308,7 +313,7 @@ export default function EditorFileTab({ /> ) : ( { if (file.isPreview && onMakePermanent) { @@ -329,12 +334,12 @@ export default function EditorFileTab({ {tabLabel} )} - {file.externalMutation && !isRenaming && ( + {isMissingFileMutation && !isRenaming && ( {file.externalMutation} )} - {tabStatus && !isRenaming && !file.externalMutation && ( + {tabStatus && !isRenaming && !isMissingFileMutation && ( { + toast.success( + translate( + 'auto.components.tab.group.AiVaultSessionDropLayer.sessionQueued', + 'Session queued' + ) ) - ) + } + if (launchResult.tabId === null) { + void launchResult.runtimeLaunch.then((created) => { + if (!created) { + toast.error( + translate( + 'auto.lib.launch.agent.in.new.tab.11cce5cc77', + 'Could not launch {{value0}} in a new terminal.', + { value0: payload.agent } + ) + ) + return + } + showQueuedToast() + }) + return true + } + showQueuedToast() return true }, [clearDragState, target, updateTarget, worktreeId] diff --git a/src/renderer/src/components/terminal-pane/TerminalPane.tsx b/src/renderer/src/components/terminal-pane/TerminalPane.tsx index ee8053809..7bdb5d203 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPane.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPane.tsx @@ -24,7 +24,17 @@ import TerminalSearch from '@/components/TerminalSearch' import type { PtyTransport } from './pty-transport' import { fitPanes, isWindowsUserAgent } from './pane-helpers' import { getConnectionId, getConnectionIdFromState } from '@/lib/connection-context' -import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { + getExplicitRuntimeEnvironmentIdForWorktree, + getRuntimeEnvironmentIdForWorktree +} from '@/lib/worktree-runtime-owner' +import { + selectRuntimeAwareSshStatus, + selectRuntimeAwareSshTargetLabel, + selectRuntimeAwareSshTargetRemoved +} from '@/store/slices/runtime-environment-ssh' +import { hydrateRuntimeEnvironmentSshState } from '@/runtime/runtime-environment-ssh-state' +import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' import { handleInternalTerminalFileDrop } from './terminal-drop-handler' import { recordTerminalUserInputForLeaf } from './terminal-input-activity' import { @@ -306,16 +316,44 @@ export default function TerminalPane({ } return connectionId }) + // Which machine's SSH store this target belongs to: a remote Orca server's + // per-environment bucket, or null for this machine's local SSH maps. The + // explicit-owner resolver never lets a merely focused runtime make a + // local-owned workspace look remote. The paired web client mirrors its one + // host through the local maps instead. + const sshReconnectEnvironmentId = useAppStore((store) => + sshReconnectTargetId && !isPairedWebClientWindow() + ? getExplicitRuntimeEnvironmentIdForWorktree(store, worktreeId) + : null + ) const sshReconnectStatus = useAppStore((store) => sshReconnectTargetId - ? (store.sshConnectionStates.get(sshReconnectTargetId)?.status ?? 'disconnected') + ? selectRuntimeAwareSshStatus(store, sshReconnectEnvironmentId, sshReconnectTargetId) : null ) const sshReconnectTargetLabel = useAppStore((store) => sshReconnectTargetId - ? (store.sshTargetLabels.get(sshReconnectTargetId) ?? sshReconnectTargetId) + ? selectRuntimeAwareSshTargetLabel(store, sshReconnectEnvironmentId, sshReconnectTargetId) : '' ) + // Why: the target was removed entirely (a ghost) when it's no longer a known + // SSH target on its owning host. Reconnecting to it can only fail ("SSH + // target not found"), so the overlay must offer to remove the workspace + // instead of Connect. The selector requires positive removal evidence. + const sshReconnectTargetRemoved = useAppStore((store) => + sshReconnectTargetId + ? selectRuntimeAwareSshTargetRemoved(store, sshReconnectEnvironmentId, sshReconnectTargetId) + : false + ) + useEffect(() => { + if (!sshReconnectEnvironmentId) { + return + } + // Why: an SSH-backed workspace can be mirrored before its owning + // environment's bucket ever hydrated (no-op once hydrated), and overlay + // state must come from fetched evidence, never from an empty default. + void hydrateRuntimeEnvironmentSshState(sshReconnectEnvironmentId).catch(() => {}) + }, [sshReconnectEnvironmentId]) useVisibleTerminalTabClaim({ isVisible, tabId }) @@ -2972,6 +3010,9 @@ export default function TerminalPane({ targetId={sshReconnectTargetId} targetLabel={sshReconnectTargetLabel} status={sshReconnectStatus} + targetRemoved={sshReconnectTargetRemoved} + worktreeId={worktreeId} + sshOwnerEnvironmentId={sshReconnectEnvironmentId} /> ) : null} diff --git a/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.test.tsx b/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.test.tsx index 328dbec12..7f46a5181 100644 --- a/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.test.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.test.tsx @@ -13,23 +13,44 @@ const toastMocks = vi.hoisted(() => ({ error: vi.fn() })) +const deleteFlowMocks = vi.hoisted(() => ({ + runWorktreeDelete: vi.fn() +})) + +const environmentSshMocks = vi.hoisted(() => ({ + connectRuntimeEnvironmentSshTarget: vi.fn(), + resyncRuntimeEnvironmentSshTargets: vi.fn() +})) + vi.mock('sonner', () => ({ toast: { error: toastMocks.error } })) +vi.mock('../sidebar/delete-worktree-flow', () => ({ + runWorktreeDelete: deleteFlowMocks.runWorktreeDelete +})) + +vi.mock('@/runtime/runtime-environment-ssh-state', () => environmentSshMocks) + vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string, values?: Record) => fallback.replace('{{value0}}', values?.value0 ?? '') })) -function installSshConnect(connect: ReturnType): void { +function installSshConnect( + connect: ReturnType, + overrides: Record> = {} +): void { Object.defineProperty(window, 'api', { configurable: true, value: { ssh: { - connect + connect, + listTargets: vi.fn().mockResolvedValue([]), + listRemovedTargetLabels: vi.fn().mockResolvedValue({}), + ...overrides } } }) @@ -39,6 +60,9 @@ describe('TerminalSshReconnectOverlay', () => { beforeEach(() => { useAppStore.setState(useAppStore.getInitialState(), true) toastMocks.error.mockReset() + deleteFlowMocks.runWorktreeDelete.mockReset() + environmentSshMocks.connectRuntimeEnvironmentSshTarget.mockReset() + environmentSshMocks.resyncRuntimeEnvironmentSshTargets.mockReset() }) afterEach(() => { @@ -101,6 +125,139 @@ describe('TerminalSshReconnectOverlay', () => { expect(screen.getByRole('button', { name: 'Connect' })).toBeEnabled() }) + it('resyncs target metadata after a failed connect so a stale overlay converges', async () => { + const connect = vi.fn().mockRejectedValue(new Error('SSH target "ssh-dead" not found')) + const listTargets = vi + .fn() + .mockResolvedValue([ + { id: 'ssh-live', label: 'devbox', host: 'devbox', port: 22, username: 'me' } + ]) + const listRemovedTargetLabels = vi.fn().mockResolvedValue({ 'ssh-dead': 'devbox (removed)' }) + installSshConnect(connect, { listTargets, listRemovedTargetLabels }) + const user = userEvent.setup() + + render( + + ) + + await user.click(screen.getByRole('button', { name: 'Connect' })) + + // Why: the metadata refresh is what flips TerminalPane's targetRemoved + // derivation, replacing the failing Connect loop with the ghost-host UI. + await waitFor(() => { + expect(useAppStore.getState().sshTargetLabels.get('ssh-live')).toBe('devbox') + expect(useAppStore.getState().removedSshTargetLabels.get('ssh-dead')).toBe('devbox (removed)') + }) + }) + + it('still applies the target list when the removed-labels refresh fails', async () => { + const connect = vi.fn().mockRejectedValue(new Error('SSH target "ssh-dead" not found')) + const listTargets = vi + .fn() + .mockResolvedValue([ + { id: 'ssh-live', label: 'devbox', host: 'devbox', port: 22, username: 'me' } + ]) + const listRemovedTargetLabels = vi.fn().mockRejectedValue(new Error('unavailable')) + installSshConnect(connect, { listTargets, listRemovedTargetLabels }) + const user = userEvent.setup() + + render( + + ) + + await user.click(screen.getByRole('button', { name: 'Connect' })) + + // Why: a removed-labels failure must not discard the refreshed target + // list — it alone is enough evidence for targetRemoved to converge. + await waitFor(() => { + expect(useAppStore.getState().sshTargetLabels.get('ssh-live')).toBe('devbox') + expect(useAppStore.getState().sshTargetsHydrated).toBe(true) + }) + }) + + it('offers to remove the workspace (not Connect) when the SSH target was removed', async () => { + const connect = vi.fn().mockResolvedValue(undefined) + installSshConnect(connect) + const user = userEvent.setup() + + render( + + ) + + expect(screen.getByText('SSH host removed')).toBeInTheDocument() + // No Connect button — reconnect is impossible for a removed target. + expect(screen.queryByRole('button', { name: 'Connect' })).not.toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Remove workspace' })) + expect(deleteFlowMocks.runWorktreeDelete).toHaveBeenCalledWith('repo::/work/wt') + expect(connect).not.toHaveBeenCalled() + }) + + it('routes Connect to the owning environment runtime RPC for a remote-owned workspace', async () => { + const connect = vi.fn().mockResolvedValue(undefined) + installSshConnect(connect) + environmentSshMocks.connectRuntimeEnvironmentSshTarget.mockResolvedValue(null) + const user = userEvent.setup() + + render( + + ) + + await user.click(screen.getByRole('button', { name: 'Connect' })) + + await waitFor(() => + expect(environmentSshMocks.connectRuntimeEnvironmentSshTarget).toHaveBeenCalledWith( + 'env-1', + 'ssh-remote-1' + ) + ) + // The local ssh API must never see a remote host's target. + expect(connect).not.toHaveBeenCalled() + }) + + it('resyncs the owning environment (not the local store) after a failed remote connect', async () => { + const connect = vi.fn().mockResolvedValue(undefined) + const listTargets = vi.fn().mockResolvedValue([]) + installSshConnect(connect, { listTargets }) + environmentSshMocks.connectRuntimeEnvironmentSshTarget.mockRejectedValue( + new Error('SSH target "ssh-remote-dead" not found') + ) + environmentSshMocks.resyncRuntimeEnvironmentSshTargets.mockResolvedValue(undefined) + const user = userEvent.setup() + + render( + + ) + + await user.click(screen.getByRole('button', { name: 'Connect' })) + + await waitFor(() => + expect(toastMocks.error).toHaveBeenCalledWith('SSH target "ssh-remote-dead" not found') + ) + await waitFor(() => + expect(environmentSshMocks.resyncRuntimeEnvironmentSshTargets).toHaveBeenCalledWith('env-1') + ) + // The failed-connect resync must not rewrite local target metadata. + expect(listTargets).not.toHaveBeenCalled() + expect(useAppStore.getState().sshTargetsHydrated).toBe(false) + }) + it('publishes the returned SSH state so deferred terminal reattach can resume', async () => { const connectedState: SshConnectionState = { targetId: 'ssh-target-1', diff --git a/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.tsx b/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.tsx index 8d6b013b0..b3ee59833 100644 --- a/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.tsx @@ -6,11 +6,24 @@ import { useMountedRef } from '@/hooks/useMountedRef' import { useAppStore } from '@/store' import type { SshConnectionStatus } from '../../../../shared/ssh-types' import { translate } from '@/i18n/i18n' +import { runWorktreeDelete } from '../sidebar/delete-worktree-flow' +import { + connectRuntimeEnvironmentSshTarget, + resyncRuntimeEnvironmentSshTargets +} from '@/runtime/runtime-environment-ssh-state' type TerminalSshReconnectOverlayProps = { targetId: string targetLabel: string status: SshConnectionStatus + // The SSH target was removed entirely — reconnect is impossible, so offer to + // remove the workspace instead of a Connect button that can only fail. + targetRemoved?: boolean + worktreeId?: string + // Set when the SSH target belongs to a remote Orca server (runtime + // environment): Connect and the failed-connect resync then route to that + // environment's runtime RPC and bucket instead of the local ssh.* API. + sshOwnerEnvironmentId?: string | null } // Why: relay deployment/reconnect are host-driven transient states; the @@ -63,13 +76,17 @@ function messageForStatus(status: SshConnectionStatus, targetLabel: string): str export function TerminalSshReconnectOverlay({ targetId, targetLabel, - status + status, + targetRemoved = false, + worktreeId, + sshOwnerEnvironmentId = null }: TerminalSshReconnectOverlayProps): React.JSX.Element { const [connecting, setConnecting] = useState(false) const mountedRef = useMountedRef() const setSshConnectionState = useAppStore((store) => store.setSshConnectionState) const isConnecting = connecting || isConnectingStatus(status) - const showConnect = canConnectStatus(status) + // Why: a removed target can never reconnect, so never offer Connect for it. + const showConnect = !targetRemoved && canConnectStatus(status) const handleConnect = useCallback(async () => { if (isConnecting) { @@ -77,11 +94,16 @@ export function TerminalSshReconnectOverlay({ } setConnecting(true) try { - const connectState = await window.api.ssh.connect({ targetId }) - if (connectState) { - // Why: ssh.connect can resolve before the global state-change IPC lands; - // the waiting deferred PTY reattach path keys off this renderer store. - setSshConnectionState(targetId, connectState) + if (sshOwnerEnvironmentId) { + // Bucket state is written inside the helper, mirroring the local path. + await connectRuntimeEnvironmentSshTarget(sshOwnerEnvironmentId, targetId) + } else { + const connectState = await window.api.ssh.connect({ targetId }) + if (connectState) { + // Why: ssh.connect can resolve before the global state-change IPC lands; + // the waiting deferred PTY reattach path keys off this renderer store. + setSshConnectionState(targetId, connectState) + } } } catch (err) { toast.error( @@ -92,12 +114,27 @@ export function TerminalSshReconnectOverlay({ 'SSH connection failed' ) ) + // Why: a failed connect usually means the renderer's target metadata is + // stale (target removed, or re-added under a new id). Resync it so the + // overlay converges to the ghost/re-adopted state instead of offering + // the same failing Connect forever (STA-1468). Apply the target list + // first — a removed-labels failure must not discard it. + if (sshOwnerEnvironmentId) { + void resyncRuntimeEnvironmentSshTargets(sshOwnerEnvironmentId).catch(() => {}) + } else { + void (async () => { + const targets = await window.api.ssh.listTargets() + useAppStore.getState().setSshTargetsMetadata(targets) + const removedLabels = await window.api.ssh.listRemovedTargetLabels() + useAppStore.getState().setRemovedSshTargetLabels(removedLabels) + })().catch(() => {}) + } } finally { if (mountedRef.current) { setConnecting(false) } } - }, [isConnecting, mountedRef, setSshConnectionState, targetId]) + }, [isConnecting, mountedRef, setSshConnectionState, sshOwnerEnvironmentId, targetId]) return (
- {translate( - 'auto.components.terminal.pane.TerminalSshReconnectOverlay.title', - 'SSH connection required' - )} + {targetRemoved + ? translate( + 'auto.components.terminal.pane.TerminalSshReconnectOverlay.removedTitle', + 'SSH host removed' + ) + : translate( + 'auto.components.terminal.pane.TerminalSshReconnectOverlay.title', + 'SSH connection required' + )}
- {messageForStatus(status, targetLabel)} + {targetRemoved + ? translate( + 'auto.components.terminal.pane.TerminalSshReconnectOverlay.removedBody', + 'The SSH host for this workspace was removed, so it can no longer connect. Remove the workspace to clear it — remote files are left untouched.' + ) + : messageForStatus(status, targetLabel)}
@@ -130,26 +177,40 @@ export function TerminalSshReconnectOverlay({ {targetLabel}
- + {targetRemoved ? ( + + ) : ( + + )}
diff --git a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts index 8e9d37327..d3e613f68 100644 --- a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts +++ b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts @@ -176,25 +176,24 @@ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTracke // can identify the foreground — that pair is exactly a leaked nested-shell // command under a full-screen agent (or a fast real shell command), so on a // no-identity pane confirm it rather than trusting the D as a prompt return. - // A pending confirming read counts too: user shell integrations double up - // Orca's OSC 133, and the duplicate D must re-confirm, not fast-path past - // the in-flight confirmation it just cancelled. - const commandReadWasPending = - scheduledReadReason === 'command' || - activeReadReason === 'command' || - scheduledReadReason === 'command-finished' || - activeReadReason === 'command-finished' + // ANY in-flight read counts: a command-start read, a prior confirming read + // (user shell integrations double up Orca's OSC 133), or the reattach/visible + // recovery probe. All three are attempts to establish this pane's identity, so + // a D that cancels one must re-confirm — never fast-path to shell, which the + // sampleVisiblePaneForegroundAgent gate would then latch, permanently hiding + // an idle reattached agent's icon (the "codex reattached at rest" bug). + const identityReadWasPending = scheduledReadReason !== null || activeReadReason !== null cancelPendingRead() if (!trackablePtyId()) { return } // Why: trust the 133;D and mark shell without an RPC only when nothing hints // at an agent — no prior agent evidence, no launch/hook identity, and no - // command-start read racing this finish. + // identity read racing this finish. if ( !hasForegroundAgentEvidence && deps.hasKnownAgentIdentity?.() !== true && - !commandReadWasPending + !identityReadWasPending ) { deps.publish({ agent: null, shellForeground: true }) return diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index 49432d691..3f159cc6a 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -210,6 +210,7 @@ type MockTransport = { ) => unknown } sendInput: ReturnType + sendInputImmediate: ReturnType sendInputAccepted?: ReturnType resize: ReturnType getPtyId: ReturnType @@ -358,6 +359,9 @@ function createMockTransport(initialPtyId: string | null = null): MockTransport serializeBuffer: undefined } as MockTransport const sendInput = transport.sendInput as unknown as (data: string) => boolean + // Why: query replies now route through sendInputImmediate; delegate to the + // same spy so assertions on reply delivery still observe them (#7329). + transport.sendInputImmediate = vi.fn((data: string) => sendInput(data)) transport.sendInputAccepted = vi.fn(async (data: string) => sendInput(data)) return transport } @@ -5262,6 +5266,189 @@ describe('connectPanePty', () => { ) }) + it('resizes the pane to the snapshot grid before replaying daemon snapshot bytes (bug #7279)', async () => { + // Why: the daemon serializes soft-wrapped lines as continuous text. Replaying + // that at the pane's current column count rewraps rows one cell early/late. + // The reattach path must resize xterm to the snapshot's grid before writing + // the snapshot bytes, so a remote pane whose size drifted from the daemon's + // grid still repaints the exact host layout. + const { connectPanePty } = await import('./pty-connection') + const transport = createMockTransport() + transport.connect.mockImplementation(async ({ sessionId }: { sessionId?: string }) => { + if (sessionId) { + return { + id: sessionId, + snapshot: '\x1b[?1004hrestored snapshot', + snapshotCols: 80, + snapshotRows: 24 + } + } + return null + }) + transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { + 'wt-1': [{ id: 'tab-1', ptyId: 'tab-pty' }] + } + } as StoreState + + // createPane opens the pane at 120x40, deliberately different from the + // daemon snapshot's 80x24 grid. + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + restoredLeafId: LEAF_1, + restoredPtyIdByLeafId: { [LEAF_1]: 'tab-pty' } + }) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks(20) + + // Pane was resized to the snapshot grid before the snapshot bytes landed. + expect(pane.terminal.resize).toHaveBeenCalledWith(80, 24) + const resizeToSnapshotCall = pane.terminal.resize.mock.invocationCallOrder.find( + (_order, index) => { + const [cols, rows] = pane.terminal.resize.mock.calls[index] + return cols === 80 && rows === 24 + } + ) + const snapshotWriteCall = pane.terminal.write.mock.invocationCallOrder.find( + (_order, index) => pane.terminal.write.mock.calls[index][0] === '\x1b[?1004hrestored snapshot' + ) + expect(resizeToSnapshotCall).toBeDefined() + expect(snapshotWriteCall).toBeDefined() + expect(resizeToSnapshotCall as number).toBeLessThan(snapshotWriteCall as number) + }) + + it('writes the daemon pendingEscapeTailAnsi after the reset on local reattach (#7329)', async () => { + // Why: the mid-escape tail must be re-armed LAST — after the reattach reset, + // whose ESC would abort it — so the racing live continuation completes it + // instead of rendering literally. Covers the local daemon reattach path, + // which previously dropped the field the remote path already honored. + const { connectPanePty } = await import('./pty-connection') + const transport = createMockTransport() + transport.connect.mockImplementation(async ({ sessionId }: { sessionId?: string }) => { + if (sessionId) { + return { + id: sessionId, + snapshot: 'restored snapshot', + snapshotCols: 80, + snapshotRows: 24, + pendingEscapeTailAnsi: '\x1b[3' + } + } + return null + }) + transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'tab-pty' }] } + } as StoreState + + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + restoredLeafId: LEAF_1, + restoredPtyIdByLeafId: { [LEAF_1]: 'tab-pty' } + }) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks(20) + + const tailWriteCall = pane.terminal.write.mock.invocationCallOrder.find( + (_order, index) => pane.terminal.write.mock.calls[index][0] === '\x1b[3' + ) + const resetWriteCall = pane.terminal.write.mock.invocationCallOrder.find((_order, index) => + String(pane.terminal.write.mock.calls[index][0]).includes(POST_REPLAY_REATTACH_RESET) + ) + expect(tailWriteCall).toBeDefined() + expect(resetWriteCall).toBeDefined() + // The dangling tail is written AFTER the reset. + expect(resetWriteCall as number).toBeLessThan(tailWriteCall as number) + }) + + it('routes native onData query replies through sendInputImmediate, typed input through sendInput (#7329)', async () => { + // Why this test: the mock transport delegates sendInputImmediate to the + // sendInput spy, so reply-delivery assertions elsewhere cannot tell the two + // apart — reverting the onData isTerminalQueryReply branch used to pass the + // whole suite. This pins the routing decision itself. + const { connectPanePty } = await import('./pty-connection') + enableActiveRuntimeEnvironment() + const pane = createPane(1) + const transport = createMockTransport('remote:web-env-1@@pty-7329') + transportFactoryQueue.push(transport) + const manager = createManager(1, 1) + const deps = createDeps() + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + + // xterm answers CSI 6n natively by emitting a CPR through onData, mixed + // with keystrokes. It must take the immediate path (skips the remote 8ms + // input debounce that corrupted it). + sendTerminalInputThroughPane(pane, '\x1b[3;1R') + expect(transport.sendInputImmediate).toHaveBeenCalledWith('\x1b[3;1R') + + // Ordinary typed input must stay on the debounced path — never immediate. + transport.sendInputImmediate.mockClear() + sendTerminalInputThroughPane(pane, 'yes') + sendTerminalInputThroughPane(pane, '\x1b[A') // arrow-key auto-repeat stays batched + expect(transport.sendInput).toHaveBeenCalledWith('yes') + expect(transport.sendInput).toHaveBeenCalledWith('\x1b[A') + expect(transport.sendInputImmediate).not.toHaveBeenCalled() + }) + + it('writes the onReplayData pendingEscapeTailAnsi meta last, after the replayed bytes (#7329)', async () => { + // Why this test: the remote snapshot path delivers the daemon tail through + // transport callbacks.onReplayData meta into drainReplayDataQueue. That + // consumer (and the replayDataCallback meta threading before it) had no + // failing test — severing the meta pass-through kept the suite green. + const { connectPanePty } = await import('./pty-connection') + enableActiveRuntimeEnvironment() + const pane = createPane(1) + const writes: string[] = [] + pane.terminal.write = vi.fn((data: string, callback?: () => void) => { + writes.push(data) + callback?.() + }) as typeof pane.terminal.write + const transport = createMockTransport('remote:web-env-1@@pty-7329-tail') + const replayCallback: { + current: + | (( + data: string, + meta?: { clearBeforeReplay?: boolean; pendingEscapeTailAnsi?: string } + ) => void) + | null + } = { current: null } + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + replayCallback.current = callbacks.onReplayData ?? null + return { id: 'remote:web-env-1@@pty-7329-tail', replay: '' } + }) + transportFactoryQueue.push(transport) + const manager = createManager(1, 1) + const deps = createDeps() + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks(20) + expect(replayCallback.current).toBeTypeOf('function') + + replayCallback.current?.('remote snapshot bytes', { + clearBeforeReplay: false, + pendingEscapeTailAnsi: '\x1b[3' + }) + await flushAsyncTicks(20) + + const snapshotIndex = writes.indexOf('remote snapshot bytes') + const tailIndex = writes.lastIndexOf('\x1b[3') + expect(snapshotIndex).toBeGreaterThanOrEqual(0) + expect(tailIndex).toBeGreaterThanOrEqual(0) + // The dangling tail is re-armed after the snapshot (and any reset), so the + // next live chunk's continuation completes it instead of rendering literally. + expect(tailIndex).toBeGreaterThan(snapshotIndex) + expect(writes.slice(tailIndex + 1)).toEqual([]) + }) + it('preserves live modes and injects focus-in after focused agent reattach', async () => { const { connectPanePty } = await import('./pty-connection') const transport = createMockTransport() @@ -15840,6 +16027,66 @@ describe('connectPanePty', () => { shellForeground: false }) }) + + it('re-confirms rather than trusting a leaked 133;D that races the recovery read', async () => { + // Why: an idle reattached agent (no launchAgent/hook/title) schedules the + // visible-pty recovery read. A full-screen agent's nested shell then leaks a + // 133;D onto the main PTY. Trusting that D would mark the pane shell- + // foreground and the sample gate would latch it, hiding the agent icon + // forever — instead the leak must re-confirm the foreground. + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) + getForegroundProcess.mockResolvedValue('codex') + const ptyId = 'pty-reattach-idle-codex-leaked-d' + const tabId = `tab-${ptyId}` + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation( + async ({ sessionId, callbacks }: { sessionId?: string; callbacks?: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks?.onData ?? null + return sessionId ? { id: sessionId } : null + } + ) + transportFactoryQueue.push(transport) + const deps = createDeps({ + tabId, + restoredLeafId: LEAF_1, + restoredPtyIdByLeafId: { [LEAF_1]: ptyId } + }) + connectPanePty(createPane(1) as never, createManager(1) as never, deps as never) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks(20) + + const cacheKey = makePaneKey(tabId, LEAF_1) + dataCallbackRef.current?.('\x1b]133;D;0\x07') + + await advanceVisibleForegroundRead() + + expect(mockStoreState.setPaneForegroundAgent).not.toHaveBeenCalledWith(cacheKey, { + agent: null, + shellForeground: true + }) + expect(mockStoreState.setPaneForegroundAgent).toHaveBeenCalledWith(cacheKey, { + agent: 'codex', + shellForeground: false + }) + }) + + it('never probes the foreground for a visible remote/SSH restored pane', async () => { + // Why: foreground reads are local-only (expensive RPCs, replayed OSC + // streams). isTrackablePtyId must keep remote/SSH panes off the recovery + // probe entirely, so the fix stays local-only. + vi.useFakeTimers() + const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) + getForegroundProcess.mockResolvedValue('codex') + const ptyId = 'remote:web-env-1@@pty-remote-idle-agent' + + await connectRestoredPaneForForegroundSampling({ ptyId, tabId: 'tab-remote-idle-agent' }) + await advanceVisibleForegroundRead() + + expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) + }) }) describe('terminal input liveness IPC gating (perf)', () => { diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index e9494c672..fe8b7a391 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -9,6 +9,7 @@ import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph' import { useAppStore } from '@/store' import { getWorktreeMapFromState } from '@/store/selectors' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host' import { createTerminalZeroDimensionsMessage } from '../../../../shared/terminal-zero-dimensions-diagnostic' import { parseTerminalOscColorQuery } from '../../../../shared/terminal-osc-color-reply' import { @@ -22,6 +23,7 @@ import { } from '../../../../shared/terminal-reply-query-extraction' import { takeCurrentPtyDeliveryAckCredit } from './terminal-pty-ack-gate' import { serializeWithAbsoluteCursor } from '../../../../shared/terminal-serialize-absolute-cursor' +import { isTerminalQueryReply } from '../../../../shared/terminal-query-reply' import type { PtyBufferSnapshot, PtyConnectResult } from './pty-transport' import { createIpcPtyTransport } from './pty-transport' import { createRemoteRuntimePtyTransport } from './remote-runtime-pty-transport' @@ -2827,7 +2829,9 @@ export function connectPanePty( useAppStore.getState().settings, getSystemPrefersDark() ) - transport.sendInput(mode2031SequenceFor(mode)) + // Why immediate: a mode-2031 query reply must beat the remote input debounce + // or it can miss the querying program's read window (#7329). + transport.sendInputImmediate(mode2031SequenceFor(mode)) // Why: register the subscription exactly like the xterm CSI handler // would — without the registry entry, later theme flips never push the // CSI 997 update and the TUI keeps a stale theme after reveal. @@ -2838,13 +2842,16 @@ export function connectPanePty( const terminalCapabilityRepliesDisposable = installTerminalCapabilityReplyHandlers({ terminal: pane.terminal, parser: pane.terminal.parser, - sendInput: (data) => transport.sendInput(data), + // Why: OSC 10/11 + DA1 replies must beat the querying program's raw-mode + // read window; the remote transport's input debounce would corrupt them + // (#7329), so send immediately. + sendInput: (data) => transport.sendInputImmediate(data), isReplaying: () => isPaneReplaying(deps.replayingPanesRef, pane.id), ...(isNativeWindowsConpty ? { da1Response: CONPTY_DA1_RESPONSE } : {}) }) const respondToTerminalPixelSizeQueries = createTerminalPixelSizeQueryResponder( pane.terminal, - (data) => transport.sendInput(data) + (data) => transport.sendInputImmediate(data) ) const onDataDisposable = pane.terminal.onData((data) => { @@ -2882,6 +2889,19 @@ export function connectPanePty( clearPendingTerminalInputIntent() return } + // Why: xterm answers CPR/DSR/DA queries natively through this same onData + // stream (mixed with keystrokes). Those replies are latency-critical — a + // querying program reads them in raw mode with a short timeout — so send + // them immediately, skipping the remote input debounce that would corrupt + // them (#7329). They are not user input, so they bypass intent inference and + // activity recording below. No pending-intent guard: the only intents are + // plain-escape (`\x1b`) and ctrl-c (`\x03`), neither of which can satisfy + // isTerminalQueryReply (it requires length >= 3 and a full reply grammar), + // so a real keystroke never reaches this branch. + if (isTerminalQueryReply(data)) { + transport.sendInputImmediate(data) + return + } const intent = pendingTerminalInputIntent // Why: real xterm can deliver the terminal byte even when our DOM keydown // listener missed the press. Exact Ctrl+C/Escape bytes are still safe to @@ -4037,13 +4057,14 @@ export function connectPanePty( type PendingReplayData = { data: string clearBeforeReplay: boolean + pendingEscapeTailAnsi?: string } let pendingReplayData: PendingReplayData | null = null let replayDrainQueued = false const drainReplayDataQueue = async (): Promise => { while (pendingReplayData !== null) { - const { data, clearBeforeReplay } = pendingReplayData + const { data, clearBeforeReplay, pendingEscapeTailAnsi } = pendingReplayData pendingReplayData = null // Relay replay buffers may overlap with content already rendered in // xterm. Local eager replay decides this earlier so metadata-only frames @@ -4061,6 +4082,14 @@ export function connectPanePty( await writeReplayDataAsync(reattachReplayResetSequence()) sendFocusedReattachFocusInAfterReplay() } + // Why: the daemon could not serialize a PTY read that ended mid-escape, + // so the emulator shipped the dangling partial separately. Write it LAST + // — after the reset, whose ESC would otherwise abort it — so the next + // live chunk completes the sequence instead of rendering literally + // (#7329). Guarded so a later ESC cannot leave the parser wedged. + if (pendingEscapeTailAnsi) { + await writeReplayDataAsync(pendingEscapeTailAnsi) + } if (disposed) { pendingReplayData = null return @@ -4071,10 +4100,14 @@ export function connectPanePty( manager.rebuildPaneWebgl(pane.id) } } - const replayDataCallback = (data: string, meta: { clearBeforeReplay?: boolean } = {}): void => { + const replayDataCallback = ( + data: string, + meta: { clearBeforeReplay?: boolean; pendingEscapeTailAnsi?: string } = {} + ): void => { pendingReplayData = { data, - clearBeforeReplay: meta.clearBeforeReplay !== false + clearBeforeReplay: meta.clearBeforeReplay !== false, + ...(meta.pendingEscapeTailAnsi ? { pendingEscapeTailAnsi: meta.pendingEscapeTailAnsi } : {}) } if (replayDrainQueued) { return @@ -4087,7 +4120,10 @@ export function connectPanePty( replayDrainQueued = false if (pendingReplayData !== null) { replayDataCallback(pendingReplayData.data, { - clearBeforeReplay: pendingReplayData.clearBeforeReplay + clearBeforeReplay: pendingReplayData.clearBeforeReplay, + ...(pendingReplayData.pendingEscapeTailAnsi + ? { pendingEscapeTailAnsi: pendingReplayData.pendingEscapeTailAnsi } + : {}) }) } }) @@ -4700,9 +4736,10 @@ export function connectPanePty( hiddenStartupRendererQueryPending = extracted.pending if (extracted.oscColorQueryData) { // Why: Codex's startup palette probe has a 100 ms budget. Answer - // hidden color queries directly so renderer scheduling cannot miss it. + // hidden color queries directly and immediately so neither renderer + // scheduling nor the remote input debounce (#7329) can miss it. sendTerminalOscColorQueryReplies(extracted.oscColorQueryData, pane.terminal, (reply) => - transport.sendInput(reply) + transport.sendInputImmediate(reply) ) } if (extracted.statelessQueryData) { @@ -5399,8 +5436,9 @@ export function connectPanePty( if (snapshot.pendingEscapeTailAnsi) { // Why last: the snapshot was taken with main's emulator mid-escape; // re-arming the dangling sequence must be the FINAL replay write (any - // later ESC aborts it) so the racing tail's continuation bytes - // complete it exactly as live (Bug E fix). + // later ESC — including the reset above — aborts it) so the racing + // live tail's continuation completes it exactly as live, instead of + // rendering literally (Bug E fix / #7329). writeReplayData(snapshot.pendingEscapeTailAnsi) } hiddenRendererStateDirty = false @@ -5772,7 +5810,9 @@ export function connectPanePty( sendTerminalOscColorQueryReplies( pendingForegroundQuery.oscColorQueryData, pane.terminal, - (reply) => transport.sendInput(reply) + // Why: OSC color reply — immediate so the remote debounce cannot delay + // it past the querying program's read window (#7329). + (reply) => transport.sendInputImmediate(reply) ) } const restoreAppliesToCurrentPty = @@ -5913,12 +5953,45 @@ export function connectPanePty( // and only the freshest source belongs on screen. if (connectResult?.snapshot) { rememberReattachPayloadAgentSignal(connectResult.snapshot, { fullScreenReplay: true }) + // Why: the daemon serializes its grid with soft-wrapped lines as + // continuous text. Replaying that at a different column count rewraps + // rows one cell early/late (bug #7279). Replay at the snapshot's own + // dimensions first; safeFit below fits the pane back and resizes the + // remote PTY. Suppress the xterm->PTY forward so this layout-only + // resize does not SIGWINCH the live remote TUI. Mirrors + // applyMainBufferSnapshot. + const snapshotCols = connectResult.snapshotCols + const snapshotRows = connectResult.snapshotRows + const hasSnapshotDimensions = + typeof snapshotCols === 'number' && + typeof snapshotRows === 'number' && + Number.isFinite(snapshotCols) && + Number.isFinite(snapshotRows) && + snapshotCols > 0 && + snapshotRows > 0 + if ( + hasSnapshotDimensions && + (pane.terminal.cols !== snapshotCols || pane.terminal.rows !== snapshotRows) + ) { + suppressSnapshotReplayPtyResize = true + try { + pane.terminal.resize(snapshotCols, snapshotRows) + } finally { + suppressSnapshotReplayPtyResize = false + } + } writeReplayData('\x1b[2J\x1b[3J\x1b[H') writeReplayData(connectResult.snapshot) // Snapshot reattach keeps a live session, so avoid the broader mode // reset. We only drop renderer-owned state that should not leak from // replay bytes into the restored renderer terminal. writeReplayData(reattachReplayResetSequence()) + if (connectResult.pendingEscapeTailAnsi) { + // Why last: re-arm the daemon's dangling mid-escape sequence AFTER the + // reset (whose ESC would abort it) so the racing live continuation + // completes it instead of rendering literally (#7329). + writeReplayData(connectResult.pendingEscapeTailAnsi) + } sendFocusedReattachFocusInAfterReplay() if (connectResult.coldRestore) { // Snapshot superseded the cold-restore payload — ack it so the @@ -5999,6 +6072,21 @@ export function connectPanePty( // because the SSH provider isn't registered until after connect succeeds. if (connectionId) { const storeState = useAppStore.getState() + // Why: the SSH target was removed entirely (a ghost workspace). Reattaching + // can only fail with "SSH target not found", which surfaces a red "file an + // issue" banner for what is an expected user action. Skip reattach — the + // terminal overlay already shows a "host removed" state with a remove + // action. Runtime-owned targets aren't user-managed, so they're exempt. + // A target map that exists but omits this id means the target was removed. + // (Guard the map's presence for minimal test stubs that omit it; an absent + // map is "not hydrated", not "target gone".) + if ( + !isRuntimeOwnedSshTargetId(connectionId) && + storeState.sshTargetLabels instanceof Map && + !storeState.sshTargetLabels.has(connectionId) + ) { + return + } const restoredLeafSessionId = deps.restoredLeafId && deps.restoredPtyIdByLeafId ? (deps.restoredPtyIdByLeafId[deps.restoredLeafId] ?? null) diff --git a/src/renderer/src/components/terminal-pane/pty-transport-types.ts b/src/renderer/src/components/terminal-pane/pty-transport-types.ts index eae47abae..6cc404b84 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport-types.ts @@ -26,7 +26,7 @@ export type PtyBufferSnapshot = { /** Trailing incomplete escape sequence main's emulator ingested (a PTY read * ended mid-escape). Must be written LAST — after post-replay resets, right * before post-snapshot live chunks — so the continuation completes it - * exactly as live instead of rendering literal (Bug E). */ + * exactly as live instead of rendering literal (Bug E / #7329). */ pendingEscapeTailAnsi?: string } @@ -42,13 +42,20 @@ export type PtyConnectResult = { sessionExpired?: boolean coldRestore?: { scrollback: string; cwd: string } replay?: string + /** Trailing partial escape the daemon emulator held mid-parse; the reattach + * replay writes it LAST (after the reset) so a racing live continuation + * completes it instead of rendering literally (#7329). */ + pendingEscapeTailAnsi?: string } type PtyCallbacks = { onConnect?: () => void onDisconnect?: () => void onData?: (data: string, meta?: PtyDataMeta) => void - onReplayData?: (data: string, meta?: { clearBeforeReplay?: boolean }) => void + onReplayData?: ( + data: string, + meta?: { clearBeforeReplay?: boolean; pendingEscapeTailAnsi?: string } + ) => void onStatus?: (shell: string) => void onError?: (message: string, errors?: string[]) => void onExit?: (code: number) => void @@ -82,6 +89,13 @@ export type PtyTransport = { }) => void disconnect: () => void sendInput: (data: string) => boolean + // Why: latency-critical terminal query replies (CPR/DSR/DA/OSC color/pixel + // size) must skip input coalescing — a querying program reads them in raw + // mode with a short timeout, so a debounced reply lands on the shell prompt + // and corrupts input (#7329). Local transports already write promptly, so + // this is `sendInput` for them; the remote transport flushes pending input + // (preserving order) and sends the reply immediately. + sendInputImmediate: (data: string) => boolean sendInputAccepted?: (data: string) => Promise resize: ( cols: number, diff --git a/src/renderer/src/components/terminal-pane/pty-transport.test.ts b/src/renderer/src/components/terminal-pane/pty-transport.test.ts index ad09ceca6..3e0482049 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.test.ts @@ -1093,6 +1093,51 @@ describe('createIpcPtyTransport', () => { }) }) + it('threads the daemon pendingEscapeTailAnsi through the reattach connect result (#7329)', async () => { + // Why: the local daemon ships the mid-escape tail on the spawn/reattach + // result; dropping it here silently regressed the local half of #7329 + // (the consumer test injects at the transport boundary, so only this + // asserts the IPC threading). + const { createIpcPtyTransport } = await import('./pty-transport') + const spawnMock = vi.fn().mockResolvedValue({ + id: 'pty-reattach-tail', + isReattach: true, + snapshot: 'snapshot data', + snapshotCols: 80, + snapshotRows: 24, + pendingEscapeTailAnsi: '\x1b[3' + }) + + ;(globalThis as { window: typeof window }).window = { + ...originalWindow, + api: { + ...originalWindow?.api, + pty: { + ...originalWindow?.api?.pty, + spawn: spawnMock, + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn(), + onData: vi.fn(() => () => {}), + onReplay: vi.fn(() => () => {}), + onExit: vi.fn(() => () => {}) + } + } + } as unknown as typeof window + + const transport = createIpcPtyTransport() + const result = await transport.connect({ + url: '', + sessionId: 'pty-reattach-tail', + callbacks: {} + }) + + expect(result).toMatchObject({ + id: 'pty-reattach-tail', + pendingEscapeTailAnsi: '\x1b[3' + }) + }) + it('kills a PTY that finishes spawning after the transport was destroyed', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const spawnControls: { resolve: ((value: { id: string }) => void) | null } = { resolve: null } diff --git a/src/renderer/src/components/terminal-pane/pty-transport.ts b/src/renderer/src/components/terminal-pane/pty-transport.ts index c624edd01..f3e36cef8 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.ts @@ -90,6 +90,10 @@ type ProcessPtyOutputOptions = { replayingBufferedData?: boolean suppressAttentionEvents?: boolean clearBeforeReplay?: boolean + // Why: a mid-escape tail the daemon could not serialize. The replay consumer + // must write it LAST, after the post-replay reset, so the next live chunk + // completes it instead of rendering literally (#7329). + pendingEscapeTailAnsi?: string } type PendingPtySideEffect = { @@ -417,8 +421,16 @@ export function createPtyOutputProcessor({ // session into the live store. The parser still consumes the bytes so they // do not leak into xterm, we just suppress the callback. if (options.replayingBufferedData && callbacks.onReplayData) { - if (options.clearBeforeReplay === false) { - callbacks.onReplayData(data, { clearBeforeReplay: false }) + const replayMeta = { + ...(options.clearBeforeReplay === false ? { clearBeforeReplay: false } : {}), + ...(options.pendingEscapeTailAnsi + ? { pendingEscapeTailAnsi: options.pendingEscapeTailAnsi } + : {}) + } + // Why: preserve the bare-data call shape when there is no replay metadata, + // so eager-buffer replay (which passes neither) is unchanged. + if (Object.keys(replayMeta).length > 0) { + callbacks.onReplayData(data, replayMeta) } else { callbacks.onReplayData(data) } @@ -693,7 +705,8 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra isAlternateScreen: spawnResult.isAlternateScreen, sessionExpired: spawnResult.sessionExpired, coldRestore: spawnResult.coldRestore, - replay: spawnResult.replay + replay: spawnResult.replay, + pendingEscapeTailAnsi: spawnResult.pendingEscapeTailAnsi } satisfies PtyConnectResult } if (spawnResult.launchConfig) { @@ -871,6 +884,17 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra return inputWriteQueue.enqueue(ptyId, data) }, + // Why: the local write queue already drains a lone item in the same turn + // (no wall-clock debounce), so query replies are prompt without special + // handling. Kept as a distinct method so callers express intent and the + // remote transport can override with its flush-then-send behavior (#7329). + sendInputImmediate(data: string): boolean { + if (!connected || !ptyId) { + return false + } + return inputWriteQueue.enqueue(ptyId, data) + }, + ...(connectionId ? {} : { diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.ts index 8e1ee1b0a..48a37e4b9 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.ts @@ -8,6 +8,7 @@ import { export type RemoteRuntimePtyBatcher = { push: (data: string) => boolean + hasPendingValidation: () => boolean drain: () => Promise takePending: () => string flush: () => void @@ -145,6 +146,10 @@ export function createRemoteRuntimePtyTextBatcher( enqueueValidatedInput(data, tooLarge) return true }, + // Why: earlier input can be mid async byte-length validation and not yet in + // `pending`. `takePending()` cannot see it, so callers that must preserve + // byte order (sendInputImmediate) check this before bypassing the queue. + hasPendingValidation: (): boolean => validationTail !== null, drain, takePending, flush, diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts new file mode 100644 index 000000000..8060b32b7 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts @@ -0,0 +1,142 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../../../shared/clipboard-text' + +// Regression for #7329: terminal query replies must NOT sit behind the remote +// input debounce (REMOTE_TERMINAL_INPUT_FLUSH_MS). transport.sendInputImmediate +// sends without arming the 8ms timer, so a reply beats the querying program's +// raw-mode read window; transport.sendInput stays debounced for typed input. + +describe('remote transport sendInputImmediate (#7329)', () => { + const runtimeCall = vi.fn() + const runtimeSubscribe = vi.fn() + const subscriptionSendBinary = vi.fn() + let subscriptionCallbacks: { + onResponse: (response: unknown) => void + onBinary?: (bytes: Uint8Array) => void + onError?: (error: { code: string; message: string }) => void + onClose?: () => void + } | null = null + + beforeEach(() => { + vi.resetModules() + vi.doUnmock('../../runtime/remote-runtime-terminal-multiplexer') + vi.clearAllMocks() + subscriptionCallbacks = null + subscriptionSendBinary.mockReset() + runtimeCall.mockResolvedValue({ ok: true, result: { terminal: { handle: 'terminal-1' } } }) + runtimeSubscribe.mockImplementation( + async (_args: unknown, callbacks: typeof subscriptionCallbacks) => { + subscriptionCallbacks = callbacks + return { unsubscribe: vi.fn(), sendBinary: subscriptionSendBinary } + } + ) + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { call: runtimeCall, subscribe: runtimeSubscribe } + } + }) + }) + + function terminalSendCalls(): unknown[] { + return runtimeCall.mock.calls + .map((call) => call[0] as { method?: string; params?: { text?: string } }) + .filter((args) => args.method === 'terminal.send') + } + + it('sends a query reply immediately, but debounces typed input by 8ms', async () => { + vi.useFakeTimers() + try { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'tab-1', + leafId: 'pane:1' + }) + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: {} + }) + + // Typed input: debounced — nothing sent before the 8ms flush. + expect(transport.sendInput('yes')).toBe(true) + expect(terminalSendCalls()).toEqual([]) + + // Query reply (OSC 11 background color): sent immediately, no timer. + expect(transport.sendInputImmediate('\x1b]11;rgb:2828/2c2c/3434\x1b\\')).toBe(true) + await Promise.resolve() + + // The immediate send flushed pending typed input ahead of the reply + // (preserving byte order) in a single send, without advancing timers. + const sends = terminalSendCalls() as { params: { text: string } }[] + expect(sends).toHaveLength(1) + expect(sends[0]?.params.text).toBe('yes\x1b]11;rgb:2828/2c2c/3434\x1b\\') + } finally { + vi.useRealTimers() + } + }) + + it('sends an immediate reply even with no pending typed input', async () => { + vi.useFakeTimers() + try { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'tab-1', + leafId: 'pane:1' + }) + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: {} + }) + + expect(transport.sendInputImmediate('\x1b[3;1R')).toBe(true) // CPR reply + await Promise.resolve() + + const sends = terminalSendCalls() as { params: { text: string } }[] + expect(sends).toHaveLength(1) + expect(sends[0]?.params.text).toBe('\x1b[3;1R') + } finally { + vi.useRealTimers() + } + }) + + it('does not reorder a query reply ahead of a large paste still in async validation', async () => { + // #7736 review: a paste over the deferred-measurement threshold sits in the + // batcher's async validationTail (not in `pending`). sendInputImmediate must + // not send the reply ahead of it and reorder bytes on the wire. + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'tab-1', + leafId: 'pane:1' + }) + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: {} + }) + + // A paste above CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS forces the async + // validation path, so its bytes are captured in validationTail, not pending. + const paste = 'p'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1) + expect(transport.sendInput(paste)).toBe(true) + // Immediately (validation still pending) a TUI emits a CPR reply. + expect(transport.sendInputImmediate('\x1b[3;1R')).toBe(true) + + // Wait until the reply is actually flushed instead of sleeping a fixed + // interval: the reply legitimately trails the paste's async validation plus + // one debounce tick, and a fixed sleep raced that chain under CI load. + const combined = (): string => + (terminalSendCalls() as { params: { text: string } }[]).map((s) => s.params.text).join('') + await expect.poll(combined, { timeout: 5000, interval: 5 }).toContain('\x1b[3;1R') + + // The paste bytes must come before the reply — no reordering. + expect(combined().indexOf('p')).toBeLessThan(combined().indexOf('\x1b[3;1R')) + expect(combined()).toContain(`${paste}\x1b[3;1R`) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts new file mode 100644 index 000000000..8d7014697 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts @@ -0,0 +1,116 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamJson, + encodeTerminalStreamFrame, + encodeTerminalStreamJson, + encodeTerminalStreamText +} from '../../../../shared/terminal-stream-protocol' + +// Client-side wire regression for #7329: the daemon's pendingEscapeTailAnsi +// rides the SnapshotStart JSON frame. This drives REAL binary frames through +// the REAL multiplexer (decodeSnapshotInfo → onSnapshot meta) into the REAL +// transport (processData → onReplayData meta). The server-side counterpart is +// terminal-multiplex-escape-tail.test.ts; without this test the client half of +// the chain could silently drop the field and every suite stayed green. + +describe('remote transport snapshot escape-tail threading (#7329)', () => { + const runtimeCall = vi.fn() + const runtimeSubscribe = vi.fn() + const subscriptionSendBinary = vi.fn() + let subscriptionCallbacks: { + onResponse: (response: unknown) => void + onBinary?: (bytes: Uint8Array) => void + onError?: (error: { code: string; message: string }) => void + onClose?: () => void + } | null = null + + beforeEach(() => { + vi.resetModules() + vi.doUnmock('../../runtime/remote-runtime-terminal-multiplexer') + vi.clearAllMocks() + subscriptionCallbacks = null + subscriptionSendBinary.mockReset() + runtimeCall.mockResolvedValue({ ok: true, result: { terminal: { handle: 'terminal-1' } } }) + runtimeSubscribe.mockImplementation( + async (_args: unknown, callbacks: typeof subscriptionCallbacks) => { + subscriptionCallbacks = callbacks + return { unsubscribe: vi.fn(), sendBinary: subscriptionSendBinary } + } + ) + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { call: runtimeCall, subscribe: runtimeSubscribe } + } + }) + }) + + it('delivers the SnapshotStart pendingEscapeTailAnsi to onReplayData meta', async () => { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'tab-1', + leafId: 'pane:1' + }) + const onReplayData = vi.fn() + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: { onReplayData } + }) + + // Complete the multiplexer handshake so the terminal stream subscribes. + await expect.poll(() => subscriptionCallbacks !== null, { timeout: 5000 }).toBe(true) + subscriptionCallbacks?.onResponse({ ok: true, result: { type: 'ready' } }) + + // The client allocates the terminal's stream id in its Subscribe payload. + await expect + .poll(() => subscriptionSendBinary.mock.calls.length, { timeout: 5000 }) + .toBeGreaterThan(0) + const subscribeFrame = subscriptionSendBinary.mock.calls + .map((call) => decodeTerminalStreamFrame(call[0] as Uint8Array)) + .find((frame) => frame?.opcode === TerminalStreamOpcode.Subscribe) + expect(subscribeFrame).toBeDefined() + const subscribePayload = decodeTerminalStreamJson<{ streamId: number }>(subscribeFrame!.payload) + const streamId = subscribePayload!.streamId + + // Server → client: initial snapshot whose emulator sat mid-escape. + const frames = [ + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.SnapshotStart, + streamId, + seq: 0, + payload: encodeTerminalStreamJson({ + cols: 80, + rows: 24, + seq: 7, + source: 'headless', + pendingEscapeTailAnsi: '\x1b[3' + }) + }), + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.SnapshotChunk, + streamId, + seq: 0, + payload: encodeTerminalStreamText('user@host:~$ ') + }), + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.SnapshotEnd, + streamId, + seq: 0, + payload: new Uint8Array(0) + }) + ] + for (const frame of frames) { + subscriptionCallbacks?.onBinary?.(frame) + } + + await expect.poll(() => onReplayData.mock.calls.length, { timeout: 5000 }).toBeGreaterThan(0) + expect(onReplayData).toHaveBeenCalledWith( + 'user@host:~$ ', + expect.objectContaining({ pendingEscapeTailAnsi: '\x1b[3' }) + ) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts index 148acb6c0..698059809 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts @@ -215,6 +215,115 @@ describe('createRemoteRuntimePtyTransport', () => { }) }) + it('re-derives the host session handle after a transport close instead of resubscribing the stale one', async () => { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const onPtySpawn = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'web-terminal-tab-1', + leafId: 'pane:1', + onPtySpawn + }) + + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: {} + }) + await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled()) + expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-1' }) + + // Why: while the tunnel was down the host re-minted this pane's handle; + // resubscribing the stale closure handle would bind the mirror to a + // different PTY (#7718). The transport must re-derive from the snapshot. + runtimeCall.mockImplementation(async (args: { method: string }) => + args.method === 'session.tabs.list' + ? { + ok: true, + result: { + worktree: 'wt-1', + publicationEpoch: 'epoch-1', + snapshotVersion: 2, + activeGroupId: null, + activeTabId: 'tab-1::pane:1', + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: 'tab-1::pane:1', + parentTabId: 'tab-1', + leafId: 'pane:1', + title: 'Terminal', + isActive: true, + status: 'ready', + terminal: 'terminal-2' + } + ] + } + } + : { ok: true, result: {} } + ) + const subscribeCallsBefore = runtimeSubscribe.mock.calls.length + + // The dedicated multiplex socket dies (liveness/close) → onTransportClose. + subscriptionCallbacks?.onClose?.() + + await vi.waitFor(() => + expect(runtimeSubscribe.mock.calls.length).toBeGreaterThan(subscribeCallsBefore) + ) + await vi.waitFor(() => + expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-2' }) + ) + expect(transport.getPtyId()).toContain('terminal-2') + expect(onPtySpawn).toHaveBeenCalledWith(expect.stringContaining('terminal-2')) + }) + + it('retires the mirror when the host no longer publishes the surface after a transport close', async () => { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const onPtyExit = vi.fn() + const onError = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'web-terminal-tab-1', + leafId: 'pane:1', + onPtyExit + }) + + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: { onError } + }) + await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled()) + + runtimeCall.mockImplementation(async (args: { method: string }) => + args.method === 'session.tabs.list' + ? { + ok: true, + result: { + worktree: 'wt-1', + publicationEpoch: 'epoch-1', + snapshotVersion: 2, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + } + : { ok: true, result: {} } + ) + + subscriptionCallbacks?.onClose?.() + + // Why: no red xterm error — retire quietly and let the next session-tabs + // snapshot drive respawn/removal. + await vi.waitFor(() => expect(onPtyExit).toHaveBeenCalledWith('remote:env-1@@terminal-1')) + expect(transport.getPtyId()).toBeNull() + expect(onError).not.toHaveBeenCalled() + }) + it('does not close host-owned terminal handles attached from session snapshots', async () => { const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') const transport = createRemoteRuntimePtyTransport('env-1', { diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts index f739ef970..e9a8f361f 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts @@ -182,6 +182,16 @@ export function createRemoteRuntimePtyTransport( return null } + async function listHostSessionHandle(hostTabId: string): Promise { + if (!worktreeId) { + return null + } + const listed = await callRuntime('session.tabs.list', { + worktree: toRuntimeWorktreeSelector(worktreeId) + }) + return findReadyHostSessionHandle(listed, hostTabId) + } + async function attachHostSessionMirror( options: Parameters[0] ): Promise { @@ -280,7 +290,9 @@ export function createRemoteRuntimePtyTransport( } return true } catch (error) { - storedCallbacks.onError?.(runtimeTerminalErrorMessage(error)) + // Why: stale-handle errors must retire the mirror (recoverable via the + // next snapshot) rather than dead-end in a red xterm banner (#7718). + handleRemoteTerminalError(error) return false } } @@ -298,7 +310,7 @@ export function createRemoteRuntimePtyTransport( text, client: { id: clientId, type: 'desktop' } }).catch((error) => { - storedCallbacks.onError?.(runtimeTerminalErrorMessage(error)) + handleRemoteTerminalError(error) }) }) @@ -371,6 +383,31 @@ export function createRemoteRuntimePtyTransport( storedCallbacks.onError?.(message) } + // Why: after a transport drop the host may have re-minted this pane's + // handle (reconnect, epoch or PTY change). Re-derive it from the current + // session snapshot instead of resubscribing the stale closure value, which + // would mirror (and type into) whatever PTY now sits behind it (#7718). + async function resubscribeAfterTransportClose(previousHandle: string): Promise { + if (tabId && isWebTerminalSurfaceTabId(tabId)) { + const nextHandle = await listHostSessionHandle(toHostSessionTabId(tabId)) + if (destroyed || !connected || handle !== previousHandle) { + return + } + if (!nextHandle) { + // Why: the host no longer publishes this surface; retire quietly and + // let the next session-tabs snapshot drive respawn/removal. + retireRemoteTerminalId() + return + } + if (nextHandle !== previousHandle) { + handle = nextHandle + remotePtyId = toRemoteRuntimePtyId(nextHandle, currentRuntimeEnvironmentId) + onPtySpawn?.(remotePtyId) + } + } + await subscribeToHandle() + } + async function subscribeToHandle(): Promise { if (!handle) { return @@ -391,11 +428,16 @@ export function createRemoteRuntimePtyTransport( outputProcessor.processData(data, storedCallbacks, undefined, meta) } }, - onSnapshot: (data) => { - if (data && isCurrentSubscription()) { + onSnapshot: (data, meta) => { + // Why: a snapshot with no body can still carry a pending mid-escape + // tail that must be replayed so the next live chunk completes it. + if ((data || meta?.pendingEscapeTailAnsi) && isCurrentSubscription()) { outputProcessor.processData(data, storedCallbacks, { replayingBufferedData: true, - suppressAttentionEvents: true + suppressAttentionEvents: true, + ...(meta?.pendingEscapeTailAnsi + ? { pendingEscapeTailAnsi: meta.pendingEscapeTailAnsi } + : {}) }) } }, @@ -448,10 +490,9 @@ export function createRemoteRuntimePtyTransport( } resubscribing = true const resubscribeHandle = handle - const resubscribePtyId = remotePtyId - void subscribeToHandle() + void resubscribeAfterTransportClose(resubscribeHandle) .catch((error) => { - if (isCurrentRemoteTerminal(resubscribeHandle, resubscribePtyId)) { + if (!destroyed && connected && handle) { handleRemoteTerminalError(error) } }) @@ -616,6 +657,49 @@ export function createRemoteRuntimePtyTransport( return inputBatcher.push(data) }, + // Why: terminal query replies (CPR/DSR/DA/OSC color/pixel size) are read by + // the querying program in raw mode with a short timeout. The 8ms input + // debounce makes the reply miss that window, so it lands on the shell prompt + // and is echoed literally / spliced into typed input (#7329). Flush any + // pending batched input first so byte order is preserved, then send the + // reply immediately without arming the debounce timer. + sendInputImmediate(data: string): boolean { + const targetHandle = handle + if (!connected || !targetHandle) { + return false + } + if (!data) { + return true + } + // Why: earlier input (e.g. a large paste) may still be in async byte-length + // validation, so it is captured in the batcher's validationTail and NOT in + // takePending(). Bypassing the queue here would send the reply ahead of it + // and reorder bytes on the wire. In that rare window, route the reply + // through the batcher's ordered queue and flush what is already validated; + // the reply lands right after the pending input once its validation + // resolves. Order correctness beats the immediacy that the debounce + // normally trades away. + if (inputBatcher.hasPendingValidation()) { + const accepted = inputBatcher.push(data) + inputBatcher.flush() + return accepted + } + const pending = inputBatcher.takePending() + const text = `${pending}${data}` + const stream = getCurrentMultiplexedStream(targetHandle) + if (stream?.sendInput(text)) { + return true + } + void callRuntime('terminal.send', { + terminal: targetHandle, + text, + client: { id: clientId, type: 'desktop' } + }).catch((error) => { + handleRemoteTerminalError(error) + }) + return true + }, + sendInputAccepted: sendInputAcceptedToRuntime, resize(cols: number, rows: number): boolean { diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts index e8b59a3a4..b42304cb8 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts @@ -31,13 +31,15 @@ type FakeManager = { getPanes: ReturnType resumeRendering: ReturnType scheduleRevealRepaint: ReturnType + scheduleRevealPresent: ReturnType } function createManager(order: string[] = []): FakeManager { return { getPanes: vi.fn(() => []), resumeRendering: vi.fn(() => order.push('resume-rendering')), - scheduleRevealRepaint: vi.fn(() => order.push('reveal-repaint')) + scheduleRevealRepaint: vi.fn(() => order.push('reveal-repaint')), + scheduleRevealPresent: vi.fn(() => order.push('reveal-present')) } } @@ -79,13 +81,52 @@ describe('resumeTerminalVisibility reveal repaint', () => { expect(order).toEqual(['resume-rendering', 'reveal-repaint']) }) - it('schedules the repaint on window-wake recovery', () => { + it('schedules the atlas-clearing repaint on genuine wake recovery', () => { const manager = createManager() recoverVisibleTerminalWindowWake({ manager: manager as never as PaneManager, - isActive: false + isActive: false, + clearGlyphAtlases: true }) expect(manager.scheduleRevealRepaint).toHaveBeenCalledTimes(1) + expect(manager.scheduleRevealPresent).not.toHaveBeenCalled() + }) + + it('clears shared glyph atlases only on genuine wake recovery', async () => { + const { resetAndRefreshAllTerminalWebglAtlases } = vi.mocked( + await import('@/lib/pane-manager/pane-manager-registry') + ) + const manager = createManager() + recoverVisibleTerminalWindowWake({ + manager: manager as never as PaneManager, + isActive: false, + clearGlyphAtlases: true + }) + + expect(resetAndRefreshAllTerminalWebglAtlases).toHaveBeenCalledTimes(1) + }) + + it('keeps the warm glyph atlas on plain-refocus recovery', async () => { + // Deliberate reversal of the #6354 focus-clear: wiping the shared atlas on + // every refocus forces a mass re-rasterization that can hit xterm's atlas + // page-merge race (#4480) and garble streaming panes. Focus recovery must + // resume rendering and present WITHOUT the atlas-clearing reveal repaint — + // scheduleRevealRepaint clears each pane's (shared) atlas, so the refocus + // path must route to the atlas-preserving present instead. + const { resetAndRefreshAllTerminalWebglAtlases } = vi.mocked( + await import('@/lib/pane-manager/pane-manager-registry') + ) + const manager = createManager() + recoverVisibleTerminalWindowWake({ + manager: manager as never as PaneManager, + isActive: false, + clearGlyphAtlases: false + }) + + expect(resetAndRefreshAllTerminalWebglAtlases).not.toHaveBeenCalled() + expect(manager.resumeRendering).toHaveBeenCalledTimes(1) + expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1) + expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled() }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts index 0c821e5d0..d1a0cc9e2 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts @@ -40,6 +40,7 @@ type HideTerminalVisibilityResult = { type RecoverVisibleTerminalWindowWakeArgs = { manager: PaneManager isActive: boolean + clearGlyphAtlases: boolean } export function resumeTerminalVisibility({ @@ -123,7 +124,8 @@ export function hideTerminalVisibility({ export function recoverVisibleTerminalWindowWake({ manager, - isActive + isActive, + clearGlyphAtlases }: RecoverVisibleTerminalWindowWakeArgs): void { // Why: macOS screensaver/display wake can leave xterm visible but with a // stale renderer/input surface; Orca's own hidden-state resume never runs. @@ -138,8 +140,19 @@ export function recoverVisibleTerminalWindowWake({ fitPanes(manager) } enforceTerminalViewportIntents(manager) - resetAndRefreshAllTerminalWebglAtlases() - manager.scheduleRevealRepaint() + if (clearGlyphAtlases) { + // Why: only a genuine wake may wipe the shared glyph atlas. The wipe makes + // every same-config pane re-rasterize at once, and xterm's atlas page-merge + // clear-model flag is consumed by one renderer (xterm.js #4480), so panes + // that lose that race paint garbled glyphs mid-stream. + resetAndRefreshAllTerminalWebglAtlases() + manager.scheduleRevealRepaint() + } else { + // Why: the reveal repaint clears each pane's texture atlas (a shared, + // same-config wipe), so a plain refocus must use the atlas-preserving + // present instead — otherwise it re-arms the same mid-stream garble race. + manager.scheduleRevealPresent() + } } function requestLightTabBacklogRecovery(manager: PaneManager): void { diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts index 0ad8f80d1..f8355d8b3 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts @@ -131,6 +131,7 @@ function useMountForFileDrop( resumeRendering: ReturnType resetWebglTextureAtlases: ReturnType scheduleRevealRepaint: ReturnType + scheduleRevealPresent: ReturnType suspendRendering: ReturnType getActivePane: ReturnType } @@ -148,6 +149,7 @@ function useMountForFileDrop( resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => null) } @@ -225,6 +227,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(() => order.push('resume')), resetWebglTextureAtlases: vi.fn(() => order.push('reset-atlas')), scheduleRevealRepaint: vi.fn(() => order.push('reveal-repaint')), + scheduleRevealPresent: vi.fn(() => order.push('reveal-present')), refreshAllPanes: vi.fn(() => order.push('refresh')), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), @@ -313,6 +316,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), refreshAllPanes: vi.fn(), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), @@ -393,6 +397,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), refreshAllPanes: vi.fn(), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), @@ -455,6 +460,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), refreshAllPanes: vi.fn(), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), @@ -509,6 +515,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), refreshAllPanes: vi.fn(), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), @@ -587,6 +594,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => ({ id: 1, terminal: { name: 'terminal-a' } })) } @@ -619,6 +627,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), getActivePane: vi.fn(() => null), @@ -672,18 +681,22 @@ describe('useTerminalPaneGlobalEffects', () => { expect(mocks.enforceTerminalCurrentScrollIntent).toHaveBeenLastCalledWith(terminalA) }) - it('clears WebGL texture atlases when the active visible terminal regains focus', () => { + it('keeps the shared glyph atlas warm on plain window refocus', () => { const manager = { getPanes: vi.fn(() => []), resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => null) } - // Why: focus recovery resets every registered manager (shared glyph - // atlas), so the fake manager observes the reset through the registry. + // Why: deliberate reversal of the #6354 focus-clear. A refocus atlas wipe + // forces every pane to re-rasterize at once, and xterm's page-merge + // clear-model flag is consumed by a single renderer (#4480), so panes that + // lose the race paint garbled glyphs while an agent streams. Focus must + // stay a WebGL-retry + pane-scoped repaint boundary only. registerManagerForReset(manager) beginHookRender() useTerminalPaneGlobalEffects({ @@ -711,9 +724,18 @@ describe('useTerminalPaneGlobalEffects', () => { throw new Error('expected focus listener') } manager.resetWebglTextureAtlases.mockClear() + manager.scheduleRevealRepaint.mockClear() + manager.scheduleRevealPresent.mockClear() + listener(new Event('focus')) + listener(new Event('focus')) listener(new Event('focus')) - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) + // Count proof: repeated refocus performs zero shared-atlas wipes. It routes + // to the atlas-preserving present (scheduleRevealPresent), never the + // atlas-clearing reveal repaint, which would clear each pane's shared atlas. + expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled() + expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled() + expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(3) }) it('recovers visible terminal rendering and input when the window regains focus', () => { @@ -723,6 +745,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), refreshAllPanes: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => ({ id: 1, terminal })) @@ -757,6 +780,10 @@ describe('useTerminalPaneGlobalEffects', () => { manager.resumeRendering.mockClear() manager.resetWebglTextureAtlases.mockClear() manager.refreshAllPanes.mockClear() + // Clear the mount-time reveal spies so the assertions measure only the + // focus event, not the initial visibility resume. + manager.scheduleRevealRepaint.mockClear() + manager.scheduleRevealPresent.mockClear() mocks.fitAndFocusPanes.mockClear() mocks.flushTerminalOutput.mockClear() mocks.requestTerminalBacklogRecovery.mockClear() @@ -767,6 +794,59 @@ describe('useTerminalPaneGlobalEffects', () => { expect(mocks.flushTerminalOutput).toHaveBeenCalledWith(terminal, { maxChars: 64 * 1024 }) expect(manager.resumeRendering).toHaveBeenCalledTimes(1) expect(mocks.fitAndFocusPanes).toHaveBeenCalledWith(manager) + // Why: refocus recovery is atlas-preserving — no shared-atlas reset, no + // registry-wide repaint, and no atlas-clearing reveal repaint; the + // atlas-preserving present covers stale pixels. + expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled() + expect(manager.refreshAllPanes).not.toHaveBeenCalled() + expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled() + expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1) + }) + + it('clears WebGL texture atlases when the OS resumes', () => { + const manager = { + getPanes: vi.fn(() => []), + resumeRendering: vi.fn(), + resetWebglTextureAtlases: vi.fn(), + scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), + refreshAllPanes: vi.fn(), + suspendRendering: vi.fn(), + getActivePane: vi.fn(() => null) + } + const captured: { onSystemResumed: (() => void) | null } = { onSystemResumed: null } + const unsubscribeSystemResumed = vi.fn() + ;( + window.api.ui as unknown as { onSystemResumed: (callback: () => void) => () => void } + ).onSystemResumed = vi.fn((callback: () => void) => { + captured.onSystemResumed = callback + return unsubscribeSystemResumed + }) + + registerManagerForReset(manager) + beginHookRender() + useTerminalPaneGlobalEffects({ + tabId: 'tab-1', + worktreeId: 'wt-1', + isActive: true, + isVisible: true, + isSyncFitEnabled: true, + paneCount: 0, + managerRef: { current: manager as never }, + containerRef: { current: null }, + paneTransportsRef: { current: new Map() }, + isActiveRef: { current: false }, + isVisibleRef: { current: false }, + toggleExpandPane: vi.fn() + }) + + expect(captured.onSystemResumed).toBeTypeOf('function') + manager.resetWebglTextureAtlases.mockClear() + manager.refreshAllPanes.mockClear() + captured.onSystemResumed?.() + + // Why: OS resume is a genuine wake — GPU state may be stale without a + // context-loss event, so the shared-atlas clear and full repaint still run. expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) }) @@ -788,6 +868,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => null) } @@ -843,6 +924,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => null) } @@ -889,6 +971,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => pane) } @@ -945,6 +1028,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), getActivePane: vi.fn(() => pane) } @@ -1061,6 +1145,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), getActivePane: vi.fn(() => null) @@ -1095,6 +1180,7 @@ describe('useTerminalPaneGlobalEffects', () => { resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), + scheduleRevealPresent: vi.fn(), suspendRendering: vi.fn(), fitAllPanes: vi.fn(), getActivePane: vi.fn(() => null) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts index 3174c443c..f70a85dcf 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts @@ -49,11 +49,19 @@ describe('useTerminalWindowWakeRecovery', () => { ) } - it('runs the same wake recovery for system resume as for window focus', () => { + it('clears the glyph atlas on system resume but not on plain window focus', () => { + // Why: wiping the shared WebGL glyph atlas on a plain refocus provokes + // xterm's page-merge race and paints garbled glyphs (#7604). Only a genuine + // OS resume — which can leave a stale renderer surface — clears the atlas. renderWakeRecoveryHook() window.dispatchEvent(new Event('focus')) expect(recoverVisibleTerminalWindowWakeMock).toHaveBeenCalledTimes(1) + expect(recoverVisibleTerminalWindowWakeMock).toHaveBeenNthCalledWith(1, { + manager, + isActive: true, + clearGlyphAtlases: false + }) expect(systemResumedCallback).toBeTypeOf('function') systemResumedCallback?.() @@ -61,11 +69,9 @@ describe('useTerminalWindowWakeRecovery', () => { expect(recoverVisibleTerminalWindowWakeMock).toHaveBeenCalledTimes(2) expect(recoverVisibleTerminalWindowWakeMock).toHaveBeenNthCalledWith(2, { manager, - isActive: true + isActive: true, + clearGlyphAtlases: true }) - expect(recoverVisibleTerminalWindowWakeMock.mock.calls[1]).toEqual( - recoverVisibleTerminalWindowWakeMock.mock.calls[0] - ) }) it('unsubscribes from the system resume event on cleanup', () => { diff --git a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts index 0f922235b..5168afc68 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts @@ -20,6 +20,7 @@ export function useTerminalWindowWakeRecovery({ return } let wakeRecoveryFrameId: number | null = null + let settledClearGlyphAtlases = false const cancelScheduledWakeRecovery = (): void => { if (wakeRecoveryFrameId === null || typeof cancelAnimationFrame !== 'function') { wakeRecoveryFrameId = null @@ -28,9 +29,12 @@ export function useTerminalWindowWakeRecovery({ cancelAnimationFrame(wakeRecoveryFrameId) wakeRecoveryFrameId = null } - const recoverVisibleWake = (): void => { + const recoverVisibleWake = (clearGlyphAtlases: boolean): void => { // Focus and visibility often fire together; keep one immediate recovery and one settled RAF pass. if (wakeRecoveryFrameId !== null) { + // Why: a pending settled pass may only upgrade in strength — a plain + // focus that lands after a genuine wake must not skip its atlas clear. + settledClearGlyphAtlases ||= clearGlyphAtlases return } const manager = managerRef.current @@ -39,27 +43,43 @@ export function useTerminalWindowWakeRecovery({ } recoverVisibleTerminalWindowWake({ manager, - isActive: isActiveRef.current + isActive: isActiveRef.current, + clearGlyphAtlases }) if (typeof requestAnimationFrame !== 'function') { return } + settledClearGlyphAtlases = clearGlyphAtlases wakeRecoveryFrameId = requestAnimationFrame(() => { wakeRecoveryFrameId = null + const clearGlyphAtlasesOnSettle = settledClearGlyphAtlases + settledClearGlyphAtlases = false const settledManager = managerRef.current if (!settledManager || !isVisibleRef.current) { return } recoverVisibleTerminalWindowWake({ manager: settledManager, - isActive: isActiveRef.current + isActive: isActiveRef.current, + clearGlyphAtlases: clearGlyphAtlasesOnSettle }) }) } - const onFocus = (): void => recoverVisibleWake() + // Why: plain refocus (alt-tab, devtools) is frequent and often lands while + // an agent streams; wiping the shared glyph atlas then provokes xterm's + // page-merge race and paints garbled glyphs. Focus recovery keeps the warm + // atlas: it only retries WebGL attach, refits, and repaints pane-scoped. + const onFocus = (): void => recoverVisibleWake(false) const onVisibilityChange = (): void => { if (typeof document !== 'undefined' && document.visibilityState === 'visible') { - recoverVisibleWake() + recoverVisibleWake(true) + } + } + // Why: Linux has no window-occlusion tracking, so visibilitychange never + // fires around system suspend; the main process broadcasts OS resume. + const onSystemResumed = (): void => { + if (typeof document === 'undefined' || document.visibilityState === 'visible') { + recoverVisibleWake(true) } } window.addEventListener('focus', onFocus) @@ -67,10 +87,13 @@ export function useTerminalWindowWakeRecovery({ document.addEventListener('visibilitychange', onVisibilityChange) } // Why: a focus-preserving display wake fires neither focus nor - // visibilitychange, so main relays powerMonitor resume over IPC. Same - // recovery path — it resumes pane rendering and clears the WebGL latch. + // visibilitychange, so main relays powerMonitor resume over IPC. Genuine + // wake clears the WebGL glyph atlas (clearGlyphAtlases=true via + // onSystemResumed) — the latch-clearing recovery — unlike plain refocus. const unsubscribeSystemResumed = - window.api?.ui.onSystemResumed?.(() => recoverVisibleWake()) ?? null + typeof window.api?.ui?.onSystemResumed === 'function' + ? window.api.ui.onSystemResumed(onSystemResumed) + : null return () => { cancelScheduledWakeRecovery() window.removeEventListener('focus', onFocus) diff --git a/src/renderer/src/hooks/metadata-request-cache.test.ts b/src/renderer/src/hooks/metadata-request-cache.test.ts index 89644e5a8..7770aca96 100644 --- a/src/renderer/src/hooks/metadata-request-cache.test.ts +++ b/src/renderer/src/hooks/metadata-request-cache.test.ts @@ -49,19 +49,88 @@ describe('metadata-request-cache', () => { expect(getFreshMetadata(store, 'repo-b:labels')?.data).toEqual(['b']) }) - it('does not cache failed requests', async () => { + it('paces failed requests with a short negative TTL instead of refetching immediately', async () => { const store = createMetadataRequestStore() const fetcher = vi .fn<() => Promise>() .mockRejectedValueOnce(new Error('network')) .mockResolvedValueOnce(['triage']) - await expect(loadMetadata(store, 'repo:labels', fetcher)).rejects.toThrow('network') - await expect(loadMetadata(store, 'repo:labels', fetcher)).resolves.toEqual(['triage']) + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 1_000)).rejects.toThrow( + 'network' + ) + // Within the failure TTL the cached rejection is reused without a fetch. + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 2_000)).rejects.toThrow( + 'network' + ) + expect(fetcher).toHaveBeenCalledTimes(1) + // Past the failure TTL the key becomes fetchable again. + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 11_000)).resolves.toEqual([ + 'triage' + ]) expect(fetcher).toHaveBeenCalledTimes(2) }) + it('a success clears the remembered failure for its key', async () => { + const store = createMetadataRequestStore() + const fetcher = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error('network')) + .mockResolvedValueOnce(['triage']) + + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 1_000)).rejects.toThrow( + 'network' + ) + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 12_000)).resolves.toEqual([ + 'triage' + ]) + expect(store.failures.has('repo:labels')).toBe(false) + }) + + it('keeps failure entries isolated per key and bounded', async () => { + const store = createMetadataRequestStore() + await expect( + loadMetadata( + store, + 'repo-a:labels', + () => Promise.reject(new Error('down')), + () => 1_000 + ) + ).rejects.toThrow('down') + + const fetcherB = vi.fn(() => Promise.resolve(['ok'])) + await expect(loadMetadata(store, 'repo-b:labels', fetcherB, () => 1_000)).resolves.toEqual([ + 'ok' + ]) + expect(fetcherB).toHaveBeenCalledTimes(1) + }) + + it('does not record failures from a cleared generation', async () => { + const store = createMetadataRequestStore() + let rejectRequest: (error: Error) => void = () => {} + const pending = loadMetadata( + store, + 'repo:labels', + () => + new Promise((_resolve, reject) => { + rejectRequest = reject + }), + () => 1_000 + ) + + clearMetadataRequestStore(store) + rejectRequest(new Error('stale failure')) + await expect(pending).rejects.toThrow('stale failure') + expect(store.failures.size).toBe(0) + + const fetcher = vi.fn(() => Promise.resolve(['fresh'])) + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 1_500)).resolves.toEqual([ + 'fresh' + ]) + expect(fetcher).toHaveBeenCalledTimes(1) + }) + it('does not let stale in-flight responses repopulate after clear', async () => { const store = createMetadataRequestStore() let resolveRequest: (value: string[]) => void = () => {} diff --git a/src/renderer/src/hooks/metadata-request-cache.ts b/src/renderer/src/hooks/metadata-request-cache.ts index 20df229f0..033f5e984 100644 --- a/src/renderer/src/hooks/metadata-request-cache.ts +++ b/src/renderer/src/hooks/metadata-request-cache.ts @@ -1,11 +1,19 @@ const METADATA_TTL = 300_000 // 5 min const MAX_METADATA_CACHE_ENTRIES = 500 +// Why: an unreachable provider/runtime fails every consumer render; without a +// negative cache each settlement re-issues the fetch, which storms a dead +// remote. Failures are remembered briefly so retries are paced, not disabled — +// short enough that a recovered provider is picked up within seconds. +const METADATA_FAILURE_TTL = 10_000 +const MAX_METADATA_FAILURE_ENTRIES = 200 type CachedMetadata = { data: T; fetchedAt: number } +type CachedMetadataFailure = { error: unknown; failedAt: number } export type MetadataRequestStore = { cache: Map> inflight: Map> + failures: Map generation: number } @@ -13,6 +21,7 @@ export function createMetadataRequestStore(): MetadataRequestStore { return { cache: new Map(), inflight: new Map(), + failures: new Map(), generation: 0 } } @@ -21,6 +30,7 @@ export function clearMetadataRequestStore(store: MetadataRequestStore): vo store.generation += 1 store.cache.clear() store.inflight.clear() + store.failures.clear() } function pruneMetadataCache( @@ -55,6 +65,37 @@ export function getFreshMetadata( return entry } +function pruneMetadataFailures( + store: MetadataRequestStore, + now: number, + maxEntries = MAX_METADATA_FAILURE_ENTRIES +): void { + for (const [key, entry] of store.failures) { + if (now - entry.failedAt >= METADATA_FAILURE_TTL) { + store.failures.delete(key) + } + } + if (store.failures.size <= maxEntries) { + return + } + const sorted = [...store.failures.entries()].sort((a, b) => b[1].failedAt - a[1].failedAt) + for (const [key] of sorted.slice(maxEntries)) { + store.failures.delete(key) + } +} + +export function getRecentMetadataFailure( + store: MetadataRequestStore, + key: string, + now = Date.now() +): CachedMetadataFailure | null { + const entry = store.failures.get(key) + if (!entry || now - entry.failedAt >= METADATA_FAILURE_TTL) { + return null + } + return entry +} + export function loadMetadata( store: MetadataRequestStore, key: string, @@ -71,6 +112,11 @@ export function loadMetadata( return inflight } + const recentFailure = getRecentMetadataFailure(store, key, now()) + if (recentFailure) { + return Promise.reject(recentFailure.error) + } + // Why: clearMetadataRequestStore invalidates auth/repo boundaries; late // responses from the previous generation must not repopulate the cache. const generation = store.generation @@ -79,6 +125,7 @@ export function loadMetadata( if (store.generation === generation) { const fetchedAt = now() store.cache.set(key, { data, fetchedAt }) + store.failures.delete(key) // Why: these module-level stores are reused across dialogs and // repo/runtime keys; TTL controls freshness but also needs pruning so // long sessions do not retain stale metadata indefinitely. @@ -86,6 +133,14 @@ export function loadMetadata( } return data }) + .catch((error: unknown) => { + if (store.generation === generation) { + const failedAt = now() + store.failures.set(key, { error, failedAt }) + pruneMetadataFailures(store, failedAt) + } + throw error + }) .finally(() => { if (store.inflight.get(key) === promise) { store.inflight.delete(key) diff --git a/src/renderer/src/hooks/runtime-client-events-sync.test.ts b/src/renderer/src/hooks/runtime-client-events-sync.test.ts index 3546b5b7b..c3ebb64cd 100644 --- a/src/renderer/src/hooks/runtime-client-events-sync.test.ts +++ b/src/renderer/src/hooks/runtime-client-events-sync.test.ts @@ -135,7 +135,8 @@ describe('createRuntimeClientEventsSync', () => { getDesiredEnvironmentIds: () => desired, subscribe, onEvent: vi.fn(), - retryDelayMs: 10 + retryDelayMs: 10, + random: () => 1 }) sync.sync() @@ -156,4 +157,212 @@ describe('createRuntimeClientEventsSync', () => { vi.useRealTimers() } }) + + it('backs off exponentially with a cap while an environment keeps failing', async () => { + vi.useFakeTimers() + try { + const subscribe = vi.fn( + (): Promise => + Promise.reject(new Error('unreachable')) + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => ['A'], + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + retryMaxDelayMs: 40, + random: () => 1 + }) + + sync.sync() + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(1) + + // Attempt 2 after 10ms (base). + await vi.advanceTimersByTimeAsync(10) + expect(subscribe).toHaveBeenCalledTimes(2) + // Attempt 3 after 20ms more (doubled) — not before. + await vi.advanceTimersByTimeAsync(19) + expect(subscribe).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(subscribe).toHaveBeenCalledTimes(3) + // Attempt 4 after 40ms more (doubled again, hits cap). + await vi.advanceTimersByTimeAsync(40) + expect(subscribe).toHaveBeenCalledTimes(4) + // Attempt 5 stays at the 40ms cap. + await vi.advanceTimersByTimeAsync(39) + expect(subscribe).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(1) + expect(subscribe).toHaveBeenCalledTimes(5) + } finally { + vi.useRealTimers() + } + }) + + it('applies jitter below the full backoff delay', async () => { + vi.useFakeTimers() + try { + const subscribe = vi.fn( + (): Promise => + Promise.reject(new Error('unreachable')) + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => ['A'], + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + random: () => 0 + }) + + sync.sync() + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(1) + + // random() => 0 halves the delay: retry at 5ms instead of 10ms. + await vi.advanceTimersByTimeAsync(5) + expect(subscribe).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + } + }) + + it('starts a fresh backoff epoch after a successful subscribe', async () => { + vi.useFakeTimers() + try { + let desired = ['A'] + let failing = true + const unsubscribe = vi.fn() + const subscribe = vi.fn((): Promise => { + if (failing) { + return Promise.reject(new Error('unreachable')) + } + return Promise.resolve({ unsubscribe }) + }) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => desired, + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + random: () => 1 + }) + + // Two failures escalate the delay to 20ms. + sync.sync() + await Promise.resolve() + await vi.advanceTimersByTimeAsync(10) + expect(subscribe).toHaveBeenCalledTimes(2) + + // Third attempt succeeds — failure count resets. + failing = false + await vi.advanceTimersByTimeAsync(20) + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(3) + + // Env leaves and re-enters the desired set, then fails again: the first + // retry is back at the 10ms base, not the escalated delay. + desired = [] + sync.sync() + desired = ['A'] + failing = true + sync.sync() + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(9) + expect(subscribe).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(1) + expect(subscribe).toHaveBeenCalledTimes(5) + } finally { + vi.useRealTimers() + } + }) + + it('an external sync retries a waiting environment immediately (recovery path)', async () => { + vi.useFakeTimers() + try { + const subscribe = vi.fn( + (): Promise => + Promise.reject(new Error('unreachable')) + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => ['A'], + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10_000, + random: () => 1 + }) + + sync.sync() + // Let the rejection propagate through the then/catch chain so the retry + // timer is armed before the external sync fires. + await vi.advanceTimersByTimeAsync(0) + expect(subscribe).toHaveBeenCalledTimes(1) + + // A reachable-set transition calls sync() directly; the pending backoff + // timer must not delay this immediate re-attempt. + sync.sync() + await vi.advanceTimersByTimeAsync(0) + expect(subscribe).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + } + }) + + it('does not carry a stale failure count when a rejection lands after the env left the set', async () => { + vi.useFakeTimers() + try { + // 'B' stays pending forever so the desired set is never empty and the + // generation never bumps — this is what lets A's late rejection still be + // observed by its .catch (the exact leave-while-in-flight race). + let desired = ['A', 'B'] + const aRejecters: ((error: Error) => void)[] = [] + let aAttempts = 0 + const subscribe = vi.fn( + (environmentId: string): Promise => { + if (environmentId === 'B') { + return new Promise(() => {}) + } + aAttempts += 1 + return new Promise((_resolve, reject) => { + aRejecters.push(reject) + }) + } + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => desired, + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + random: () => 1 + }) + + sync.sync() + expect(aAttempts).toBe(1) + + // A leaves the desired set while its subscribe is still in flight. + desired = ['B'] + sync.sync() + + // A's in-flight subscribe rejects now, after it is no longer desired. + aRejecters[0](new Error('unreachable')) + await vi.advanceTimersByTimeAsync(0) + + // A re-enters and its fresh subscribe (attempt 2) also fails. + desired = ['A', 'B'] + sync.sync() + await vi.advanceTimersByTimeAsync(0) + expect(aAttempts).toBe(2) + aRejecters[1](new Error('unreachable')) + await vi.advanceTimersByTimeAsync(0) + + // The first retry after re-entry must use the base delay (10ms). A stale + // count from the discarded rejection would have doubled it to 20ms. + await vi.advanceTimersByTimeAsync(9) + expect(aAttempts).toBe(2) + await vi.advanceTimersByTimeAsync(1) + await Promise.resolve() + expect(aAttempts).toBe(3) + } finally { + vi.useRealTimers() + } + }) }) diff --git a/src/renderer/src/hooks/runtime-client-events-sync.ts b/src/renderer/src/hooks/runtime-client-events-sync.ts index 128341dac..b23b6f01e 100644 --- a/src/renderer/src/hooks/runtime-client-events-sync.ts +++ b/src/renderer/src/hooks/runtime-client-events-sync.ts @@ -14,7 +14,11 @@ export type RuntimeClientEventsSyncDeps = { onError: (error: unknown) => void ) => Promise onEvent: (environmentId: string, event: RuntimeClientEvent) => void + /** Base retry delay; doubles per consecutive failure up to retryMaxDelayMs. */ retryDelayMs?: number + retryMaxDelayMs?: number + /** Injectable randomness for deterministic backoff-jitter tests. */ + random?: () => number } export type RuntimeClientEventsSync = { @@ -46,7 +50,10 @@ export function createRuntimeClientEventsSync( const subscriptions = new Map void>() const pending = new Set() const retryTimers = new Map>() + const consecutiveFailures = new Map() const retryDelayMs = deps.retryDelayMs ?? 1_000 + const retryMaxDelayMs = deps.retryMaxDelayMs ?? 30_000 + const random = deps.random ?? Math.random let generation = 0 const clearRetryTimer = (environmentId: string): void => { @@ -58,6 +65,17 @@ export function createRuntimeClientEventsSync( retryTimers.delete(environmentId) } + const nextRetryDelayMs = (environmentId: string): number => { + // Why: a flat retry hammers an unreachable runtime with one socket dial per + // tick forever. Exponential-with-cap keeps transient blips fast to recover + // while a dead host settles at one attempt per cap window; jitter keeps + // multiple envs from dialing in lockstep. External sync() (desired/reachable + // transitions) still retries immediately, so recovery is not delayed. + const failures = consecutiveFailures.get(environmentId) ?? 0 + const capped = Math.min(retryDelayMs * 2 ** Math.max(0, failures - 1), retryMaxDelayMs) + return capped * (0.5 + random() * 0.5) + } + const scheduleRetry = (environmentId: string, subscribeGeneration: number): void => { if (retryTimers.has(environmentId)) { return @@ -73,7 +91,7 @@ export function createRuntimeClientEventsSync( return } sync() - }, retryDelayMs) + }, nextRetryDelayMs(environmentId)) retryTimers.set(environmentId, retryTimer) } @@ -88,6 +106,7 @@ export function createRuntimeClientEventsSync( clearTimeout(retryTimer) } retryTimers.clear() + consecutiveFailures.clear() } const sync = (): void => { @@ -98,6 +117,11 @@ export function createRuntimeClientEventsSync( } clearRetryTimer(environmentId) } + for (const environmentId of consecutiveFailures.keys()) { + if (!desiredIds.has(environmentId)) { + consecutiveFailures.delete(environmentId) + } + } for (const [environmentId, unsubscribe] of subscriptions) { if (desiredIds.has(environmentId)) { @@ -139,14 +163,25 @@ export function createRuntimeClientEventsSync( subscription.unsubscribe() return } + consecutiveFailures.delete(environmentId) subscriptions.set(environmentId, subscription.unsubscribe) }) .catch((error) => { pending.delete(environmentId) if (subscribeGeneration === generation) { console.warn('[runtime-client-events] failed to subscribe:', error) + // Why: only track a failure when we will actually retry this env. + // A failure that lands after the env left the desired set must not + // leave a stale count that makes its first retry after re-entry skip + // the base delay. if (deps.getDesiredEnvironmentIds().includes(environmentId)) { + consecutiveFailures.set( + environmentId, + (consecutiveFailures.get(environmentId) ?? 0) + 1 + ) scheduleRetry(environmentId, subscribeGeneration) + } else { + consecutiveFailures.delete(environmentId) } } }) diff --git a/src/renderer/src/hooks/useEditorExternalWatch.test.ts b/src/renderer/src/hooks/useEditorExternalWatch.test.ts index cc375bb51..90029020d 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch.test.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch.test.ts @@ -521,6 +521,179 @@ describe('createExternalWatchEventHandler tombstone coalescing', () => { dispose() }) + it('marks a dirty edit tab changed-on-disk instead of reloading it', () => { + const dirtyFile = { + ...fileNotes, + isDirty: true + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [dirtyFile], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyFile] as never) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + vi.advanceTimersByTime(200) + + expect(setExternalMutation).toHaveBeenCalledWith('file-notes', 'changed') + expect(notifyEditorExternalFileChange).not.toHaveBeenCalled() + dispose() + }) + + it('still reloads a clean sibling diff tab when the edit tab for the path is dirty', () => { + const dirtyFile = { + ...fileNotes, + isDirty: true + } + const cleanDiffTab = { + id: 'diff-notes', + worktreeId: 'wt-1', + worktreePath: '/repo', + filePath: '/repo/notes.md', + relativePath: 'notes.md', + mode: 'diff' as const, + diffSource: 'unstaged' as const, + isDirty: false + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [dirtyFile, cleanDiffTab], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyFile, cleanDiffTab] as never) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + vi.advanceTimersByTime(200) + + expect(setExternalMutation).toHaveBeenCalledWith('file-notes', 'changed') + expect(notifyEditorExternalFileChange).toHaveBeenCalledWith({ + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'notes.md', + runtimeEnvironmentId: null + }) + dispose() + }) + + it('does not mark a dirty tab for the echo of Orca’s own save', async () => { + const dirtyFile = { + ...fileNotes, + isDirty: true + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [dirtyFile], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyFile] as never) + const readFile = vi.fn().mockResolvedValue({ content: 'orca save', isBinary: false }) + vi.stubGlobal('window', { api: { fs: { readFile } } }) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + recordSelfWrite('/repo/notes.md', 'orca save') + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + await vi.advanceTimersByTimeAsync(100) + + expect(setExternalMutation).not.toHaveBeenCalledWith('file-notes', 'changed') + dispose() + }) + + it('marks a dirty tab when a genuine external write lands inside the self-write TTL', async () => { + const dirtyFile = { + ...fileNotes, + isDirty: true + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [dirtyFile], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyFile] as never) + const readFile = vi.fn().mockResolvedValue({ content: 'agent content', isBinary: false }) + vi.stubGlobal('window', { api: { fs: { readFile } } }) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + recordSelfWrite('/repo/notes.md', 'orca save') + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + await vi.advanceTimersByTimeAsync(100) + + expect(setExternalMutation).toHaveBeenCalledWith('file-notes', 'changed') + dispose() + }) + + it('shares one echo-verification read across a burst of watcher payloads', async () => { + const dirtyFile = { + ...fileNotes, + isDirty: true + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [dirtyFile], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyFile] as never) + const readFile = vi.fn().mockResolvedValue({ content: 'agent content', isBinary: false }) + vi.stubGlobal('window', { api: { fs: { readFile } } }) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + recordSelfWrite('/repo/notes.md', 'orca save') + // Why: SSH poll + event streams can deliver several payloads for one + // write; each verification is a full-file read, so a burst must share + // the in-flight read instead of stacking network round-trips. + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + await vi.advanceTimersByTimeAsync(100) + + expect(readFile).toHaveBeenCalledTimes(1) + expect(setExternalMutation).toHaveBeenCalledWith('file-notes', 'changed') + dispose() + }) + + it('marks a lone dirty unstaged-diff tab changed-on-disk', () => { + const dirtyDiffTab = { + id: 'diff-notes', + worktreeId: 'wt-1', + worktreePath: '/repo', + filePath: '/repo/notes.md', + relativePath: 'notes.md', + mode: 'diff' as const, + diffSource: 'unstaged' as const, + isDirty: true + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [dirtyDiffTab], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyDiffTab] as never) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + vi.advanceTimersByTime(200) + + expect(setExternalMutation).toHaveBeenCalledWith('diff-notes', 'changed') + expect(notifyEditorExternalFileChange).not.toHaveBeenCalled() + dispose() + }) + + it('does not let an update event clear a changed-on-disk mark while the tab stays dirty', () => { + const dirtyChangedFile = { + ...fileNotes, + isDirty: true, + externalMutation: 'changed' as const + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [dirtyChangedFile], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([dirtyChangedFile] as never) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }])) + vi.advanceTimersByTime(200) + + expect(setExternalMutation).not.toHaveBeenCalledWith('file-notes', null) + dispose() + }) + it('does not reload a branch-compare combined diff for working-tree changes', () => { const branchDiffTab = { id: 'wt-1::all-diffs::branch', diff --git a/src/renderer/src/hooks/useEditorExternalWatch.ts b/src/renderer/src/hooks/useEditorExternalWatch.ts index 157b91df0..9fd18202b 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch.ts @@ -8,6 +8,7 @@ import { basename, joinPath } from '@/lib/path' import { getExternalFileChangeRelativePath } from '@/components/right-sidebar/useFileExplorerWatch' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' import { + canAutoSaveOpenFile, getOpenFilesForExternalFileChange, isExternalReloadableEditorTab, isWorkingTreeCombinedDiffTab, @@ -28,6 +29,7 @@ import { type WorktreeFileChangeEventDetail } from './worktree-file-change-event' import { isGitRepoKind } from '../../../shared/repo-kind' +import { markFileChangedOnDisk } from '@/components/editor/editor-changed-on-disk-mark' // Why: atomic-write patterns (Claude Code's Edit tool, editors like vim, // VSCode) land as a short burst of `update` events — or `delete + create` on @@ -545,7 +547,10 @@ export function createExternalWatchEventHandler( // Why: if a previously-deleted file reappears at the same path (e.g. // the user ran `git checkout`), clear the tombstone so the tab returns // to its normal state and any non-dirty content gets reloaded below. - // `createOrUpdatePaths` was collected above. + // `createOrUpdatePaths` was collected above. Scoped to deleted/renamed: + // a 'changed' mark means the file was rewritten while the tab was dirty, + // so a further update event must not clear it — it resolves via reload, + // save, or the reload path below. if (createOrUpdatePaths.size > 0) { const state = useAppStore.getState() for (const file of state.openFiles) { @@ -553,7 +558,7 @@ export function createExternalWatchEventHandler( file.worktreeId === target.worktreeId && openFileRuntimeOwner(file) === target.runtimeEnvironmentId && (file.mode === 'edit' || file.mode === 'markdown-preview') && - file.externalMutation && + (file.externalMutation === 'deleted' || file.externalMutation === 'renamed') && createOrUpdatePaths.has(normalizeRuntimePathForComparison(file.filePath)) ) { state.setExternalMutation(file.id, null) @@ -637,11 +642,27 @@ export function createExternalWatchEventHandler( } continue } - if (matching.some((f) => f.isDirty)) { - if (hasCombinedDiffConsumer) { - scheduleDebouncedExternalReload(notification) + const dirtyMatches = matching.filter((f) => f.isDirty) + if (dirtyMatches.length > 0) { + // Why: an external write landing on a dirty tab must not vanish + // silently (issue #7265) — the user was left with a stale tab and a + // save that clobbered the newer disk content. Mark the tab so the + // editor shows a changed-on-disk banner with an explicit reload path. + scheduleChangedOnDiskMark( + target, + notification, + // Why: canAutoSaveOpenFile is exactly the set of tabs that can hold + // unsaved edits (edit + unstaged diff) — the tabs the banner serves. + dirtyMatches.filter((dirtyFile) => canAutoSaveOpenFile(dirtyFile)).map((f) => f.id) + ) + if (dirtyMatches.length === matching.length) { + if (hasCombinedDiffConsumer) { + scheduleDebouncedExternalReload(notification) + } + continue } - continue + // Clean sibling tabs (e.g. an unstaged diff of the same path) still + // reload below; every notification consumer skips dirty files. } const absolutePath = joinPath(notification.worktreePath, notification.relativePath) const recentSelfWrite = getRecentSelfWrite(absolutePath, target.runtimeEnvironmentId) @@ -665,6 +686,90 @@ export function createExternalWatchEventHandler( return { handleFsChanged, dispose } } +const inFlightEchoVerificationReads = new Map>() + +// Why: one save echo can arrive as a burst of watcher payloads (SSH poll + +// event streams), and each verification is a full-file read — on remote +// transports a network round-trip. Concurrent payloads for the same file +// share the in-flight read instead of stacking duplicates. +function readFileForEchoVerification(args: { + runtimeEnvironmentId: string | null | undefined + filePath: string + relativePath: string + worktreeId: string | null | undefined + connectionId: string | undefined +}): ReturnType { + const key = `${args.runtimeEnvironmentId ?? ''}::${args.connectionId ?? ''}::${args.filePath}` + let pending = inFlightEchoVerificationReads.get(key) + if (!pending) { + pending = readRuntimeFileContent({ + settings: args.runtimeEnvironmentId + ? { activeRuntimeEnvironmentId: args.runtimeEnvironmentId } + : null, + filePath: args.filePath, + relativePath: args.relativePath, + worktreeId: args.worktreeId ?? undefined, + connectionId: args.connectionId + }) + inFlightEchoVerificationReads.set(key, pending) + const release = (): void => { + if (inFlightEchoVerificationReads.get(key) === pending) { + inFlightEchoVerificationReads.delete(key) + } + } + pending.then(release, release) + } + return pending +} + +function markTabsChangedOnDisk(fileIds: string[], connectionId: string | undefined): void { + const state = useAppStore.getState() + for (const fileId of fileIds) { + const file = state.openFiles.find((f) => f.id === fileId) + // Why: echo verification resolves async — a save or reload may already + // have resolved the conflict; the helper only marks still-dirty tabs. + if (file) { + markFileChangedOnDisk(state, file, { connectionId, origin: 'live' }) + } + } +} + +function scheduleChangedOnDiskMark( + target: WatchedTarget, + notification: ExternalWatchNotification, + fileIds: string[] +): void { + if (fileIds.length === 0) { + return + } + const absolutePath = joinPath(notification.worktreePath, notification.relativePath) + const recentSelfWrite = getRecentSelfWrite(absolutePath, target.runtimeEnvironmentId) + // Why: the fs event may be the echo of Orca's own save racing keystrokes + // typed during the write. Marking on the echo would show a false "changed + // on disk" banner, so verify disk really differs from our last write. + if (!recentSelfWrite || recentSelfWrite.content === null) { + markTabsChangedOnDisk(fileIds, target.connectionId) + return + } + void readFileForEchoVerification({ + runtimeEnvironmentId: target.runtimeEnvironmentId, + filePath: absolutePath, + relativePath: notification.relativePath, + worktreeId: notification.worktreeId, + connectionId: target.connectionId + }) + .then((result) => { + if (result.isBinary || result.content !== recentSelfWrite.content) { + markTabsChangedOnDisk(fileIds, target.connectionId) + } + }) + .catch(() => { + // Why: unreadable disk state can't disprove an external change — keep + // the conflict visible rather than risk a silent overwrite. + markTabsChangedOnDisk(fileIds, target.connectionId) + }) +} + function scheduleSelfWriteAwareExternalReload( target: WatchedTarget, notification: ExternalWatchNotification, @@ -680,8 +785,8 @@ function scheduleSelfWriteAwareExternalReload( // Why: a recent self-write stamp only proves the path changed recently; an // agent can write a newer version inside the same TTL. Compare disk content // with the saved text so we suppress only the echo of Orca's own write. - void readRuntimeFileContent({ - settings: runtimeEnvironmentId ? { activeRuntimeEnvironmentId: runtimeEnvironmentId } : null, + void readFileForEchoVerification({ + runtimeEnvironmentId, filePath: file.filePath, relativePath: file.relativePath, worktreeId: file.worktreeId, @@ -706,7 +811,9 @@ function scheduleSelfWriteAwareExternalReload( function hasCleanExternalReloadTarget(notification: ExternalWatchNotification): boolean { const matching = getOpenFilesForExternalFileChange(useAppStore.getState().openFiles, notification) - return matching.length > 0 && matching.every((file) => !file.isDirty) + // Why: one clean target is enough — every notification consumer skips dirty + // files per-file, so a dirty sibling tab no longer vetoes the reload. + return matching.some((file) => !file.isDirty) } export function getOverflowExternalReloadTargets( diff --git a/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx b/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx index 4bec2a92d..4be71732d 100644 --- a/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx +++ b/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx @@ -122,4 +122,56 @@ describe('useGitHubSlugMetadata', () => { }) expect(renders).toBeLessThanOrEqual(4) }) + + it('does not re-issue a failed label fetch when a fresh settings object re-renders', async () => { + // Regression: with an unreachable provider, the failure setState re-rendered + // the consumer, the fresh settings identity re-armed the effect, and the hook + // re-issued the fetch each settlement — a render-paced request storm. + let renders = 0 + let error: string | null = null + apiMocks.listLabelsBySlug.mockRejectedValue(new Error('Could not connect')) + + function FailingLabelsProbe(): null { + renders += 1 + const metadata = useRepoLabelsBySlug('stablyai', 'orca', { + activeRuntimeEnvironmentId: null + }) + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + // Extra settlement rounds give a storm the chance to manifest. + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(apiMocks.listLabelsBySlug).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed assignee fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + apiMocks.listAssignableUsersBySlug.mockRejectedValue(new Error('Could not connect')) + + function FailingAssigneesProbe(): null { + renders += 1 + const metadata = useRepoAssigneesBySlug('stablyai', 'orca', ['jinwoo'], { + activeRuntimeEnvironmentId: null + }) + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(apiMocks.listAssignableUsersBySlug).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) }) diff --git a/src/renderer/src/hooks/useGitHubSlugMetadata.ts b/src/renderer/src/hooks/useGitHubSlugMetadata.ts index 26022191f..4b3c07696 100644 --- a/src/renderer/src/hooks/useGitHubSlugMetadata.ts +++ b/src/renderer/src/hooks/useGitHubSlugMetadata.ts @@ -44,12 +44,17 @@ export function useRepoLabelsBySlug( error: null }) const activeKeyRef = useRef(null) + // Why: parent selectors can pass a fresh settings object each render; keying + // the effect on the primitive env id keeps a failure's setState from re-running + // the effect and re-issuing the fetch in a render-paced loop (same class as + // the seedKey stabilization below). + const activeRuntimeEnvironmentId = settings?.activeRuntimeEnvironmentId ?? null useEffect(() => { if (!owner || !repo) { return } - const target = getActiveRuntimeTarget(settings) + const target = getActiveRuntimeTarget({ activeRuntimeEnvironmentId }) const key = target.kind === 'environment' ? `runtime:${target.environmentId}:${owner}/${repo}` @@ -57,8 +62,6 @@ export function useRepoLabelsBySlug( const cached = getFreshMetadata(slugLabelStore, key) if (cached) { - // Why: parent selectors can pass a fresh settings object each render; - // only the first cached hit for this key should write React state. if (activeKeyRef.current !== key) { setState({ data: cached.data, loading: false, error: null }) } @@ -110,7 +113,7 @@ export function useRepoLabelsBySlug( error: err instanceof Error ? err.message : 'Failed to load labels' })) }) - }, [owner, repo, settings]) + }, [owner, repo, activeRuntimeEnvironmentId]) return state } @@ -131,12 +134,15 @@ export function useRepoAssigneesBySlug( // the joined-string identity so the effect doesn't re-fire on every render // — this is the assignee popover refetch-storm fix. const seedKey = (seedLogins ?? []).slice().sort().join(',') + // Why: see useRepoLabelsBySlug — primitive env id keeps failure setState from + // re-arming the effect through a fresh settings object identity. + const activeRuntimeEnvironmentId = settings?.activeRuntimeEnvironmentId ?? null useEffect(() => { if (!owner || !repo) { return } - const target = getActiveRuntimeTarget(settings) + const target = getActiveRuntimeTarget({ activeRuntimeEnvironmentId }) const key = target.kind === 'environment' ? `runtime:${target.environmentId}:${owner}/${repo}#${seedKey}` @@ -202,7 +208,7 @@ export function useRepoAssigneesBySlug( error: err instanceof Error ? err.message : 'Failed to load assignees' })) }) - }, [owner, repo, seedKey, settings]) + }, [owner, repo, seedKey, activeRuntimeEnvironmentId]) return state } diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index b86a258bd..0623acbba 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -5,6 +5,7 @@ import { buildRuntimeClientEventEnvironmentKey, buildNewWorkspaceShortcutModalData, getNewlyConnectedRuntimeEnvironmentIds, + getNewlyDisconnectedRuntimeEnvironmentIds, getRuntimeProjectRefreshEnvironmentIds, openNewWorkspaceFromShortcut, resolveBrowserSessionTabTarget, @@ -57,6 +58,15 @@ describe('getNewlyConnectedRuntimeEnvironmentIds', () => { }) }) +describe('getNewlyDisconnectedRuntimeEnvironmentIds', () => { + it('returns only environments whose transport was just observed down', () => { + expect(getNewlyDisconnectedRuntimeEnvironmentIds(['env-a', 'env-b'], ['env-a'])).toEqual([ + 'env-b' + ]) + expect(getNewlyDisconnectedRuntimeEnvironmentIds(['env-a'], ['env-a', 'env-b'])).toEqual([]) + }) +}) + describe('getRuntimeProjectRefreshEnvironmentIds', () => { it('refreshes when an already-desired runtime becomes reachable', () => { expect( diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index af6295f29..e318b7120 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -83,6 +83,11 @@ import { attachMobileMarkdownBridge } from '@/runtime/mobile-markdown-bridge' import { closeMobileSessionTabInStore } from '@/runtime/mobile-session-tab-close' import { createWorktreeChangeRefreshQueue } from './worktree-change-refresh-queue' import { subscribeRuntimeClientEvents } from '@/runtime/runtime-client-events' +import { + applyRuntimeEnvironmentSshStateChanged, + hydrateRuntimeEnvironmentSshState +} from '@/runtime/runtime-environment-ssh-state' +import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' import { createRuntimeProjectRefreshScheduler } from './runtime-project-refresh-scheduler' import { createRuntimeClientEventsSync } from './runtime-client-events-sync' import { detectLanguage } from '@/lib/language-detect' @@ -769,6 +774,15 @@ export function getNewlyConnectedRuntimeEnvironmentIds( return [...new Set(next)].filter((environmentId) => !known.has(environmentId)) } +/** Ids in `previous` not in `next` — runtime environments whose transport was + * just observed down. Their mirrored SSH buckets get downgraded to unknown. */ +export function getNewlyDisconnectedRuntimeEnvironmentIds( + previous: readonly string[], + next: readonly string[] +): string[] { + return getNewlyConnectedRuntimeEnvironmentIds(next, previous) +} + export function getRuntimeProjectRefreshEnvironmentIds(args: { previousDesired: readonly string[] nextDesired: readonly string[] @@ -954,6 +968,13 @@ export function useIpcEvents(): void { const runtimeProjectRefreshScheduler = createRuntimeProjectRefreshScheduler({ refresh: async (environmentId) => { + if (!isPairedWebClientWindow()) { + // Why: mirrored SSH-backed workspaces read the owning environment's + // SSH bucket; refresh it whenever the environment (re)connects so a + // pre-drop snapshot can't keep a reconnect overlay stale. The web + // client mirrors host SSH state through the global store instead. + void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {}) + } const repos = await useAppStore.getState().fetchRuntimeEnvironmentRepos(environmentId) await refreshRuntimeProjectWorktrees(repos) await useAppStore.getState().fetchWorktreeLineage() @@ -963,11 +984,28 @@ export function useIpcEvents(): void { } }) + // Assigned later in this effect, next to the ssh.onStateChanged wiring; + // events can't fire before that because subscriptions attach asynchronously. + let handleSshStateChangedEvent: ((data: { targetId: string; state: unknown }) => void) | null = + null + const handleRuntimeClientEvent = (environmentId: string, event: RuntimeClientEvent): void => { if (event.type === 'reposChanged') { runtimeProjectRefreshScheduler.request(environmentId) return } + if (event.type === 'sshStateChanged') { + // Why: a paired web client mirrors host SSH state in the global store — + // its whole ssh.* API routes to that one host (STA-1468). A desktop + // client owns a local SSH surface those maps must keep describing, so a + // remote host's state goes into that environment's own bucket instead. + if (isPairedWebClientWindow()) { + handleSshStateChangedEvent?.({ targetId: event.targetId, state: event.state }) + } else { + applyRuntimeEnvironmentSshStateChanged(environmentId, event.targetId, event.state) + } + return + } if (event.type === 'worktreesChanged') { void ensureRuntimeEventRepoKnown(environmentId, event.repoId).then(() => worktreeChangeRefreshQueue.enqueue({ repoId: event.repoId }) @@ -992,7 +1030,17 @@ export function useIpcEvents(): void { const runtimeClientEventsSync = createRuntimeClientEventsSync({ getDesiredEnvironmentIds: getRuntimeClientEventEnvironmentIds, - subscribe: subscribeRuntimeClientEvents, + subscribe: (environmentId, onEvent, onError) => + subscribeRuntimeClientEvents(environmentId, onEvent, onError, () => { + if (isPairedWebClientWindow()) { + return + } + // Why: sshStateChanged events during the transport gap are lost, so + // the pre-drop bucket may hold a stale "connected". Downgrade to + // unknown, then refetch the authoritative state. + useAppStore.getState().markEnvironmentSshStateStale(environmentId) + void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {}) + }), onEvent: handleRuntimeClientEvent }) @@ -1033,6 +1081,13 @@ export function useIpcEvents(): void { })) { runtimeProjectRefreshScheduler.request(environmentId) } + for (const environmentId of getNewlyDisconnectedRuntimeEnvironmentIds( + reachableRuntimeEnvironmentIds, + nextReachableEnvironmentIds + )) { + // No-op when the environment has no SSH bucket (e.g. web client). + useAppStore.getState().markEnvironmentSshStateStale(environmentId) + } runtimeClientEventEnvironmentIds = nextEnvironmentIds runtimeClientEventEnvironmentKey = nextKey reachableRuntimeEnvironmentIds = nextReachableEnvironmentIds @@ -2516,6 +2571,14 @@ export function useIpcEvents(): void { try { const targets = await window.api.ssh.listTargets() useAppStore.getState().setSshTargetsMetadata(targets) + // Why: ghost-host UI (removed target still referenced by a workspace) + // shows a friendly name from the removal tombstones instead of the raw id. + try { + const removedLabels = await window.api.ssh.listRemovedTargetLabels() + useAppStore.getState().setRemovedSshTargetLabels(removedLabels) + } catch { + // Best-effort — a missing map just falls back to the raw target id. + } for (const target of targets) { const state = await window.api.ssh.getState({ targetId: target.id }) if (state) { @@ -2659,49 +2722,49 @@ export function useIpcEvents(): void { let sshTargetStateEventId = 0 const latestSshTargetStateEventByTargetId = new Map() - unsubs.push( - window.api.ssh.onStateChanged((data: { targetId: string; state: unknown }) => { - const store = useAppStore.getState() - const state = data.state as SshConnectionState - const stateEventId = ++sshTargetStateEventId - latestSshTargetStateEventByTargetId.set(data.targetId, stateEventId) - if (!store.sshTargetLabels.has(data.targetId)) { - // Why: targets added after boot aren't in the labels map, while - // removed targets can still race a final disconnect event. Confirm - // with main before mutating renderer state for an unknown target id. - window.api.ssh - .listTargets() - // Why: this refresh is now a deletion guard, not just a label fetch. - // Retry once so a transient IPC failure does not drop a real added-target event. - .catch(() => window.api.ssh.listTargets()) - .then((targets) => { - if (latestSshTargetStateEventByTargetId.get(data.targetId) !== stateEventId) { - return - } + handleSshStateChangedEvent = (data: { targetId: string; state: unknown }): void => { + const store = useAppStore.getState() + const state = data.state as SshConnectionState + const stateEventId = ++sshTargetStateEventId + latestSshTargetStateEventByTargetId.set(data.targetId, stateEventId) + if (!store.sshTargetLabels.has(data.targetId)) { + // Why: targets added after boot aren't in the labels map, while + // removed targets can still race a final disconnect event. Confirm + // with main before mutating renderer state for an unknown target id. + window.api.ssh + .listTargets() + // Why: this refresh is now a deletion guard, not just a label fetch. + // Retry once so a transient IPC failure does not drop a real added-target event. + .catch(() => window.api.ssh.listTargets()) + .then((targets) => { + if (latestSshTargetStateEventByTargetId.get(data.targetId) !== stateEventId) { + return + } + latestSshTargetStateEventByTargetId.delete(data.targetId) + const latestStore = useAppStore.getState() + if (!targets.some((target) => target.id === data.targetId)) { + // Why: disconnect/state events can race after target removal. + // Treat absence from main's target list as deletion, not a new target. + latestStore.clearRemovedSshTargetState(data.targetId) + return + } + latestStore.setSshTargetsMetadata(targets) + applySshConnectionStateChange(data.targetId, state) + }) + .catch(() => { + if (latestSshTargetStateEventByTargetId.get(data.targetId) === stateEventId) { latestSshTargetStateEventByTargetId.delete(data.targetId) - const latestStore = useAppStore.getState() - if (!targets.some((target) => target.id === data.targetId)) { - // Why: disconnect/state events can race after target removal. - // Treat absence from main's target list as deletion, not a new target. - latestStore.clearRemovedSshTargetState(data.targetId) - return - } - latestStore.setSshTargetsMetadata(targets) applySshConnectionStateChange(data.targetId, state) - }) - .catch(() => { - if (latestSshTargetStateEventByTargetId.get(data.targetId) === stateEventId) { - latestSshTargetStateEventByTargetId.delete(data.targetId) - applySshConnectionStateChange(data.targetId, state) - } - }) - return - } + } + }) + return + } - latestSshTargetStateEventByTargetId.delete(data.targetId) - applySshConnectionStateChange(data.targetId, state) - }) - ) + latestSshTargetStateEventByTargetId.delete(data.targetId) + applySshConnectionStateChange(data.targetId, state) + } + + unsubs.push(window.api.ssh.onStateChanged(handleSshStateChangedEvent)) let remoteWorkspaceClientId: string | null = null let remoteWorkspaceClientIdPromise: Promise | null = null diff --git a/src/renderer/src/hooks/useIssueMetadata.test.tsx b/src/renderer/src/hooks/useIssueMetadata.test.tsx new file mode 100644 index 000000000..e7e6dda6d --- /dev/null +++ b/src/renderer/src/hooks/useIssueMetadata.test.tsx @@ -0,0 +1,153 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + clearLinearMetadataCache, + useTeamLabels, + useTeamMembers, + useTeamStates +} from './useIssueMetadata' + +const linearMocks = vi.hoisted(() => ({ + linearTeamStates: vi.fn(), + linearTeamLabels: vi.fn(), + linearTeamMembers: vi.fn() +})) + +vi.mock('@/runtime/runtime-linear-client', () => ({ + linearTeamStates: linearMocks.linearTeamStates, + linearTeamLabels: linearMocks.linearTeamLabels, + linearTeamMembers: linearMocks.linearTeamMembers +})) + +vi.mock('@/runtime/runtime-rpc-client', () => ({ + callRuntimeRpc: vi.fn(), + getActiveRuntimeTarget: (settings?: { activeRuntimeEnvironmentId?: string | null } | null) => + settings?.activeRuntimeEnvironmentId + ? { kind: 'environment', environmentId: settings.activeRuntimeEnvironmentId } + : { kind: 'local' } +})) + +const roots: Root[] = [] + +async function flushEffects(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +function renderProbe(element: React.ReactNode): void { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + roots.push(root) + act(() => { + root.render(element) + }) +} + +describe('useIssueMetadata Linear hooks', () => { + beforeEach(() => { + clearLinearMetadataCache() + linearMocks.linearTeamStates.mockReset() + linearMocks.linearTeamLabels.mockReset() + linearMocks.linearTeamMembers.mockReset() + }) + + afterEach(() => { + roots.splice(0).forEach((root) => { + act(() => root.unmount()) + }) + document.body.replaceChildren() + }) + + it('does not loop when cached team-state metadata is read with a fresh settings object', async () => { + let renders = 0 + let states: unknown[] = [] + linearMocks.linearTeamStates.mockResolvedValue([{ id: 's1', name: 'Todo' }]) + + function StatesProbe(): null { + renders += 1 + // Fresh settings object each render — the storm trigger. + const metadata = useTeamStates('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + states = metadata.data + return null + } + + renderProbe() + await flushEffects() + + expect(states).toEqual([{ id: 's1', name: 'Todo' }]) + expect(linearMocks.linearTeamStates).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed team-state fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + linearMocks.linearTeamStates.mockRejectedValue(new Error('Could not connect')) + + function StatesProbe(): null { + renders += 1 + const metadata = useTeamStates('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(linearMocks.linearTeamStates).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed team-label fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + linearMocks.linearTeamLabels.mockRejectedValue(new Error('Could not connect')) + + function LabelsProbe(): null { + renders += 1 + const metadata = useTeamLabels('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(linearMocks.linearTeamLabels).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed team-member fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + linearMocks.linearTeamMembers.mockRejectedValue(new Error('Could not connect')) + + function MembersProbe(): null { + renders += 1 + const metadata = useTeamMembers('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(linearMocks.linearTeamMembers).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) +}) diff --git a/src/renderer/src/hooks/useIssueMetadata.ts b/src/renderer/src/hooks/useIssueMetadata.ts index ea1e306ca..4bd89dbb6 100644 --- a/src/renderer/src/hooks/useIssueMetadata.ts +++ b/src/renderer/src/hooks/useIssueMetadata.ts @@ -231,13 +231,18 @@ export function useTeamStates( error: null }) const activeKeyRef = useRef(null) + // Why: parents can pass a fresh settings object each render; keying the effect + // on the derived cache key keeps a failure's setState from re-arming the fetch + // in a render-paced loop. The ref carries the latest settings for the call. + const settingsRef = useRef(settings) + settingsRef.current = settings + const cacheKey = teamId ? linearMetadataCacheKey(teamId, settings, workspaceId) : null useEffect(() => { - if (!teamId) { + if (!teamId || !cacheKey) { return } - const cacheKey = linearMetadataCacheKey(teamId, settings, workspaceId) const cached = getFreshMetadata(linearStateStore, cacheKey) if (cached) { if (activeKeyRef.current !== cacheKey) { @@ -256,7 +261,7 @@ export function useTeamStates( error: null })) loadMetadata(linearStateStore, cacheKey, () => - linearTeamStates(settings, teamId, workspaceId).then( + linearTeamStates(settingsRef.current, teamId, workspaceId).then( (states) => states as LinearWorkflowState[] ) ) @@ -277,7 +282,7 @@ export function useTeamStates( error: err instanceof Error ? err.message : 'Failed to load states' })) }) - }, [settings, teamId, workspaceId]) + }, [cacheKey, teamId, workspaceId]) return state } @@ -293,13 +298,17 @@ export function useTeamLabels( error: null }) const activeKeyRef = useRef(null) + // Why: see useTeamStates — cache-key deps + latest-settings ref stop the + // failure-setState render loop. + const settingsRef = useRef(settings) + settingsRef.current = settings + const cacheKey = teamId ? linearMetadataCacheKey(teamId, settings, workspaceId) : null useEffect(() => { - if (!teamId) { + if (!teamId || !cacheKey) { return } - const cacheKey = linearMetadataCacheKey(teamId, settings, workspaceId) const cached = getFreshMetadata(linearLabelStore, cacheKey) if (cached) { if (activeKeyRef.current !== cacheKey) { @@ -318,7 +327,9 @@ export function useTeamLabels( error: null })) loadMetadata(linearLabelStore, cacheKey, () => - linearTeamLabels(settings, teamId, workspaceId).then((labels) => labels as LinearLabel[]) + linearTeamLabels(settingsRef.current, teamId, workspaceId).then( + (labels) => labels as LinearLabel[] + ) ) .then((data) => { if (activeKeyRef.current !== requestKey) { @@ -337,7 +348,7 @@ export function useTeamLabels( error: err instanceof Error ? err.message : 'Failed to load labels' })) }) - }, [settings, teamId, workspaceId]) + }, [cacheKey, teamId, workspaceId]) return state } @@ -353,13 +364,17 @@ export function useTeamMembers( error: null }) const activeKeyRef = useRef(null) + // Why: see useTeamStates — cache-key deps + latest-settings ref stop the + // failure-setState render loop. + const settingsRef = useRef(settings) + settingsRef.current = settings + const cacheKey = teamId ? linearMetadataCacheKey(teamId, settings, workspaceId) : null useEffect(() => { - if (!teamId) { + if (!teamId || !cacheKey) { return } - const cacheKey = linearMetadataCacheKey(teamId, settings, workspaceId) const cached = getFreshMetadata(linearMemberStore, cacheKey) if (cached) { if (activeKeyRef.current !== cacheKey) { @@ -378,7 +393,9 @@ export function useTeamMembers( error: null })) loadMetadata(linearMemberStore, cacheKey, () => - linearTeamMembers(settings, teamId, workspaceId).then((members) => members as LinearMember[]) + linearTeamMembers(settingsRef.current, teamId, workspaceId).then( + (members) => members as LinearMember[] + ) ) .then((data) => { if (activeKeyRef.current !== requestKey) { @@ -397,7 +414,7 @@ export function useTeamMembers( error: err instanceof Error ? err.message : 'Failed to load members' })) }) - }, [settings, teamId, workspaceId]) + }, [cacheKey, teamId, workspaceId]) return state } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index d15a81c46..d0dc2e8de 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Connect to Orca", "mobileScopeRejected": "This QR code grants limited (mobile) access. To use the full web app, open the browser access link from Settings → Runtime Environments → Share this Orca server → New Link." }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "Agent Session History is not available for this execution host." + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "Resume from history is only available in local workspaces.", "openLocalWorkspace": "Open a local workspace before resuming a session.", "sessionQueued": "Session queued", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "sessionHostMismatchUnsupported": "This session belongs to a different host. Drop it onto a workspace on the same host.", "localSessionSshWorkspaceUnsupported": "This session's history is stored on this machine, so it can't resume in an SSH workspace. Drop it onto a local workspace instead." }, @@ -9648,9 +9650,7 @@ "logPath": "Log path", "originalPaneUnavailable": "Original pane is no longer available.", "worktreeUnavailable": "Worktree is no longer available.", - "runtimeBrowseLocalHistory": "Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "sessionHostMismatchUnsupported": "This session belongs to a different host. Open a workspace on the same host to resume it.", "localSessionSshWorkspaceUnsupported": "This session's history is stored on this machine, so it can't resume in an SSH workspace. Open a local workspace instead." }, @@ -11522,6 +11522,24 @@ }, "richMarkdownLargeTextPaste": { "tooLarge": "Paste is too large." + }, + "ExternalFileChangeBanner": { + "7c41e90d12": "This file changed on disk while you have unsaved edits. Saving will overwrite the newer disk content.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "5c02de9b31": "Reloaded from disk", + "d1e830fa22": "Undo", + "90b2ce7d43": "Compare" + }, + "ExternalFileChangeCompareDialog": { + "4b8de20a11": "File changed on disk", + "90cc31e4d7": "Disk version on the left, your unsaved edits on the right.", + "8fe30ab254": "Reading file from disk...", + "e2b1cd0393": "Could not read the file from disk: {{value0}}", + "b6cf20d514": "The file on disk is binary — no text comparison available.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "2c8f1e07b9": "Loading comparison..." } }, "diff": { @@ -11711,7 +11729,7 @@ "f2d0c22d67": "Delete annotation {{value0}}", "11c5084aa2": "Clear annotations", "734e4343ec": "Clear browser annotations", - "95af781091": "Send feedback to a new agent", + "95af781091": "Send feedback to an agent", "ac39b9366b": "Send", "a3508d7e6e": "{{value0}} annotation{{value1}} ready. Select another element or copy all feedback.", "f796c774a4": "Type a URL above to start browsing.", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 84d5a861a..8923d561d 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Conectar con Orca", "mobileScopeRejected": "Este código QR solo da acceso limitado para móvil. Para usar la app web completa, abre el enlace para navegador desde Ajustes → Servidores remotos de Orca → Comparte este servidor Orca → Nuevo enlace." }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "El historial de sesiones de Agents no está disponible para este host de ejecución." + }, "web": { "preload": { "api": { @@ -1107,7 +1110,7 @@ }, "NewWorkspaceComposerCard": { "cbb47ee0dc": "Solo disponible para proyectos Git locales.", - "d861de981b": "Checkout sparse", + "d861de981b": "Sparse checkout", "090cfedeb4": "Escribe una nota", "f8728aa4f9": "Nota", "0ee17638fe": "Nombre del espacio de trabajo", @@ -2004,7 +2007,7 @@ "643d7e9496": "upstream", "51d1608920": "Origen", "cdc9bd64fa": "compacto", - "30b2c9df91": "Ascendente" + "30b2c9df91": "Upstream" }, "PRFilterDropdowns": { "979be3cf6b": "Asignado", @@ -2251,7 +2254,7 @@ "38ca0b1400": "Esto elimina permanentemente sus archivos locales. No puedes deshacer esto.", "c4f4782c02": "No sugerido", "0a2e3c7cba": "Revisar", - "e97e4580c7": "Sucio", + "e97e4580c7": "Con cambios", "9623a5107d": "commits sin push", "e8b3741ff7": "ignorado", "a9957007eb": "Ignorar {{value0}}", @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "Reanudar desde el historial solo está disponible en espacios de trabajo locales.", "openLocalWorkspace": "Abre un espacio de trabajo local antes de reanudar una sesión.", "sessionQueued": "Sesión en cola", - "runtimeWorkspacesUnsupported": "Reanudar desde el historial no está disponible en espacios de trabajo alojados en un host.", - "openSupportedWorkspace": "Abre un espacio de trabajo local o SSH antes de reanudar una sesión.", + "openSupportedWorkspace": "Abre un espacio de trabajo antes de reanudar una sesión.", "localSessionSshWorkspaceUnsupported": "El historial de esta sesión solo existe en este equipo. Para reanudarla, arrástrala a un workspace local. Los workspaces SSH no tienen acceso a ese historial.", "sessionHostMismatchUnsupported": "Esta sesión pertenece a un host diferente. Suéltala en un espacio de trabajo del mismo host." }, @@ -4655,9 +4657,9 @@ "566d9a99ab": "_token=…; minimax_group_id_v2=…", "f38b9cc4bd": "Reemplazar", "590a3130f9": "Guardar", - "79418c782a": "Abre platform.minimax.io/console/usage en tu navegador, inicia sesión y copia el encabezado Cookie de DevTools (Red → cualquier solicitud a remains → Cookie).", + "79418c782a": "Abre platform.minimax.io/console/usage en tu navegador, inicia sesión y, en DevTools, copia el valor del encabezado Cookie (Red → una solicitud de remains → Cookie).", "9dd50d3f75": "Avanzado", - "174fb408f9": "Deja estos valores predeterminados a menos que la actualización de uso de MiniMax apunte al workspace o modelo equivocado.", + "174fb408f9": "Deja estos valores predeterminados a menos que la actualización de uso de MiniMax apunte al espacio de trabajo o modelo equivocado.", "bf160bb6c0": "Anulación de Group ID", "b1e2743313": "Opcional. Déjalo en blanco para usar minimax_group_id_v2 de la cookie.", "0747d6391a": "Usar el Group ID de la cookie", @@ -4665,20 +4667,20 @@ "5cf4b0f85f": "Nombres de modelos opcionales separados por comas. Déjalo en general a menos que MiniMax devuelva un error específico del modelo.", "3c92b0d31c": "general", "0d8e77bc40": "Abrir consola", - "0b8c1c7e02": "Almacenado localmente", - "1fd1b1b6b4": "Cookie no configurada", + "0b8c1c7e02": "Almacenada localmente", + "1fd1b1b6b4": "Cookie sin configurar", "5e08b0fe57": "Se almacena localmente y se envía solo a platform.minimax.io para actualizar el uso.", "43d7a45b97": "Cómo copiar", - "b8a4f21c3e": "Pega el encabezado Cookie desde DevTools", + "b8a4f21c3e": "Pega el valor del encabezado Cookie de DevTools", "53f7b8c7a2": "Última actualización: {{value0}}", "31d24a4e87": "La cookie caduca cuando cierras sesión en el navegador.", "3a30aaf526": "ahora mismo", "f5d8d2a6a1": "Abre platform.minimax.io/console/usage en tu navegador e inicia sesión.", "24560fe830": "Abre DevTools.", - "4cab0fa42d": "Ve a la pestaña Red y activa Preserve log.", + "4cab0fa42d": "Ve a la pestaña Red y activa Conservar registro.", "bee4e63e1c": "Recarga la página.", "87f814af6f": "Filtra por remains y selecciona la solicitud coding_plan/remains.", - "435df0ee51": "En Request Headers, copia el valor de Cookie.", + "435df0ee51": "En Encabezados de solicitud, copia el valor del encabezado Cookie.", "7492fb3bba": "Pégalo aquí y haz clic en Guardar.", "9fec52de4b": "Cómo copiar la cookie", "4e32e030b2": "Se almacena localmente. Orca solo la envía a platform.minimax.io para actualizar el uso." @@ -6987,7 +6989,7 @@ "40e5c3c285": "kimi", "c927a155d5": "Muestra el uso de la suscripción de Kimi en la barra de estado.", "3a6c028ea8": "Uso de Kimi", - "25e51b62ee": "rate limit", + "25e51b62ee": "límite de uso", "d9e7cef86f": "cookie", "d16378a88f": "minimax", "e46178eb1b": "Muestra el uso de la suscripción de MiniMax en la barra de estado.", @@ -8689,13 +8691,13 @@ "DevToolsPane": { "nativeActionLayoutCheck": "Comprobación de diseño de acción nativa", "secondary": "Secundario", - "secondaryActionClicked": "Acción secundaria pulsada", + "secondaryActionClicked": "Clic en acción secundaria", "primaryAction": "Acción principal", - "primaryActionClicked": "Acción principal pulsada", + "primaryActionClicked": "Clic en acción principal", "branchHasChanges": "la rama tiene cambios", - "viewChangesClicked": "Ver cambios pulsado", - "forceDeleteClicked": "Forzar eliminación pulsado", - "devOnlyCallback": "Callback solo para desarrolladores.", + "viewChangesClicked": "Clic en Ver cambios", + "forceDeleteClicked": "Clic en Forzar eliminación", + "devOnlyCallback": "Callback solo para desarrollo.", "infoToast": "Toast informativo", "infoToastDescription": "Texto informativo largo sin acción explícita.", "localCanaryBehind": "La rama canary local está detrás de origin/canary", @@ -8707,14 +8709,14 @@ "errorToastDescription": "Texto de error largo sin acciones de recuperación.", "failedToSyncWorkspaceMetadata": "Error al sincronizar metadatos del espacio de trabajo", "nativeActionToast": "Toast de acción nativa", - "nativeActionToastDescription": "Utiliza las ranuras de acción y cancelación de Sonner.", + "nativeActionToastDescription": "Usa los slots de acción y cancelación de Sonner.", "deleteFailureToast": "Toast de error al eliminar", "deleteFailureToastDescription": "Pie personalizado con Ver y Forzar eliminación.", - "behindBaseRefToast": "Toast de retraso respecto a la rama base", + "behindBaseRefToast": "Toast de referencia base atrasada", "behindBaseRefToastDescription": "Aviso persistente con un enlace a Ajustes y una acción en el pie.", - "notificationPlayground": "Área de prueba de notificaciones", - "notificationPlaygroundDescription": "Disparadores solo para desarrolladores para comprobar el diseño de toasts, acciones de recuperación y ajuste de texto largo.", - "devOnly": "Solo desarrollo" + "notificationPlayground": "Panel de prueba de notificaciones", + "notificationPlaygroundDescription": "Disparadores solo para desarrollo para comprobar el diseño de toasts, acciones de recuperación y ajuste de texto largo.", + "devOnly": "Solo para desarrollo" }, "EphemeralVmRecipeRow": { "useInWorkspace": "Usar en el espacio de trabajo" @@ -8774,12 +8776,12 @@ "agentArgs": "Argumentos de la CLI", "commandTemplate": "Plantilla del comando", "more": "+{{count}} más", - "plural": "Los guardados globales no cambiarán {{count}} repositorios con sus propias recetas.", + "plural": "Guardar a nivel global no cambiará {{count}} repositorios con sus propias recetas.", "recipe": "Receta", "review": "Revisar", "reviewFirst": "Revisar primero", - "singular": "Los guardados globales no cambiarán 1 repositorio con su propia receta.", - "tooltipTitle": "Anulaciones del repositorio" + "singular": "Guardar a nivel global no cambiará 1 repositorio con su propia receta.", + "tooltipTitle": "Anulaciones de repositorio" } }, "right": { @@ -9248,8 +9250,8 @@ "c1a8f3e204": "1 commit por detrás de {{value0}}", "d2b9g4f315": "{{value0}} commits por detrás de {{value1}}", "e9c2a5d416": "A la par con {{value0}}", - "4b4a7de138": "Open review page in browser", - "createPrIntentCommitBlockedSummary": "Commit blocked: {{value0}} Fix the issue, then retry Create PR." + "4b4a7de138": "Abrir página de revisión en el navegador", + "createPrIntentCommitBlockedSummary": "Commit bloqueado: {{value0}} Corrige el problema y vuelve a intentar Crear PR." }, "SourceControlAgentActionDialog": { "8e856842d1": "No se pudo iniciar el agente seleccionado.", @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "{{value0}} mostradas", "originalPaneUnavailable": "El panel original ya no está disponible.", "worktreeUnavailable": "El worktree ya no está disponible.", - "runtimeBrowseLocalHistory": "Los workspaces alojados en runtime pueden explorar el historial local. Las acciones de reanudación están disponibles en workspaces locales y SSH.", - "runtimeWorkspacesUnsupported": "Reanudar desde el historial no está disponible en workspaces alojados en runtime.", - "openSupportedWorkspace": "Abre un workspace local o SSH antes de reanudar una sesión.", + "openSupportedWorkspace": "Abre un workspace antes de reanudar una sesión.", "localSessionSshWorkspaceUnsupported": "El historial de esta sesión solo existe en este equipo. Para reanudarla, abre un workspace local. Los workspaces SSH no tienen acceso a ese historial.", "sessionHostMismatchUnsupported": "Esta sesión pertenece a un host diferente. Abre un espacio de trabajo en el mismo host para reanudarla." }, @@ -9682,7 +9682,7 @@ "projectScope": "Proyecto", "currentProjectLower": "proyecto actual", "project": "Proyecto", - "hostScopeAriaLabel": "Session History host: {{value0}}", + "hostScopeAriaLabel": "Host del historial de sesiones: {{value0}}", "host": "Host" }, "AiVaultSessionDetails": { @@ -11522,6 +11522,24 @@ "3e6c9a2b71": "pendiente", "4f7d0c3e88": "pasos fallidos", "5a8e1d4f23": " · " + }, + "ExternalFileChangeBanner": { + "7c41e90d12": "This file changed on disk while you have unsaved edits. Saving will overwrite the newer disk content.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "5c02de9b31": "Reloaded from disk", + "d1e830fa22": "Undo", + "90b2ce7d43": "Compare" + }, + "ExternalFileChangeCompareDialog": { + "4b8de20a11": "File changed on disk", + "90cc31e4d7": "Disk version on the left, your unsaved edits on the right.", + "8fe30ab254": "Reading file from disk...", + "e2b1cd0393": "Could not read the file from disk: {{value0}}", + "b6cf20d514": "The file on disk is binary — no text comparison available.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "2c8f1e07b9": "Loading comparison..." } }, "diff": { @@ -11711,7 +11729,7 @@ "f2d0c22d67": "Eliminar anotación {{value0}}", "11c5084aa2": "Borrar anotaciones", "734e4343ec": "Borrar anotaciones del navegador", - "95af781091": "Enviar comentarios a un nuevo agente", + "95af781091": "Enviar comentarios a un agente", "ac39b9366b": "Enviar", "a3508d7e6e": "{{value0}} anotación{{value1}} listo. Seleccione otro elemento o copie todos los comentarios.", "f796c774a4": "Escriba una URL arriba para comenzar a navegar.", @@ -12457,7 +12475,7 @@ "allow": "Permitir", "deny": "Denegar" }, - "launchPromptNotDelivered": "Not delivered — check the terminal" + "launchPromptNotDelivered": "No se entregó; revisa el terminal" }, "tab": { "bar": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 20e253a58..e5bdf3384 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Orca に接続", "mobileScopeRejected": "この QR コードは制限付き(モバイル)アクセスを許可します。完全な Web アプリを使うには、設定 → リモート Orca サーバー → この Orca サーバーを共有する → 新規リンク からブラウザー用アクセスリンクを開いてください。" }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "この実行ホストでは Agent セッション履歴を使用できません。" + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "履歴からの再開はローカルワークスペースでのみ利用できます。", "openLocalWorkspace": "セッションを再開する前にローカルワークスペースを開いてください。", "sessionQueued": "セッションをキューに追加しました", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "このセッションの履歴はこのマシンに保存されているため、SSH ワークスペースでは再開できません。代わりにローカルワークスペースにドロップしてください。", "sessionHostMismatchUnsupported": "このセッションは別のホストに属しています。同じホスト上のワークスペースにドロップしてください。" }, @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "{{value0}} 件表示", "originalPaneUnavailable": "元のペインは利用できなくなりました。", "worktreeUnavailable": "ワークツリーは利用できなくなりました。", - "runtimeBrowseLocalHistory": "Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "このセッションの履歴はこのマシンに保存されているため、SSH ワークスペースでは再開できません。代わりにローカルワークスペースを開いてください。", "sessionHostMismatchUnsupported": "このセッションは別のホストに属しています。再開するには同じホスト上のワークスペースを開いてください。" }, @@ -11522,6 +11522,24 @@ "3e6c9a2b71": "保留中", "4f7d0c3e88": "失敗したステップ", "5a8e1d4f23": " · " + }, + "ExternalFileChangeBanner": { + "7c41e90d12": "This file changed on disk while you have unsaved edits. Saving will overwrite the newer disk content.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "5c02de9b31": "Reloaded from disk", + "d1e830fa22": "Undo", + "90b2ce7d43": "Compare" + }, + "ExternalFileChangeCompareDialog": { + "4b8de20a11": "File changed on disk", + "90cc31e4d7": "Disk version on the left, your unsaved edits on the right.", + "8fe30ab254": "Reading file from disk...", + "e2b1cd0393": "Could not read the file from disk: {{value0}}", + "b6cf20d514": "The file on disk is binary — no text comparison available.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "2c8f1e07b9": "Loading comparison..." } }, "diff": { @@ -11711,7 +11729,7 @@ "f2d0c22d67": "注釈 {{value0}} を削除", "11c5084aa2": "注釈をクリアする", "734e4343ec": "ブラウザの注釈をクリアする", - "95af781091": "新規 agent にフィードバックを送信する", + "95af781091": "agent にフィードバックを送信する", "ac39b9366b": "送信", "a3508d7e6e": "{{value0}} アノテーション{{value1}} が準備されました。別の要素を選択するか、すべてのフィードバックをコピーします。", "f796c774a4": "上に URL を入力して閲覧を開始します。", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index cd83a58fa..db8a2aea5 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Orca에 연결", "mobileScopeRejected": "이 QR 코드는 제한된(모바일) 액세스 권한만 제공합니다. 전체 웹 앱을 사용하려면 설정 → 원격 Orca 서버 → 이 Orca 서버 공유 → 새 링크에서 브라우저 액세스 링크를 여세요." }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "이 실행 호스트에서는 Agent 세션 기록을 사용할 수 없습니다." + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "기록에서 재개하기는 로컬 워크스페이스에서만 사용할 수 있습니다.", "openLocalWorkspace": "세션을 재개하기 전에 로컬 워크스페이스를 여세요.", "sessionQueued": "세션이 대기열에 추가됨", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "이 세션의 기록은 이 컴퓨터에 저장되어 있어 SSH 워크스페이스에서는 재개할 수 없습니다. 대신 로컬 워크스페이스에 놓으세요.", "sessionHostMismatchUnsupported": "이 세션은 다른 호스트에 속합니다. 같은 호스트의 워크스페이스에 놓으세요." }, @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "{{value0}} 표시됨", "originalPaneUnavailable": "원래 창은 더 이상 사용할 수 없습니다.", "worktreeUnavailable": "워크트리는 더 이상 사용할 수 없습니다.", - "runtimeBrowseLocalHistory": "Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "이 세션의 기록은 이 컴퓨터에 저장되어 있어 SSH 워크스페이스에서는 재개할 수 없습니다. 대신 로컬 워크스페이스를 여세요.", "sessionHostMismatchUnsupported": "이 세션은 다른 호스트에 속합니다. 재개하려면 같은 호스트의 워크스페이스를 여세요." }, @@ -11522,6 +11522,24 @@ "3e6c9a2b71": "보류 중", "4f7d0c3e88": "단계 실패", "5a8e1d4f23": " · " + }, + "ExternalFileChangeBanner": { + "7c41e90d12": "This file changed on disk while you have unsaved edits. Saving will overwrite the newer disk content.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "5c02de9b31": "Reloaded from disk", + "d1e830fa22": "Undo", + "90b2ce7d43": "Compare" + }, + "ExternalFileChangeCompareDialog": { + "4b8de20a11": "File changed on disk", + "90cc31e4d7": "Disk version on the left, your unsaved edits on the right.", + "8fe30ab254": "Reading file from disk...", + "e2b1cd0393": "Could not read the file from disk: {{value0}}", + "b6cf20d514": "The file on disk is binary — no text comparison available.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "2c8f1e07b9": "Loading comparison..." } }, "diff": { @@ -11711,7 +11729,7 @@ "f2d0c22d67": "주석 {{value0}} 삭제", "11c5084aa2": "주석 지우기", "734e4343ec": "브라우저 주석 지우기", - "95af781091": "새 agent에게 피드백 보내기", + "95af781091": "agent에게 피드백 보내기", "ac39b9366b": "보내기", "a3508d7e6e": "{{value0}} 주석{{value1}}이 준비되었습니다. 다른 요소를 선택하거나 모든 피드백을 복사하세요.", "f796c774a4": "탐색을 시작하려면 위에 URL을 입력하세요.", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 5be008913..d6cce4de2 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -137,6 +137,9 @@ "e3bcd082ac": "连接到 Orca", "mobileScopeRejected": "此二维码仅授予受限(移动端)访问权限。若要使用完整 Web 应用,请从设置 → 远程 Orca 服务器 → 分享此 Orca 服务器 → 新链接打开浏览器访问链接。" }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "此执行主机不支持 Agent 会话历史记录。" + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "从历史恢复仅支持本地工作区。", "openLocalWorkspace": "恢复会话前请先打开一个本地工作区。", "sessionQueued": "会话已排队", - "runtimeWorkspacesUnsupported": "在远程运行时托管的工作区中无法从历史记录恢复会话。", - "openSupportedWorkspace": "在恢复会话之前,请先打开一个本地或 SSH 工作区。", + "openSupportedWorkspace": "在恢复会话之前,请先打开一个工作区。", "localSessionSshWorkspaceUnsupported": "此会话的历史记录存储在本机上,因此无法在 SSH 工作区中恢复。请改为将其拖放到本地工作区。", "sessionHostMismatchUnsupported": "此会话属于其他主机。请将其拖放到同一主机上的工作区。" }, @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "已显示 {{value0}} 个", "originalPaneUnavailable": "原始面板不再可用。", "worktreeUnavailable": "工作树不再可用。", - "runtimeBrowseLocalHistory": "远程运行时托管的工作区可以浏览本地历史。恢复操作在本地和 SSH 工作区中可用。", - "runtimeWorkspacesUnsupported": "在远程运行时托管的工作区中无法从历史记录恢复会话。", - "openSupportedWorkspace": "在恢复会话之前,请先打开一个本地或 SSH 工作区。", + "openSupportedWorkspace": "在恢复会话之前,请先打开一个工作区。", "localSessionSshWorkspaceUnsupported": "此会话的历史记录存储在本机上,因此无法在 SSH 工作区中恢复。请改为打开一个本地工作区。", "sessionHostMismatchUnsupported": "此会话属于其他主机。请打开同一主机上的工作区以恢复它。" }, @@ -11522,6 +11522,24 @@ "3e6c9a2b71": "等待中", "4f7d0c3e88": "步骤失败", "5a8e1d4f23": " · " + }, + "ExternalFileChangeBanner": { + "7c41e90d12": "This file changed on disk while you have unsaved edits. Saving will overwrite the newer disk content.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "5c02de9b31": "Reloaded from disk", + "d1e830fa22": "Undo", + "90b2ce7d43": "Compare" + }, + "ExternalFileChangeCompareDialog": { + "4b8de20a11": "File changed on disk", + "90cc31e4d7": "Disk version on the left, your unsaved edits on the right.", + "8fe30ab254": "Reading file from disk...", + "e2b1cd0393": "Could not read the file from disk: {{value0}}", + "b6cf20d514": "The file on disk is binary — no text comparison available.", + "3fa2b8d417": "Reload from Disk", + "a95d02c644": "Keep My Edits", + "2c8f1e07b9": "Loading comparison..." } }, "diff": { @@ -11711,7 +11729,7 @@ "f2d0c22d67": "删除注释 {{value0}}", "11c5084aa2": "清晰的注释", "734e4343ec": "清除浏览器注释", - "95af781091": "向新智能体发送反馈", + "95af781091": "向智能体发送反馈", "ac39b9366b": "发送", "a3508d7e6e": "{{value0}} 注释{{value1}} 准备就绪。选择另一个元素或复制所有反馈。", "f796c774a4": "在上面输入 URL 即可开始浏览。", diff --git a/src/renderer/src/lib/ai-vault-resume-target.test.ts b/src/renderer/src/lib/ai-vault-resume-target.test.ts index 207bc525a..f7903f130 100644 --- a/src/renderer/src/lib/ai-vault-resume-target.test.ts +++ b/src/renderer/src/lib/ai-vault-resume-target.test.ts @@ -114,10 +114,33 @@ describe('ai vault session storage compatibility', () => { ).toBe(true) }) - it('never allows runtime or unknown targets', () => { + it('allows runtime sessions only on the matching runtime target', () => { expect( - canResumeAiVaultSessionOnTarget({ sessionFilePath: wslSessionFile, targetStatus: 'runtime' }) + canResumeAiVaultSessionOnTarget({ + sessionFilePath: '/home/ada/.codex/sessions/remote.jsonl', + sessionExecutionHostId: 'runtime:env-1', + targetStatus: 'runtime', + targetExecutionHostId: 'runtime:env-1' + }) + ).toBe(true) + expect( + canResumeAiVaultSessionOnTarget({ + sessionFilePath: '/home/ada/.codex/sessions/remote.jsonl', + sessionExecutionHostId: 'runtime:env-1', + targetStatus: 'runtime', + targetExecutionHostId: 'runtime:env-2' + }) ).toBe(false) + expect( + canResumeAiVaultSessionOnTarget({ + sessionFilePath: wslSessionFile, + targetStatus: 'runtime', + targetExecutionHostId: 'runtime:env-1' + }) + ).toBe(false) + }) + + it('never allows unknown targets', () => { expect( canResumeAiVaultSessionOnTarget({ sessionFilePath: hostSessionFile, targetStatus: 'unknown' }) ).toBe(false) @@ -149,8 +172,11 @@ describe('ai vault resume target ownership', () => { true ) expect( - isUnsupportedAiVaultResumeRepo({ connectionId: null, executionHostId: 'runtime:env-1' }) + isSupportedAiVaultResumeRepo({ connectionId: null, executionHostId: 'runtime:env-1' }) ).toBe(true) + expect( + isUnsupportedAiVaultResumeRepo({ connectionId: null, executionHostId: 'runtime:env-1' }) + ).toBe(false) }) it('resolves runtime-owned worktree targets through their repo owner', () => { diff --git a/src/renderer/src/lib/ai-vault-resume-target.ts b/src/renderer/src/lib/ai-vault-resume-target.ts index 823840ec8..f52e26c62 100644 --- a/src/renderer/src/lib/ai-vault-resume-target.ts +++ b/src/renderer/src/lib/ai-vault-resume-target.ts @@ -35,7 +35,7 @@ export function isSupportedAiVaultResumeRepo( } export function isSupportedAiVaultResumeTargetStatus(status: AiVaultResumeTargetStatus): boolean { - return status === 'local' || status === 'ssh' + return status === 'local' || status === 'ssh' || status === 'runtime' } export function isWslStoredAiVaultSessionFile(sessionFilePath: string | null | undefined): boolean { @@ -48,11 +48,20 @@ export function canResumeAiVaultSessionOnTarget(args: { targetStatus: AiVaultResumeTargetStatus targetExecutionHostId?: ExecutionHostId | null }): boolean { + const sessionExecutionHostId = normalizeExecutionHostId(args.sessionExecutionHostId) + const targetExecutionHostId = normalizeExecutionHostId(args.targetExecutionHostId) + if (args.targetStatus === 'runtime') { + // Runtime session stores live on one paired server; only queue resumes back + // onto that exact server host. + return Boolean( + sessionExecutionHostId && + targetExecutionHostId && + sessionExecutionHostId === targetExecutionHostId + ) + } if (!isSupportedAiVaultResumeTargetStatus(args.targetStatus)) { return false } - const sessionExecutionHostId = normalizeExecutionHostId(args.sessionExecutionHostId) - const targetExecutionHostId = normalizeExecutionHostId(args.targetExecutionHostId) if (sessionExecutionHostId) { if (targetExecutionHostId) { if (sessionExecutionHostId === targetExecutionHostId) { @@ -84,7 +93,8 @@ export function canResumeAiVaultSessionOnTarget(args: { export function isUnsupportedAiVaultResumeRepo( repo: AiVaultResumeRepoOwner | null | undefined ): boolean { - return getAiVaultResumeRepoTargetStatus(repo) === 'runtime' + const status = getAiVaultResumeRepoTargetStatus(repo) + return status !== 'unknown' && !isSupportedAiVaultResumeTargetStatus(status) } export function getAiVaultResumeWorktreeTargetStatus(args: { diff --git a/src/renderer/src/lib/github-source-runtime-context.test.ts b/src/renderer/src/lib/github-source-runtime-context.test.ts index 7aee8772e..b0cc6c505 100644 --- a/src/renderer/src/lib/github-source-runtime-context.test.ts +++ b/src/renderer/src/lib/github-source-runtime-context.test.ts @@ -1,11 +1,14 @@ import { describe, expect, it } from 'vitest' import type { TaskSourceContext } from '../../../shared/task-source-context' +import { getActiveRuntimeTarget } from '../runtime/runtime-rpc-client' import { canUseGitHubRepoContext, + getGitHubMutationRoutingSettings, getGitHubRuntimeRepoId, getGitHubSourceRuntimeHost, getGitHubSourceRuntimeTarget } from './github-source-runtime-context' +import type { RepoRuntimeOwnerState } from './repo-runtime-owner' const runtimeSourceContext: TaskSourceContext = { kind: 'task-source', @@ -52,3 +55,91 @@ describe('GitHub source runtime context', () => { ).toBe('fallback') }) }) + +describe('getGitHubMutationRoutingSettings', () => { + const runtimeOwnedRepo: RepoRuntimeOwnerState = { + settings: { activeRuntimeEnvironmentId: null }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'runtime:owner-runtime' }] + } + + function resolveTarget( + state: RepoRuntimeOwnerState, + repoId: string | null, + sourceContext: TaskSourceContext | null + ): ReturnType { + return getActiveRuntimeTarget(getGitHubMutationRoutingSettings(state, repoId, sourceContext)) + } + + it('routes a runtime-owned repo to its owner runtime when the source view is local (#6957)', () => { + expect( + resolveTarget(runtimeOwnedRepo, 'repo-1', { + ...runtimeSourceContext, + hostId: 'local', + repoId: 'repo-1' + }) + ).toEqual({ kind: 'environment', environmentId: 'owner-runtime' }) + }) + + it('routes a runtime-owned repo to its owner runtime when there is no source context', () => { + expect(resolveTarget(runtimeOwnedRepo, 'repo-1', null)).toEqual({ + kind: 'environment', + environmentId: 'owner-runtime' + }) + }) + + it('lets a runtime source override the repo owner when both name runtimes', () => { + expect( + resolveTarget(runtimeOwnedRepo, 'repo-1', { + ...runtimeSourceContext, + hostId: 'runtime:source-runtime', + repoId: 'repo-1' + }) + ).toEqual({ kind: 'environment', environmentId: 'source-runtime' }) + }) + + it('keeps an explicitly-local repo on local IPC even while a runtime is focused', () => { + const localRepo: RepoRuntimeOwnerState = { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'local' }] + } + expect( + resolveTarget(localRepo, 'repo-1', { + ...runtimeSourceContext, + hostId: 'local', + repoId: 'repo-1' + }) + ).toEqual({ kind: 'local' }) + }) + + it('ignores runtime hosts on non-GitHub sources', () => { + expect( + resolveTarget(runtimeOwnedRepo, 'repo-1', { + ...runtimeSourceContext, + provider: 'gitlab', + hostId: 'runtime:source-runtime' + }) + ).toEqual({ kind: 'environment', environmentId: 'owner-runtime' }) + }) + + it('never routes a repo without an explicit owner to the globally focused runtime', () => { + const noOwnerRepo: RepoRuntimeOwnerState = { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: null }] + } + expect( + resolveTarget(noOwnerRepo, 'repo-1', { + ...runtimeSourceContext, + hostId: 'local', + repoId: 'repo-1' + }) + ).toEqual({ kind: 'local' }) + expect(resolveTarget(noOwnerRepo, 'repo-1', null)).toEqual({ kind: 'local' }) + expect( + resolveTarget(noOwnerRepo, 'repo-1', { + ...runtimeSourceContext, + hostId: 'runtime:source-runtime', + repoId: 'repo-1' + }) + ).toEqual({ kind: 'environment', environmentId: 'source-runtime' }) + }) +}) diff --git a/src/renderer/src/lib/github-source-runtime-context.ts b/src/renderer/src/lib/github-source-runtime-context.ts index 617970335..c36598e34 100644 --- a/src/renderer/src/lib/github-source-runtime-context.ts +++ b/src/renderer/src/lib/github-source-runtime-context.ts @@ -2,8 +2,13 @@ import type { ParsedExecutionHost } from '../../../shared/execution-host' import { parseExecutionHostId } from '../../../shared/execution-host' import type { TaskSourceContext } from '../../../shared/task-source-context' import { getTaskSourceRuntimeSettings } from '../../../shared/task-source-context' +import type { GlobalSettings } from '../../../shared/types' import type { RuntimeClientTarget } from '@/runtime/runtime-rpc-client' import { getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' +import { + getExplicitRuntimeOwnerEnvironmentId, + type RepoRuntimeOwnerState +} from './repo-runtime-owner' export type GitHubRuntimeHost = Extract @@ -25,6 +30,22 @@ export function getGitHubSourceRuntimeTarget( ) } +// Why: PR mutations must run on the repo's explicit owner host (#6957); a +// local or absent source never downgrades a runtime-owned repo to local IPC, +// a runtime source still overrides, and the globally focused runtime is never +// used as a fallback — a repo without an explicit owner is a local repo. +export function getGitHubMutationRoutingSettings( + state: RepoRuntimeOwnerState, + repoId: string | null | undefined, + sourceContext: TaskSourceContext | null | undefined +): Pick { + const sourceHost = getGitHubSourceRuntimeHost(sourceContext) + return { + activeRuntimeEnvironmentId: + sourceHost?.environmentId ?? getExplicitRuntimeOwnerEnvironmentId(state, repoId) + } +} + export function canUseGitHubRepoContext( repoPath: string | null | undefined, sourceContext: TaskSourceContext | null | undefined diff --git a/src/renderer/src/lib/launch-agent-in-new-tab.test.ts b/src/renderer/src/lib/launch-agent-in-new-tab.test.ts index fd4dcf004..fd25fc85d 100644 --- a/src/renderer/src/lib/launch-agent-in-new-tab.test.ts +++ b/src/renderer/src/lib/launch-agent-in-new-tab.test.ts @@ -9,6 +9,7 @@ const mockPasteDraftWhenAgentReady = vi.fn() const mockSeedNativeChatLaunchPrompt = vi.fn() const mockMarkNativeChatLaunchPromptFailed = vi.fn() const mockTrack = vi.fn() +const mockToastMessage = vi.fn() const LEAF_ID = '11111111-1111-4111-8111-111111111111' @@ -80,7 +81,7 @@ vi.mock('@/store', () => ({ const mockToastError = vi.fn() vi.mock('sonner', () => ({ - toast: { message: vi.fn(), error: mockToastError } + toast: { message: mockToastMessage, error: mockToastError } })) vi.mock('@/components/tab-bar/reconcile-order', () => ({ @@ -545,7 +546,7 @@ describe('launchAgentInNewTab', () => { const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') const prompt = 'x'.repeat(25_000) - launchAgentInNewTab({ + const result = launchAgentInNewTab({ agent: 'claude', worktreeId: 'wt-1', prompt, @@ -553,6 +554,7 @@ describe('launchAgentInNewTab', () => { launchPlatform: 'win32' }) + expect(result).not.toHaveProperty('promptDeliveryResult') expect(mockQueueTabStartupCommand).toHaveBeenCalledWith( 'tab-1', expect.objectContaining({ @@ -570,16 +572,46 @@ describe('launchAgentInNewTab', () => { ) }) + it('logs rejected non-deferred prompt delivery without exposing it to callers', async () => { + const error = new Error('paste failed') + const originalConsole = console + const consoleError = vi.fn() + vi.stubGlobal('console', { ...originalConsole, error: consoleError }) + mockPasteDraftWhenAgentReady.mockRejectedValue(error) + const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') + const prompt = 'x'.repeat(25_000) + + try { + const result = launchAgentInNewTab({ + agent: 'claude', + worktreeId: 'wt-1', + prompt, + promptDelivery: 'draft', + launchPlatform: 'win32' + }) + + expect(result).not.toHaveProperty('promptDeliveryResult') + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(consoleError).toHaveBeenCalledWith('Prompt delivery failed after launch', error) + } finally { + vi.stubGlobal('console', originalConsole) + } + }) + it('seeds working after Command Code submit-after-ready prompt delivery', async () => { const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') - launchAgentInNewTab({ + const result = launchAgentInNewTab({ agent: 'command-code', worktreeId: 'wt-1', prompt: 'large generated prompt', promptDelivery: 'submit-after-ready' }) store.terminalLayoutsByTabId = { 'tab-1': { activeLeafId: LEAF_ID } } + await expect(result?.promptDeliveryResult).resolves.toEqual({ + delivered: true, + failureNotified: false + }) await Promise.resolve() await Promise.resolve() @@ -610,17 +642,114 @@ describe('launchAgentInNewTab', () => { mockPasteDraftWhenAgentReady.mockResolvedValue(false) const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') - launchAgentInNewTab({ + const result = launchAgentInNewTab({ agent: 'command-code', worktreeId: 'wt-1', prompt: 'large generated prompt', promptDelivery: 'submit-after-ready' }) + await expect(result?.promptDeliveryResult).resolves.toEqual({ + delivered: false, + failureNotified: false + }) await Promise.resolve() expect(mockTrack).not.toHaveBeenCalledWith('agent_prompt_sent', expect.anything()) }) + it('marks failed submit-after-ready delivery as notified after readiness timeout toast', async () => { + mockPasteDraftWhenAgentReady.mockImplementation(({ onTimeout }) => { + onTimeout?.() + return Promise.resolve(false) + }) + store.tabsByWorktree = { 'wt-1': [{ id: 'tab-1', ptyId: 'pty-1' } as never] } + const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') + + const result = launchAgentInNewTab({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'large generated prompt', + promptDelivery: 'submit-after-ready' + }) + + await expect(result?.promptDeliveryResult).resolves.toEqual({ + delivered: false, + failureNotified: true + }) + expect(mockToastMessage).toHaveBeenCalledWith( + "Your prompt wasn't sent — paste it once the agent is ready." + ) + }) + + it('marks a cancelled submit-after-ready launch notified when the user closed the tab', async () => { + mockPasteDraftWhenAgentReady.mockImplementation(({ onTimeout }) => { + onTimeout?.() + return Promise.resolve(false) + }) + // User closed the tab before the agent became ready — it is gone from the list. + store.tabsByWorktree = { 'wt-1': [] } + const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') + + const result = launchAgentInNewTab({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'large generated prompt', + promptDelivery: 'submit-after-ready' + }) + + await expect(result?.promptDeliveryResult).resolves.toEqual({ + delivered: false, + failureNotified: true + }) + expect(mockToastMessage).not.toHaveBeenCalled() + }) + + it('marks a cancelled submit-after-ready launch notified when the user switched worktrees', async () => { + mockPasteDraftWhenAgentReady.mockImplementation(({ onTimeout }) => { + onTimeout?.() + return Promise.resolve(false) + }) + store.tabsByWorktree = { 'wt-1': [{ id: 'tab-1', ptyId: 'pty-1' } as never] } + store.activeWorktreeId = 'wt-2' + const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') + + const result = launchAgentInNewTab({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'large generated prompt', + promptDelivery: 'submit-after-ready' + }) + + await expect(result?.promptDeliveryResult).resolves.toEqual({ + delivered: false, + failureNotified: true + }) + expect(mockToastMessage).not.toHaveBeenCalled() + }) + + it('leaves a genuine launch failure unnotified so the caller surfaces it', async () => { + mockPasteDraftWhenAgentReady.mockImplementation(({ onTimeout }) => { + onTimeout?.() + return Promise.resolve(false) + }) + // PTY never spawned: a real failure, not a user cancellation. + store.tabsByWorktree = { 'wt-1': [{ id: 'tab-1', ptyId: null } as never] } + const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') + + const result = launchAgentInNewTab({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'large generated prompt', + promptDelivery: 'submit-after-ready' + }) + + await expect(result?.promptDeliveryResult).resolves.toEqual({ + delivered: false, + failureNotified: false + }) + expect(mockToastMessage).not.toHaveBeenCalled() + }) + it('queues per-launch CLI arguments without putting generated prompts in argv', async () => { const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') diff --git a/src/renderer/src/lib/launch-agent-in-new-tab.ts b/src/renderer/src/lib/launch-agent-in-new-tab.ts index 2f06dca71..503973477 100644 --- a/src/renderer/src/lib/launch-agent-in-new-tab.ts +++ b/src/renderer/src/lib/launch-agent-in-new-tab.ts @@ -69,6 +69,7 @@ export type LaunchAgentInNewTabResult = { tabId: string | null startupPlan: AgentStartupPlan pasteDraftAfterLaunch: boolean + promptDeliveryResult?: Promise<{ delivered: boolean; failureNotified: boolean }> } | null /** @@ -153,6 +154,7 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI let pasteDraftAfterLaunch: string | null = null let submitPastedPrompt = false let forcePasteAfterLaunch = false + let promptDeliveryResult: Promise<{ delivered: boolean; failureNotified: boolean }> | undefined if (hasPrompt && promptDelivery === 'submit-after-ready') { // Why: generated multi-line prompts are too large to echo through a shell @@ -300,9 +302,9 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI // the user closed the tab or switched worktrees so the toast/telemetry // don't fire for user-initiated cancellation (mirrors the 5s launch // watchdog in QuickLaunchButton). - const tabId = tab.id - void deliverLaunchPromptToAgentTab({ - tabId, + let failureNotified = false + const deliveryPromise = deliverLaunchPromptToAgentTab({ + tabId: tab.id, content: pasteDraftAfterLaunch, agent, submit: submitPastedPrompt, @@ -310,28 +312,28 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI onTimeout: () => { const state = useAppStore.getState() const tabsForWorktree = state.tabsByWorktree[worktreeId] ?? [] - const tab = tabsForWorktree.find((t) => t.id === tabId) - // Why: if the PTY never spawned, QuickLaunch's 5s watchdog already - // surfaced the launch failure. Don't double-toast for the same root - // cause. Looking up directly in `worktreeId` (not scanning every - // worktree) also preserves "still in this worktree" intent. - if (!tab) { - return // tab closed by user - } - if (tab.ptyId === null) { - return // launch failed; QuickLaunch handled the user-facing toast - } - if (state.activeWorktreeId !== worktreeId) { + const currentTab = tabsForWorktree.find((t) => t.id === tab.id) + if (currentTab?.ptyId === null) { + // Why: PTY never spawned — a genuine launch failure. Stay silent so + // the single notice comes from the caller (source-control dialog + // toast, or QuickLaunch's watchdog); leaving failureNotified false lets it fire. + return + } + if (!currentTab || state.activeWorktreeId !== worktreeId) { + // Why: user-initiated cancellation (closed the tab or switched + // worktrees) — mark notified so the deferred source-control caller + // suppresses its generic "couldn't start" toast too, not just this nudge. + failureNotified = true return } - const label = submitPastedPrompt ? 'prompt' : 'notes' toast.message( translate( 'auto.lib.launch.agent.in.new.tab.a5a1f7033f', "Your {{value0}} wasn't sent — paste it once the agent is ready.", - { value0: label } + { value0: submitPastedPrompt ? 'prompt' : 'notes' } ) ) + failureNotified = true track('agent_error', { error_class: 'paste_readiness_timeout', agent_kind: tuiAgentToAgentKind(agent) @@ -342,11 +344,19 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI if (agent === 'command-code' && submitPastedPrompt) { // Why: Command Code has no prompt-submit hook; when Orca submits a // generated prompt after readiness, seed working at delivery time. - seedCommandCodeSubmittedPromptStatus(tabId, trimmedPrompt) + seedCommandCodeSubmittedPromptStatus(tab.id, trimmedPrompt) } onPromptDelivered?.() } + return { delivered, failureNotified: !delivered && failureNotified } }) + if (promptDelivery === 'submit-after-ready') { + promptDeliveryResult = deliveryPromise + } else { + void deliveryPromise.catch((error) => + console.error('Prompt delivery failed after launch', error) + ) + } } else if (hasPrompt) { onPromptDelivered?.() } @@ -373,5 +383,10 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI order.push(tab.id) fresh.setTabBarOrder(worktreeId, order) - return { tabId: tab.id, startupPlan, pasteDraftAfterLaunch: pasteDraftAfterLaunch !== null } + return { + tabId: tab.id, + startupPlan, + pasteDraftAfterLaunch: pasteDraftAfterLaunch !== null, + ...(promptDeliveryResult ? { promptDeliveryResult } : {}) + } } diff --git a/src/renderer/src/lib/launch-ai-vault-session.test.ts b/src/renderer/src/lib/launch-ai-vault-session.test.ts index e6a1c083a..ef0425b58 100644 --- a/src/renderer/src/lib/launch-ai-vault-session.test.ts +++ b/src/renderer/src/lib/launch-ai-vault-session.test.ts @@ -5,6 +5,11 @@ const mockCreateEmptySplitGroup = vi.fn() const mockQueueTabStartupCommand = vi.fn() const mockSetActiveTabType = vi.fn() const mockSetTabBarOrder = vi.fn() +const runtimeMocks = vi.hoisted(() => ({ + createWebRuntimeSessionTerminal: vi.fn(), + getRuntimeEnvironmentIdForWorktree: vi.fn<() => string | null>(() => null), + isWebRuntimeSessionActive: vi.fn(() => false) +})) const mockState = { createTab: mockCreateTab, @@ -37,11 +42,23 @@ vi.mock('@/lib/telemetry', () => ({ tuiAgentToAgentKind: (agent: string) => agent })) +vi.mock('@/lib/worktree-runtime-owner', () => ({ + getRuntimeEnvironmentIdForWorktree: runtimeMocks.getRuntimeEnvironmentIdForWorktree +})) + +vi.mock('@/runtime/web-runtime-session', () => ({ + createWebRuntimeSessionTerminal: runtimeMocks.createWebRuntimeSessionTerminal, + isWebRuntimeSessionActive: runtimeMocks.isWebRuntimeSessionActive +})) + import { launchAiVaultSessionInNewTab } from './launch-ai-vault-session' describe('launchAiVaultSessionInNewTab', () => { beforeEach(() => { vi.clearAllMocks() + runtimeMocks.getRuntimeEnvironmentIdForWorktree.mockReturnValue(null) + runtimeMocks.isWebRuntimeSessionActive.mockReturnValue(false) + runtimeMocks.createWebRuntimeSessionTerminal.mockResolvedValue(true) mockState.tabsByWorktree = {} mockState.openFiles = [] mockState.browserTabsByWorktree = {} @@ -118,4 +135,45 @@ describe('launchAiVaultSessionInNewTab', () => { expect(mockCreateEmptySplitGroup).toHaveBeenCalledWith('wt-1', 'group-1', 'right') expect(mockCreateTab).toHaveBeenCalledWith('wt-1', 'group-new') }) + + it('creates runtime-hosted resume terminals through the paired host', async () => { + runtimeMocks.getRuntimeEnvironmentIdForWorktree.mockReturnValue('env-1') + runtimeMocks.isWebRuntimeSessionActive.mockReturnValue(true) + + const result = launchAiVaultSessionInNewTab({ + agent: 'codex', + worktreeId: 'wt-1', + targetGroupId: 'group-1', + command: "codex resume 'session-1'", + env: { CODEX_PROFILE: 'runtime' }, + launchConfig: { + agentCommand: 'codex', + agentArgs: '', + agentEnv: { CODEX_PROFILE: 'runtime' } + } + }) + + expect(result.tabId).toBeNull() + expect(runtimeMocks.createWebRuntimeSessionTerminal).toHaveBeenCalledWith({ + worktreeId: 'wt-1', + environmentId: 'env-1', + targetGroupId: 'group-1', + command: "codex resume 'session-1'", + env: { CODEX_PROFILE: 'runtime' }, + launchConfig: { + agentCommand: 'codex', + agentArgs: '', + agentEnv: { CODEX_PROFILE: 'runtime' } + }, + launchAgent: 'codex', + activate: true + }) + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockQueueTabStartupCommand).not.toHaveBeenCalled() + + if (result.tabId === null) { + await expect(result.runtimeLaunch).resolves.toBe(true) + } + expect(mockSetActiveTabType).toHaveBeenCalledWith('terminal') + }) }) diff --git a/src/renderer/src/lib/launch-ai-vault-session.ts b/src/renderer/src/lib/launch-ai-vault-session.ts index a22f00271..e04e35345 100644 --- a/src/renderer/src/lib/launch-ai-vault-session.ts +++ b/src/renderer/src/lib/launch-ai-vault-session.ts @@ -1,10 +1,19 @@ import { useAppStore } from '@/store' import { reconcileTabOrder } from '@/components/tab-bar/reconcile-order' import { tuiAgentToAgentKind } from '@/lib/telemetry' +import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { + createWebRuntimeSessionTerminal, + isWebRuntimeSessionActive +} from '@/runtime/web-runtime-session' import type { AiVaultAgent } from '../../../shared/ai-vault-types' import type { SleepingAgentLaunchConfig } from '../../../shared/agent-session-resume' import type { TabSplitDirection } from '@/store/slices/tabs' +export type LaunchAiVaultSessionInNewTabResult = + | { tabId: string; groupId?: string } + | { tabId: null; groupId?: string; runtimeLaunch: Promise } + export function launchAiVaultSessionInNewTab(args: { agent: AiVaultAgent worktreeId: string @@ -13,9 +22,33 @@ export function launchAiVaultSessionInNewTab(args: { launchConfig?: SleepingAgentLaunchConfig targetGroupId?: string splitDirection?: TabSplitDirection -}): { tabId: string; groupId?: string } { +}): LaunchAiVaultSessionInNewTabResult { const store = useAppStore.getState() let targetGroupId = args.targetGroupId + const runtimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(store, args.worktreeId) + if (isWebRuntimeSessionActive(runtimeEnvironmentId)) { + const runtimeLaunch = createWebRuntimeSessionTerminal({ + worktreeId: args.worktreeId, + environmentId: runtimeEnvironmentId, + ...(targetGroupId ? { targetGroupId } : {}), + command: args.command, + ...(args.env ? { env: args.env } : {}), + ...(args.launchConfig ? { launchConfig: args.launchConfig } : {}), + launchAgent: args.agent, + activate: true + }).then((created) => { + if (created) { + useAppStore.getState().setActiveTabType('terminal') + } + return created + }) + return { + tabId: null, + ...(targetGroupId ? { groupId: targetGroupId } : {}), + runtimeLaunch + } + } + if (args.splitDirection && targetGroupId) { targetGroupId = store.createEmptySplitGroup(args.worktreeId, targetGroupId, args.splitDirection) ?? diff --git a/src/renderer/src/lib/monaco-peek-preview-options.test.ts b/src/renderer/src/lib/monaco-peek-preview-options.test.ts new file mode 100644 index 000000000..62e3952aa --- /dev/null +++ b/src/renderer/src/lib/monaco-peek-preview-options.test.ts @@ -0,0 +1,98 @@ +// @vitest-environment happy-dom + +import { describe, expect, it, vi } from 'vitest' +import type * as Monaco from 'monaco-editor' +import { installMonacoPeekReferencesPreviewOptions } from './monaco-peek-preview-options' + +type FakePreviewEditor = Pick + +type FakeReferenceWidgetInstance = { + _preview?: FakePreviewEditor + _fillBody?: (containerElement: HTMLElement) => void + _revealReference?: (...args: unknown[]) => Promise +} + +function createReferenceWidgetConstructor(hooks: { + fillBody?: (instance: FakeReferenceWidgetInstance) => void + revealReference?: (instance: FakeReferenceWidgetInstance) => Promise +}): { + prototype: FakeReferenceWidgetInstance & + Required> +} { + return { + prototype: { + _fillBody(this: FakeReferenceWidgetInstance): void { + hooks.fillBody?.(this) + }, + async _revealReference(this: FakeReferenceWidgetInstance): Promise { + return hooks.revealReference?.(this) + } + } + } +} + +function createPreviewEditor(): FakePreviewEditor { + return { updateOptions: vi.fn() } +} + +const peekPreviewOptions = { + smoothScrolling: false, + stickyScroll: { enabled: false }, + wordWrap: 'off' +} + +describe('installMonacoPeekReferencesPreviewOptions', () => { + it('updates the embedded preview after ReferenceWidget creates it', () => { + const preview = createPreviewEditor() + const referenceWidget = createReferenceWidgetConstructor({ + fillBody(instance) { + instance._preview = preview + } + }) + + installMonacoPeekReferencesPreviewOptions(referenceWidget) + referenceWidget.prototype._fillBody(document.createElement('div')) + + expect(preview.updateOptions).toHaveBeenCalledWith(peekPreviewOptions) + }) + + it('updates the embedded preview before revealing a reference', async () => { + const calls: string[] = [] + const preview: FakePreviewEditor = { + updateOptions: vi.fn(() => calls.push('updateOptions')) + } + const referenceWidget = createReferenceWidgetConstructor({ + revealReference: async () => { + calls.push('revealReference') + } + }) + referenceWidget.prototype._preview = preview + + installMonacoPeekReferencesPreviewOptions(referenceWidget) + await referenceWidget.prototype._revealReference('reference') + + expect(calls).toEqual(['updateOptions', 'revealReference', 'updateOptions']) + expect(preview.updateOptions).toHaveBeenCalledWith(peekPreviewOptions) + }) + + it('skips patching when the private Monaco hooks are missing', () => { + const referenceWidget: { prototype: FakeReferenceWidgetInstance } = { prototype: {} } + + installMonacoPeekReferencesPreviewOptions(referenceWidget) + + expect(referenceWidget.prototype._fillBody).toBeUndefined() + expect(referenceWidget.prototype._revealReference).toBeUndefined() + }) + + it('does not wrap ReferenceWidget more than once', async () => { + const preview = createPreviewEditor() + const referenceWidget = createReferenceWidgetConstructor({}) + referenceWidget.prototype._preview = preview + + installMonacoPeekReferencesPreviewOptions(referenceWidget) + installMonacoPeekReferencesPreviewOptions(referenceWidget) + await referenceWidget.prototype._revealReference('reference') + + expect(preview.updateOptions).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/renderer/src/lib/monaco-peek-preview-options.ts b/src/renderer/src/lib/monaco-peek-preview-options.ts new file mode 100644 index 000000000..8927ed772 --- /dev/null +++ b/src/renderer/src/lib/monaco-peek-preview-options.ts @@ -0,0 +1,67 @@ +import type * as Monaco from 'monaco-editor' +import { ReferenceWidget as MonacoReferenceWidget } from 'monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget.js' + +type PeekPreviewEditor = Pick + +const PEEK_REFERENCES_PREVIEW_OPTIONS: Monaco.editor.IEditorOptions = { + smoothScrolling: false, + stickyScroll: { enabled: false }, + wordWrap: 'off' +} + +type ReferenceWidgetInstance = { + _preview?: PeekPreviewEditor + _fillBody?: (containerElement: HTMLElement) => void + _revealReference?: (...args: unknown[]) => Promise +} + +type ReferenceWidgetConstructor = { + prototype: ReferenceWidgetInstance & { + __orcaPeekPreviewOptionsInstalled?: true + } +} + +function applyPeekReferencesPreviewOptions(editor: PeekPreviewEditor | undefined): void { + // Why: Monaco embedded editors inherit Orca's full-editor options first. + // Peek previews are transient readers, so keep scroll/wrap widgets out of them. + editor?.updateOptions(PEEK_REFERENCES_PREVIEW_OPTIONS) +} + +export function installMonacoPeekReferencesPreviewOptions( + referenceWidget: ReferenceWidgetConstructor = MonacoReferenceWidget as unknown as ReferenceWidgetConstructor +): void { + const prototype = referenceWidget.prototype + if (prototype.__orcaPeekPreviewOptionsInstalled) { + return + } + + const originalFillBody = prototype._fillBody + const originalRevealReference = prototype._revealReference + // Why: these are private Monaco members with no stability guarantee; if an + // upgrade removes either, skip patching so Peek keeps Monaco's defaults. + if (typeof originalFillBody !== 'function' || typeof originalRevealReference !== 'function') { + return + } + + prototype._fillBody = function fillBodyWithPeekPreviewOptions( + this: ReferenceWidgetInstance, + containerElement: HTMLElement + ): void { + originalFillBody.call(this, containerElement) + applyPeekReferencesPreviewOptions(this._preview) + } + + prototype._revealReference = async function revealReferenceWithPeekPreviewOptions( + this: ReferenceWidgetInstance, + ...args: unknown[] + ): Promise { + applyPeekReferencesPreviewOptions(this._preview) + try { + return await originalRevealReference.apply(this, args) + } finally { + applyPeekReferencesPreviewOptions(this._preview) + } + } + + prototype.__orcaPeekPreviewOptionsInstalled = true +} diff --git a/src/renderer/src/lib/monaco-setup.ts b/src/renderer/src/lib/monaco-setup.ts index 67d05eaef..8a955e99d 100644 --- a/src/renderer/src/lib/monaco-setup.ts +++ b/src/renderer/src/lib/monaco-setup.ts @@ -13,6 +13,7 @@ import { registerSvelteLanguage } from './monaco-languages/register-svelte' import { registerVueLanguage } from './monaco-languages/register-vue' import { installMonacoDelayerCancellationGuard } from './monaco-delayer-cancellation-guard' import { installMonacoDiffEditorDisposalGuard } from './monaco-diff-editor-disposal' +import { installMonacoPeekReferencesPreviewOptions } from './monaco-peek-preview-options' import { installMonacoContextMenuPaste } from '@/components/editor/install-monaco-context-menu-paste' globalThis.MonacoEnvironment = { @@ -78,6 +79,7 @@ registerAstroLanguage(monaco) registerNimLanguage(monaco) installMonacoDelayerCancellationGuard() installMonacoDiffEditorDisposalGuard(monaco) +installMonacoPeekReferencesPreviewOptions() // Why: Monaco's built-in context-menu Paste reads navigator.clipboard, which is // blocked in Orca's sandboxed renderer. Route it through the trusted IPC bridge // so right-click Paste works like Cmd+V (which already works via native events). diff --git a/src/renderer/src/lib/pane-manager/pane-manager.ts b/src/renderer/src/lib/pane-manager/pane-manager.ts index 77ad53988..f04d5d9c3 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager.ts @@ -41,7 +41,7 @@ import { } from './pane-rendering-control' import type { TerminalLeafId } from '../../../../shared/stable-pane-id' import { registerLivePaneManager, unregisterLivePaneManager } from './pane-manager-registry' -import { schedulePaneRevealRepaint } from './pane-reveal-repaint' +import { schedulePaneRevealPresent, schedulePaneRevealRepaint } from './pane-reveal-repaint' import { PaneIdentityRegistry } from './pane-identity-registry' import { closeManagedPane, @@ -329,6 +329,12 @@ export class PaneManager { schedulePaneRevealRepaint(() => (this.destroyed ? [] : this.panes.values())) } + scheduleRevealPresent(): void { + // Why: same destroy guard as scheduleRevealRepaint, but presents without + // clearing the shared glyph atlas — used by the plain-refocus recovery. + schedulePaneRevealPresent(() => (this.destroyed ? [] : this.panes.values())) + } + suspendRendering(): void { this.renderingSuspended = true suspendPaneRendering(this.panes.values()) diff --git a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.test.ts b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.test.ts index 564a57e98..4985ffe13 100644 --- a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ManagedPaneInternal } from './pane-manager-types' -import { schedulePaneRevealRepaint } from './pane-reveal-repaint' +import { schedulePaneRevealPresent, schedulePaneRevealRepaint } from './pane-reveal-repaint' import { resetTerminalWebglSuggestion } from './pane-webgl-renderer' type FakeWebglAddon = { clearTextureAtlas: ReturnType } @@ -144,4 +144,32 @@ describe('schedulePaneRevealRepaint', () => { expect(webglAddon.clearTextureAtlas).toHaveBeenCalledTimes(1) vi.useRealTimers() }) + + describe('schedulePaneRevealPresent', () => { + it('presents the settled buffer without wiping the shared glyph atlas', () => { + // The plain-refocus path must NOT clear the atlas — the clear is a + // same-config shared wipe that re-arms the mid-stream page-merge race. + const webglAddon = { clearTextureAtlas: vi.fn() } + const pane = createPane({ webglAddon }) + schedulePaneRevealPresent(() => [pane]) + + flushFrame() + expect(pane.terminal.refresh).not.toHaveBeenCalled() + + flushFrame() + expect(webglAddon.clearTextureAtlas).not.toHaveBeenCalled() + expect(pane.terminal.refresh).toHaveBeenCalledWith(0, 23) + }) + + it('still retries a missing WebGL attach on the settled frame', () => { + const pane = createPane() + schedulePaneRevealPresent(() => [pane]) + + flushFrame() + flushFrame() + + expect(pane.webglAddon).not.toBeNull() + expect(pane.terminal.refresh).toHaveBeenCalled() + }) + }) }) diff --git a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts index 48df07b9b..9fb283782 100644 --- a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts +++ b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts @@ -15,6 +15,21 @@ function scheduleSettledFrame(callback: () => void): void { }) } +function forEachPaneOnSettledFrame( + getPanes: () => Iterable, + visit: (pane: ManagedPaneInternal) => void +): void { + scheduleSettledFrame(() => { + for (const pane of getPanes()) { + try { + visit(pane) + } catch { + /* ignore — one pane's failure must not block repaint of the rest */ + } + } + }) +} + /** * Repaints a revealed tab's panes from their xterm buffers. * @@ -26,14 +41,27 @@ function scheduleSettledFrame(callback: () => void): void { * settled — forces a full rebuild from the buffer without any PTY resize. */ export function schedulePaneRevealRepaint(getPanes: () => Iterable): void { - scheduleSettledFrame(() => { - for (const pane of getPanes()) { - try { - reattachWebglIfNeeded(pane) - resetWebglTextureAtlas(pane) - } catch { - /* ignore — one pane's failure must not block repaint of the rest */ - } + forEachPaneOnSettledFrame(getPanes, (pane) => { + reattachWebglIfNeeded(pane) + resetWebglTextureAtlas(pane) + }) +} + +/** + * Presents already-visible panes without clearing the shared glyph atlas. + * + * Why: a plain window refocus never hid its panes, so their WebGL model is + * already current — a `refresh` re-presents the live buffer (covering a + * compositor that dropped frames while occluded). Using the atlas-clearing + * reveal repaint here would wipe the atlas shared by every same-config pane and + * re-arm the mid-stream page-merge garble race (xterm.js issue 4480); this path + * must stay texture-atlas-preserving. + */ +export function schedulePaneRevealPresent(getPanes: () => Iterable): void { + forEachPaneOnSettledFrame(getPanes, (pane) => { + reattachWebglIfNeeded(pane) + if (pane.terminal.rows > 0) { + pane.terminal.refresh(0, pane.terminal.rows - 1) } }) } diff --git a/src/renderer/src/lib/repo-runtime-owner.test.ts b/src/renderer/src/lib/repo-runtime-owner.test.ts index 719c96467..dcc78094e 100644 --- a/src/renderer/src/lib/repo-runtime-owner.test.ts +++ b/src/renderer/src/lib/repo-runtime-owner.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import type { GlobalSettings } from '../../../shared/types' import { + getExplicitRuntimeOwnerEnvironmentId, getRepoOwnerRoutedSettings, getRuntimeEnvironmentIdForRepo, getSettingsForRepoRuntimeOwner @@ -98,6 +99,100 @@ describe('getRuntimeEnvironmentIdForRepo', () => { }) }) +describe('getExplicitRuntimeOwnerEnvironmentId', () => { + it('returns the runtime env id for a repo with an explicit runtime owner', () => { + expect( + getExplicitRuntimeOwnerEnvironmentId( + { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'runtime:owner-runtime' }] + }, + 'repo-1' + ) + ).toBe('owner-runtime') + }) + + it('returns null for an explicit local owner even while a runtime is focused', () => { + expect( + getExplicitRuntimeOwnerEnvironmentId( + { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'local' }] + }, + 'repo-1' + ) + ).toBeNull() + }) + + it('returns null for an SSH-owned repo (connectionId only)', () => { + expect( + getExplicitRuntimeOwnerEnvironmentId( + { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: 'ssh-1', executionHostId: null }] + }, + 'repo-1' + ) + ).toBeNull() + }) + + // Why: unlike getRuntimeEnvironmentIdForRepo, a no-owner repo must NOT fall + // back to the focused runtime — an owner-less repo is a local repo (#6957). + it('returns null for a legacy repo without an owner instead of the focused runtime', () => { + expect( + getExplicitRuntimeOwnerEnvironmentId( + { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: null }] + }, + 'repo-1' + ) + ).toBeNull() + }) + + it('routes duplicate repo ids to the runtime row that focus selects unambiguously', () => { + expect( + getExplicitRuntimeOwnerEnvironmentId( + { + settings: { activeRuntimeEnvironmentId: 'owner-runtime' }, + repos: [ + { id: 'repo-1', connectionId: null, executionHostId: 'local' }, + { id: 'repo-1', connectionId: null, executionHostId: 'runtime:owner-runtime' } + ] + }, + 'repo-1' + ) + ).toBe('owner-runtime') + }) + + it('returns null for ambiguous duplicate repo ids when focus matches no row', () => { + expect( + getExplicitRuntimeOwnerEnvironmentId( + { + settings: { activeRuntimeEnvironmentId: 'other-runtime' }, + repos: [ + { id: 'repo-1', connectionId: null, executionHostId: 'local' }, + { id: 'repo-1', connectionId: null, executionHostId: 'runtime:owner-runtime' } + ] + }, + 'repo-1' + ) + ).toBeNull() + }) + + it('returns null when the repo id is missing', () => { + expect( + getExplicitRuntimeOwnerEnvironmentId( + { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'runtime:owner-runtime' }] + }, + null + ) + ).toBeNull() + }) +}) + describe('getRepoOwnerRoutedSettings', () => { // Why: SourceControl builds its git/file mutation contexts from this value, // so it must rebind activeRuntimeEnvironmentId to the repo OWNER even while a diff --git a/src/renderer/src/lib/repo-runtime-owner.ts b/src/renderer/src/lib/repo-runtime-owner.ts index 36b7cf757..0ccfb2d09 100644 --- a/src/renderer/src/lib/repo-runtime-owner.ts +++ b/src/renderer/src/lib/repo-runtime-owner.ts @@ -46,6 +46,25 @@ export function getRuntimeEnvironmentIdForRepo( return state.settings?.activeRuntimeEnvironmentId?.trim() || null } +// Why: PR mutations must not fall back to the globally focused runtime — a +// repo without an explicit owner is a local repo, and routing it to the +// focused runtime sends the mutation to a host that does not own it (#6957). +export function getExplicitRuntimeOwnerEnvironmentId( + state: RepoRuntimeOwnerState, + repoId: string | null | undefined +): string | null { + if (!repoId) { + return null + } + const repo = findRepoOwner(state, repoId) + const hasExplicitOwner = Boolean(repo?.executionHostId?.trim() || repo?.connectionId?.trim()) + if (!repo || !hasExplicitOwner) { + return null + } + const parsed = parseExecutionHostId(getRepoExecutionHostId(repo)) + return parsed?.kind === 'runtime' ? parsed.environmentId : null +} + export function getSettingsForRepoRuntimeOwner( state: RepoRuntimeOwnerState, repoId: string | null | undefined diff --git a/src/renderer/src/lib/use-tab-agent-sleeping-session.test.ts b/src/renderer/src/lib/use-tab-agent-sleeping-session.test.ts new file mode 100644 index 000000000..4406a1339 --- /dev/null +++ b/src/renderer/src/lib/use-tab-agent-sleeping-session.test.ts @@ -0,0 +1,184 @@ +// @vitest-environment happy-dom + +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import type { + ResumableTuiAgent, + SleepingAgentSessionRecord +} from '../../../shared/agent-session-resume' +import { makePaneKey } from '../../../shared/stable-pane-id' +import type { TerminalTab, TuiAgent } from '../../../shared/types' +import { resolveTabAgentFromSignals, useTabAgent } from './use-tab-agent' + +const initialAppState = useAppStore.getInitialState() +const LEAF_ID = '11111111-1111-4111-8111-111111111111' +let latestHookAgent: TuiAgent | null | undefined +const hookRoots: Root[] = [] + +function HookProbe({ tab }: { tab: TerminalTab }): null { + latestHookAgent = useTabAgent(tab) + return null +} + +async function flushHookEffects(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +async function renderHookProbe(tab: TerminalTab): Promise { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + hookRoots.push(root) + await act(async () => { + root.render(createElement(HookProbe, { tab })) + }) + await flushHookEffects() + return root +} + +function sleepingRecord(paneKey: string, agent: ResumableTuiAgent): SleepingAgentSessionRecord { + return { + paneKey, + worktreeId: 'wt-1', + agent, + providerSession: { key: 'session_id', id: 'sess-1' }, + prompt: '', + state: 'working', + capturedAt: 1, + updatedAt: 1 + } +} + +describe('resolveTabAgentFromSignals sleeping-session precedence', () => { + it("prefers a hibernated pane's session identity over a stale reused launchAgent", () => { + // Why: a codex launch later reused for claude leaves a claude sleeping record + // for the pane. Its generic spinner title names no agent, so only the session + // record proves the launch identity went stale. + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: false, + title: '⠐ Explain GitHub issue simply', + hookAgent: null, + sleepingSessionAgent: 'claude', + launchAgent: 'codex' + }) + ).toBe('claude') + }) + + it('keeps live hook identity ahead of a sleeping-session record', () => { + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: false, + title: 'zsh', + hookAgent: 'codex', + sleepingSessionAgent: 'claude', + launchAgent: 'codex' + }) + ).toBe('codex') + }) + + it('keeps an explicit title ahead of a conflicting sleeping-session record', () => { + // Why: sleeping identity ranks below title — a live/last-known explicit title + // is at least as fresh as the hibernation snapshot. + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: false, + title: '✳ Claude Code', + hookAgent: null, + sleepingSessionAgent: 'gemini', + launchAgent: 'codex' + }) + ).toBe('claude') + }) + + it('keeps a genuine tab icon when its sleeping record matches the launchAgent', () => { + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: false, + title: '⠐ working', + hookAgent: null, + sleepingSessionAgent: 'codex', + launchAgent: 'codex' + }) + ).toBe('codex') + }) +}) + +describe('useTabAgent sleeping-session', () => { + const originalApi = window.api + const getForegroundProcess = vi.fn() + const clearTabLaunchAgent = vi.fn() + const baseTab: TerminalTab = { + id: 'tab-1', + ptyId: 'pty-1', + worktreeId: 'wt-1', + title: 'Terminal 1', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1, + launchAgent: 'codex' + } + + beforeEach(() => { + latestHookAgent = undefined + getForegroundProcess.mockReset() + clearTabLaunchAgent.mockReset() + useAppStore.setState(initialAppState, true) + useAppStore.setState({ + ptyIdsByTabId: { 'tab-1': ['pty-1'] }, + agentStatusByPaneKey: {}, + terminalLayoutsByTabId: {}, + clearTabLaunchAgent + }) + window.api = { + ...originalApi, + pty: { + ...originalApi?.pty, + getForegroundProcess + } + } as typeof window.api + }) + + afterEach(() => { + hookRoots.splice(0).forEach((root) => { + act(() => root.unmount()) + }) + document.body.replaceChildren() + useAppStore.setState(initialAppState, true) + window.api = originalApi + }) + + it('paints a hibernated pane with its sleeping-session agent over a stale launchAgent', async () => { + const paneKey = makePaneKey('tab-1', LEAF_ID) + // Why: the pane was launched as codex, then reused for claude and hibernated. + // No live hook/process remains and the frozen title names no agent, so the + // persisted session record is the only proof the launch identity went stale. + useAppStore.setState({ + terminalLayoutsByTabId: { + 'tab-1': { + root: { type: 'leaf', leafId: LEAF_ID }, + activeLeafId: LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: { [LEAF_ID]: 'pty-1' } + } + }, + agentStatusByPaneKey: {}, + sleepingAgentSessionsByPaneKey: { [paneKey]: sleepingRecord(paneKey, 'claude') } + }) + + await renderHookProbe({ ...baseTab, title: '⠐ Explain GitHub issue simply' }) + + expect(latestHookAgent).toBe('claude') + expect(getForegroundProcess).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/use-tab-agent.test.ts b/src/renderer/src/lib/use-tab-agent.test.ts index 73978e4f3..d4d6031b2 100644 --- a/src/renderer/src/lib/use-tab-agent.test.ts +++ b/src/renderer/src/lib/use-tab-agent.test.ts @@ -265,11 +265,87 @@ describe('resolveTabAgentFromSignals', () => { isRemote: false, title: '✳ Claude Code', hookAgent: null, + launchAgent: 'codex' }) ).toBe('codex') }) + it('keeps OMP launch identity over Pi-compatible wrapper titles after activity', () => { + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: true, + title: '⠋ Pi', + hookAgent: null, + launchAgent: 'omp' + }) + ).toBe('omp') + + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: true, + title: '⠋ Pi', + hookAgent: 'pi', + launchAgent: 'omp' + }) + ).toBe('omp') + + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: false, + title: '⠋ Pi', + hookAgent: 'pi', + launchAgent: 'omp' + }) + ).toBe('omp') + + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: true, + title: 'Terminal 1', + hookAgent: null, + siblingHookAgent: 'pi', + launchAgent: 'omp' + }) + ).toBe('omp') + + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: true, + title: '⠋ OMP', + hookAgent: 'omp', + launchAgent: 'pi' + }) + ).toBe('pi') + + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: true, + title: 'zsh', + hookAgent: null, + focusedCompletedHookAgent: 'pi', + launchAgent: 'omp' + }) + ).toBe('omp') + + expect( + resolveTabAgentFromSignals({ + hasObservedAgentSignal: true, + isRemote: false, + title: 'zsh', + hookAgent: null, + siblingCompletedHookAgent: 'pi', + launchAgent: 'omp' + }) + ).toBe('omp') + }) + it('prefers explicit hook identity over a conflicting title mention', () => { expect( resolveTabAgentFromSignals({ diff --git a/src/renderer/src/lib/use-tab-agent.ts b/src/renderer/src/lib/use-tab-agent.ts index 40bf92d6f..504204971 100644 --- a/src/renderer/src/lib/use-tab-agent.ts +++ b/src/renderer/src/lib/use-tab-agent.ts @@ -11,6 +11,7 @@ import { resolveSiblingTabAgent } from './tab-agent' import { resolveExplicitTerminalTitleAgentType } from '../../../shared/terminal-title-agent-type' +import { resolveCompatibleAgentTypeForOwner } from '../../../shared/agent-title-owner' import type { TerminalTab, TuiAgent } from '../../../shared/types' // A shell name, or the tab's neutral default title — where Orca's @@ -20,6 +21,19 @@ function titleShowsNoAgent(title: string, defaultTitle?: string): boolean { return trimmed.length > 0 && (isShellProcess(trimmed) || trimmed === defaultTitle?.trim()) } +/** + * Resolves wrapper-compatible signal identity against the launch owner. + */ +function resolveSignalAgentForLaunchOwner( + signalAgent: TuiAgent | null | undefined, + launchAgent: TuiAgent | null +): TuiAgent | null { + if (!signalAgent) { + return null + } + return (resolveCompatibleAgentTypeForOwner(signalAgent, launchAgent) ?? signalAgent) as TuiAgent +} + /** * Probe-free evidence that a launched agent exited: the title shows no agent, * no live hook row remains in the tab, and either the hook completed or @@ -65,14 +79,17 @@ export function resolveTabAgentFromSignals(args: { siblingCompletedHookAgent?: TuiAgent | null processAgent?: TuiAgent | null processShellForeground?: boolean + sleepingSessionAgent?: TuiAgent | null launchAgent?: TuiAgent }): TuiAgent | null { const launchAgent = args.launchAgent ?? null - const explicitTitleAgent = resolveExplicitTerminalTitleAgentType(args.title) - // Why: when a pane is reused for a different agent, its launchAgent goes stale. - // A live title that explicitly names a *different* agent, once the pane has - // shown any activity, overrides that stale launch identity so the tab icon - // tracks what is actually running (codex launch reused for claude, etc.). + const explicitTitleAgent = resolveSignalAgentForLaunchOwner( + resolveExplicitTerminalTitleAgentType(args.title), + launchAgent + ) + // Why: explicit titles can override stale launches after activity, but + // Pi-compatible wrapper signals first resolve through the launch owner so + // OMP-created sessions do not repaint as Pi. // Why: OSC 133;D proved this local pane's foreground is back at the shell, // so any title-derived identity is stale by definition — a TUI that died // with a stuck title must not keep painting the tab through the title layer. @@ -96,30 +113,46 @@ export function resolveTabAgentFromSignals(args: { const completedHookAgent = !args.isRemote && (noAgentTitle || processProvesShell) && hasCompletedHook ? null - : (args.focusedCompletedHookAgent ?? args.siblingCompletedHookAgent ?? null) - const focusedHookAgent = args.hookAgent ?? null - const fallbackHookAgent = args.siblingHookAgent ?? completedHookAgent ?? null + : resolveSignalAgentForLaunchOwner( + args.focusedCompletedHookAgent ?? args.siblingCompletedHookAgent, + launchAgent + ) + const focusedHookAgent = resolveSignalAgentForLaunchOwner(args.hookAgent, launchAgent) + const siblingHookAgent = resolveSignalAgentForLaunchOwner(args.siblingHookAgent, launchAgent) + const fallbackHookAgent = siblingHookAgent ?? completedHookAgent const launchedAgentExited = resolveLaunchedAgentExitEvidence({ title: args.title, defaultTitle: args.defaultTitle, isRemote: args.isRemote, hasObservedAgentSignal: args.hasObservedAgentSignal, hookAgent: focusedHookAgent, - siblingHookAgent: args.siblingHookAgent, + siblingHookAgent, hasCompletedHook, processAgent: args.processAgent, processShellForeground: args.processShellForeground }) const activeLaunchAgent = launchedAgentExited ? null : launchAgent const processAgent = args.processAgent ?? null + const sleepingSessionAgent = args.sleepingSessionAgent ?? null // Why: titleAgent ranks ahead of launch/fallback hooks because, once the // pane has shown activity, a live explicit title is the freshest identity // signal — it beats a launchAgent gone stale through pane reuse. Before any // activity, titleAgent is null while launchAgent exists, so launch bootstrap // still wins the startup window. Process identity (the recognized foreground // process) is ground truth below hooks — it covers agents that emit neither - // hooks nor titles. - return focusedHookAgent ?? processAgent ?? titleAgent ?? activeLaunchAgent ?? fallbackHookAgent + // hooks nor titles. sleepingSessionAgent ranks above launch bootstrap: a + // hibernated pane's captured session identity is pane-scoped proof that the + // launch identity went stale (a codex launch later reused for claude), and it + // is the only live signal while the pane is asleep (its PTY, hooks, and + // process are all gone). + return ( + focusedHookAgent ?? + processAgent ?? + titleAgent ?? + sleepingSessionAgent ?? + activeLaunchAgent ?? + fallbackHookAgent + ) } /** @@ -135,10 +168,15 @@ export function resolveTabAgentFromSignals(args: { * command boundaries (local panes only); covers agents that emit neither * hooks nor titles, and its shell-foreground mark is title-independent * exit evidence. - * 3. launchAgent — what Orca launched here; instant bootstrap before hooks + * 3. Sleeping session identity — a hibernated pane's captured session record + * (agent + provider session). Ranks below title but above launchAgent + * because it is pane-scoped proof of reuse: a codex launch later reused for + * claude leaves a claude sleeping record, and while the pane is asleep this + * is the only live identity signal (its PTY, hooks, and process are gone). + * 4. launchAgent — what Orca launched here; instant bootstrap before hooks * arrive, cleared once hook/process/title evidence shows the launched * agent exited. - * 4. Title — legacy/unknown-session fallback, and the live override when a pane + * 5. Title — legacy/unknown-session fallback, and the live override when a pane * is reused: once the pane has shown activity, a title that explicitly names * a different agent than launchAgent wins over that stale launch identity. * Otherwise it is ignored while launchAgent exists, and generic spinner-only @@ -179,6 +217,12 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null { ? Boolean(s.paneForegroundAgentByPaneKey[focusedPaneKey]?.shellForeground) : false ) + // Why: a hibernated pane's persisted session record is pane-scoped evidence of + // which agent actually ran here — the freshest identity once the PTY, hook, + // and process signals are all gone, and proof a stale launchAgent was reused. + const sleepingSessionAgent = useAppStore((s) => + focusedPaneKey ? (s.sleepingAgentSessionsByPaneKey[focusedPaneKey]?.agent ?? null) : null + ) // The focused pane's PTY (single-pane tabs have exactly one leaf). Only used // to reset per-process-generation signals when the pane is respawned. @@ -299,6 +343,7 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null { siblingCompletedHookAgent, processAgent, processShellForeground, + sleepingSessionAgent, launchAgent: tab.launchAgent }) } diff --git a/src/renderer/src/lib/workspace-session-editor-drafts.test.ts b/src/renderer/src/lib/workspace-session-editor-drafts.test.ts index 88ce7a68d..99dd4ec59 100644 --- a/src/renderer/src/lib/workspace-session-editor-drafts.test.ts +++ b/src/renderer/src/lib/workspace-session-editor-drafts.test.ts @@ -78,4 +78,49 @@ describe('workspace session editor drafts', () => { }) ]) }) + + it('persists the disk baseline signature only alongside a dirty draft', () => { + const payload = buildWorkspaceSessionPayload( + createSnapshot({ + openFiles: [ + { + id: '/tmp/dirty.md', + filePath: '/tmp/dirty.md', + relativePath: 'dirty.md', + worktreeId: 'wt-1', + language: 'markdown', + mode: 'edit', + isDirty: true, + lastKnownDiskSignature: 'abc123' + } as never, + { + id: '/tmp/clean.md', + filePath: '/tmp/clean.md', + relativePath: 'clean.md', + worktreeId: 'wt-1', + language: 'markdown', + mode: 'edit', + isDirty: false, + lastKnownDiskSignature: 'def456' + } as never + ], + editorDrafts: { + '/tmp/dirty.md': 'unsaved edits' + } + }) + ) + + expect(payload.openFilesByWorktree?.['wt-1']).toEqual([ + expect.objectContaining({ + filePath: '/tmp/dirty.md', + dirtyDraftContent: 'unsaved edits', + lastKnownDiskSignature: 'abc123' + }), + // Why: a clean tab has no draft to conflict-check on restore, and + // persisting the signature anyway would bloat every session write. + expect.not.objectContaining({ + lastKnownDiskSignature: expect.any(String) + }) + ]) + }) }) diff --git a/src/renderer/src/lib/workspace-session.ts b/src/renderer/src/lib/workspace-session.ts index 88cb8ca5e..4970840d5 100644 --- a/src/renderer/src/lib/workspace-session.ts +++ b/src/renderer/src/lib/workspace-session.ts @@ -135,7 +135,13 @@ export function buildEditorSessionData( language: f.language, isPreview: f.isPreview || undefined, runtimeEnvironmentId: f.runtimeEnvironmentId, - ...(dirtyDraftContent !== undefined ? { dirtyDraftContent } : {}) + ...(dirtyDraftContent !== undefined ? { dirtyDraftContent } : {}), + // Why: the edit baseline travels with the dirty draft so a restore can + // re-derive a changed-on-disk conflict before autosave may overwrite an + // agent write that landed while the app was closed. + ...(dirtyDraftContent !== undefined && f.lastKnownDiskSignature + ? { lastKnownDiskSignature: f.lastKnownDiskSignature } + : {}) }) const ids = editFileIdsByWorktree[f.worktreeId] ?? (editFileIdsByWorktree[f.worktreeId] = new Set()) diff --git a/src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts b/src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts index f447d4e26..e9052326f 100644 --- a/src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts +++ b/src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts @@ -38,7 +38,7 @@ type TerminalMultiplexEvent = export type RemoteRuntimeMultiplexedTerminalCallbacks = { onData: (data: string, meta?: { seq?: number; rawLength?: number }) => void - onSnapshot: (data: string) => void + onSnapshot: (data: string, meta?: { pendingEscapeTailAnsi?: string }) => void onSubscribed?: () => void onEnd?: () => void onError?: (message: string) => void @@ -89,6 +89,10 @@ type RemoteRuntimeSnapshotInfo = { source?: 'headless' | 'renderer' requestId?: number truncated?: boolean + // Why: a mid-escape tail the emulator could not serialize; the transport + // must write it AFTER the replay reset so the next live chunk completes it + // instead of rendering literally (#7329). + pendingEscapeTailAnsi?: string } type RemoteRuntimeSnapshotRequest = { @@ -100,6 +104,7 @@ type RemoteRuntimeSnapshotRequest = { rows: number seq?: number source?: 'headless' | 'renderer' + pendingEscapeTailAnsi?: string } | null ) => void reject: (error: Error) => void @@ -466,17 +471,22 @@ class RemoteRuntimeTerminalMultiplexer { cols: info?.cols ?? 80, rows: info?.rows ?? 24, seq: info?.seq, - source: info?.source + source: info?.source, + pendingEscapeTailAnsi: info?.pendingEscapeTailAnsi }) clearPendingSnapshotRequest(stream) } else if (target === 'initial') { - stream.callbacks.onSnapshot(data ?? '') + stream.callbacks.onSnapshot(data ?? '', { + pendingEscapeTailAnsi: info?.pendingEscapeTailAnsi + }) } else if (target === 'recovery') { // Why: a server-pushed recovery snapshot replaces terminal state // mid-session; clear the screen and scrollback before applying it. // An empty snapshot is still applied so stale dropped output does // not linger on a terminal the model says is blank. - stream.callbacks.onSnapshot(`\x1b[2J\x1b[3J\x1b[H${data ?? ''}`) + stream.callbacks.onSnapshot(`\x1b[2J\x1b[3J\x1b[H${data ?? ''}`, { + pendingEscapeTailAnsi: info?.pendingEscapeTailAnsi + }) } } else if (matchesPendingRequest) { pendingRequest.resolve(null) @@ -729,6 +739,7 @@ function decodeSnapshotInfo( source?: unknown requestId?: unknown truncated?: unknown + pendingEscapeTailAnsi?: unknown }>(payload) if (!raw) { return null @@ -739,7 +750,9 @@ function decodeSnapshotInfo( seq: typeof raw.seq === 'number' ? raw.seq : undefined, source: raw.source === 'headless' || raw.source === 'renderer' ? raw.source : undefined, requestId: typeof raw.requestId === 'number' ? raw.requestId : undefined, - truncated: raw.truncated === true + truncated: raw.truncated === true, + pendingEscapeTailAnsi: + typeof raw.pendingEscapeTailAnsi === 'string' ? raw.pendingEscapeTailAnsi : undefined } } diff --git a/src/renderer/src/runtime/runtime-client-events.test.ts b/src/renderer/src/runtime/runtime-client-events.test.ts index 70acb4006..3d3888884 100644 --- a/src/renderer/src/runtime/runtime-client-events.test.ts +++ b/src/renderer/src/runtime/runtime-client-events.test.ts @@ -55,4 +55,47 @@ describe('subscribeRuntimeClientEvents', () => { subscription.unsubscribe() expect(unsubscribe).toHaveBeenCalledTimes(1) }) + + it('signals a replay-tagged response so event-derived state can resync after a reconnect', async () => { + let capturedOnResponse: ((response: unknown) => void) | undefined + const subscribe = vi.fn(async (_args, nextCallbacks) => { + capturedOnResponse = (nextCallbacks as { onResponse: (response: unknown) => void }).onResponse + return { unsubscribe: vi.fn(), sendBinary: vi.fn() } + }) + const onEvent = vi.fn() + const onReplayed = vi.fn() + + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { subscribe } + } + }) + + await subscribeRuntimeClientEvents('env-1', onEvent, vi.fn(), onReplayed) + if (!capturedOnResponse) { + throw new Error('Expected subscription callbacks') + } + + capturedOnResponse({ + ok: true, + result: { type: 'ready', subscriptionId: 'sub-1' } + }) + expect(onReplayed).not.toHaveBeenCalled() + + capturedOnResponse({ + ok: true, + result: { type: 'ready', subscriptionId: 'sub-1' }, + _replayedAfterReconnect: true + }) + expect(onReplayed).toHaveBeenCalledTimes(1) + + // A replay-tagged event frame both signals and still delivers the event. + capturedOnResponse({ + ok: true, + result: { type: 'worktreesChanged', repoId: 'repo-1' }, + _replayedAfterReconnect: true + }) + expect(onReplayed).toHaveBeenCalledTimes(2) + expect(onEvent).toHaveBeenCalledWith({ type: 'worktreesChanged', repoId: 'repo-1' }) + }) }) diff --git a/src/renderer/src/runtime/runtime-client-events.ts b/src/renderer/src/runtime/runtime-client-events.ts index 51827546a..adbdc2324 100644 --- a/src/renderer/src/runtime/runtime-client-events.ts +++ b/src/renderer/src/runtime/runtime-client-events.ts @@ -3,6 +3,7 @@ import type { RuntimeClientEventStreamMessage } from '../../../shared/runtime-client-events' import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import { isRuntimeSubscriptionReplayResponse } from '../../../shared/runtime-subscription-replay' export type RuntimeClientEventSubscription = { unsubscribe: () => void @@ -11,7 +12,12 @@ export type RuntimeClientEventSubscription = { export async function subscribeRuntimeClientEvents( environmentId: string, onEvent: (event: RuntimeClientEvent) => void, - onError: (error: unknown) => void = console.warn + onError: (error: unknown) => void = console.warn, + // Why: client events emitted while the shared-control transport was down are + // lost, not queued. The replay tag on the first post-reconnect response is + // the renderer's only signal that mirrored event-derived state (e.g. the + // per-environment SSH bucket) may have missed transitions and must resync. + onReplayedAfterReconnect?: () => void ): Promise { const handle = await window.api.runtimeEnvironments.subscribe( { @@ -21,7 +27,7 @@ export async function subscribeRuntimeClientEvents( }, { onResponse: (response) => { - handleRuntimeClientEventResponse(response, onEvent, onError) + handleRuntimeClientEventResponse(response, onEvent, onError, onReplayedAfterReconnect) }, onError } @@ -32,12 +38,16 @@ export async function subscribeRuntimeClientEvents( function handleRuntimeClientEventResponse( response: RuntimeRpcResponse, onEvent: (event: RuntimeClientEvent) => void, - onError: (error: unknown) => void + onError: (error: unknown) => void, + onReplayedAfterReconnect?: () => void ): void { if (response.ok === false) { onError(response.error) return } + if (isRuntimeSubscriptionReplayResponse(response)) { + onReplayedAfterReconnect?.() + } const message = response.result as RuntimeClientEventStreamMessage if (message.type === 'ready' || message.type === 'end') { return @@ -53,6 +63,7 @@ function isRuntimeClientEvent( return ( message.type === 'reposChanged' || message.type === 'worktreesChanged' || + message.type === 'sshStateChanged' || message.type === 'linearLinkedIssueUpdated' || message.type === 'activateWorktree' ) diff --git a/src/renderer/src/runtime/runtime-environment-ssh-state.test.ts b/src/renderer/src/runtime/runtime-environment-ssh-state.test.ts new file mode 100644 index 000000000..1e2a9939b --- /dev/null +++ b/src/renderer/src/runtime/runtime-environment-ssh-state.test.ts @@ -0,0 +1,255 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { SshConnectionState } from '../../../shared/ssh-types' +import { useAppStore } from '@/store' +import { + applyRuntimeEnvironmentSshStateChanged, + connectRuntimeEnvironmentSshTarget, + hydrateRuntimeEnvironmentSshState, + resyncRuntimeEnvironmentSshTargets +} from './runtime-environment-ssh-state' +import { callRuntimeRpc } from './runtime-rpc-client' + +vi.mock('./runtime-rpc-client', async (importOriginal) => ({ + ...(await importOriginal>()), + callRuntimeRpc: vi.fn() +})) + +const callRuntimeRpcMock = vi.mocked(callRuntimeRpc) + +function connState( + targetId: string, + status: SshConnectionState['status'] = 'connected' +): SshConnectionState { + return { targetId, status, error: null, reconnectAttempt: 0 } +} + +type RpcResponses = { + targets?: { id: string; label: string }[] + labels?: Record + states?: Record + failListTargets?: boolean + failRemovedLabels?: boolean +} + +function installRpcResponses(responses: RpcResponses): void { + callRuntimeRpcMock.mockImplementation((_target, method, params) => { + switch (method) { + case 'ssh.listTargets': + if (responses.failListTargets) { + return Promise.reject(new Error('method not found')) + } + return Promise.resolve({ targets: responses.targets ?? [] } as never) + case 'ssh.listRemovedTargetLabels': + if (responses.failRemovedLabels) { + return Promise.reject(new Error('method not found')) + } + return Promise.resolve({ labels: responses.labels ?? {} } as never) + case 'ssh.getState': { + const targetId = (params as { targetId: string }).targetId + return Promise.resolve({ state: responses.states?.[targetId] ?? null } as never) + } + default: + return Promise.reject(new Error(`unexpected method ${method}`)) + } + }) +} + +let envCounter = 0 +function nextEnvId(): string { + envCounter += 1 + return `env-${envCounter}` +} + +beforeEach(() => { + useAppStore.setState(useAppStore.getInitialState(), true) + callRuntimeRpcMock.mockReset() +}) + +describe('hydrateRuntimeEnvironmentSshState', () => { + it('populates the environment bucket with targets, tombstones, and per-target states', async () => { + const envId = nextEnvId() + installRpcResponses({ + targets: [ + { id: 'ssh-1', label: 'devbox' }, + { id: 'ssh-2', label: 'buildbox' } + ], + labels: { 'ssh-old': 'retired box' }, + states: { 'ssh-1': connState('ssh-1', 'connected') } + }) + + await hydrateRuntimeEnvironmentSshState(envId) + + const bucket = useAppStore.getState().sshStateByEnvironment.get(envId) + expect(bucket?.targetsHydrated).toBe(true) + expect(bucket?.targetLabels.get('ssh-1')).toBe('devbox') + expect(bucket?.removedTargetLabels.get('ssh-old')).toBe('retired box') + expect(bucket?.connectionStates.get('ssh-1')?.status).toBe('connected') + // ssh-2 had no live state: absent, so reads fall back to 'disconnected'. + expect(bucket?.connectionStates.has('ssh-2')).toBe(false) + // Local maps stay untouched. + expect(useAppStore.getState().sshTargetLabels.size).toBe(0) + expect(useAppStore.getState().sshTargetsHydrated).toBe(false) + // Every call was routed to the owning environment. + for (const [target] of callRuntimeRpcMock.mock.calls) { + expect(target).toEqual({ kind: 'environment', environmentId: envId }) + } + }) + + it('skips refetching when already hydrated unless forced', async () => { + const envId = nextEnvId() + installRpcResponses({ targets: [] }) + await hydrateRuntimeEnvironmentSshState(envId) + const callsAfterFirst = callRuntimeRpcMock.mock.calls.length + + await hydrateRuntimeEnvironmentSshState(envId) + expect(callRuntimeRpcMock.mock.calls.length).toBe(callsAfterFirst) + + await hydrateRuntimeEnvironmentSshState(envId, { force: true }) + expect(callRuntimeRpcMock.mock.calls.length).toBeGreaterThan(callsAfterFirst) + }) + + it('leaves the bucket un-hydrated when the host lacks the ssh RPC methods', async () => { + const envId = nextEnvId() + installRpcResponses({ failListTargets: true }) + + await expect(hydrateRuntimeEnvironmentSshState(envId)).rejects.toThrow() + + const bucket = useAppStore.getState().sshStateByEnvironment.get(envId) + expect(bucket?.targetsHydrated ?? false).toBe(false) + }) + + it('still hydrates the target list when the removed-labels fetch fails', async () => { + const envId = nextEnvId() + installRpcResponses({ + targets: [{ id: 'ssh-1', label: 'devbox' }], + failRemovedLabels: true + }) + + await hydrateRuntimeEnvironmentSshState(envId) + + const bucket = useAppStore.getState().sshStateByEnvironment.get(envId) + expect(bucket?.targetsHydrated).toBe(true) + expect(bucket?.targetLabels.get('ssh-1')).toBe('devbox') + }) +}) + +describe('applyRuntimeEnvironmentSshStateChanged', () => { + it('applies a known target state directly into the owning bucket without RPC', () => { + const envId = nextEnvId() + useAppStore + .getState() + .setEnvironmentSshTargetsMetadata(envId, [{ id: 'ssh-1', label: 'devbox' }]) + + applyRuntimeEnvironmentSshStateChanged(envId, 'ssh-1', connState('ssh-1', 'disconnected')) + + expect( + useAppStore.getState().sshStateByEnvironment.get(envId)?.connectionStates.get('ssh-1')?.status + ).toBe('disconnected') + expect(callRuntimeRpcMock).not.toHaveBeenCalled() + // Local map untouched. + expect(useAppStore.getState().sshConnectionStates.size).toBe(0) + }) + + it('does not touch another environment bucket or local state (no cross-pollution)', () => { + const envA = nextEnvId() + const envB = nextEnvId() + useAppStore.getState().setEnvironmentSshTargetsMetadata(envA, [{ id: 'ssh-1', label: 'a' }]) + useAppStore.getState().setEnvironmentSshTargetsMetadata(envB, [{ id: 'ssh-1', label: 'b' }]) + const bucketBBefore = useAppStore.getState().sshStateByEnvironment.get(envB) + const localStatesBefore = useAppStore.getState().sshConnectionStates + + applyRuntimeEnvironmentSshStateChanged(envA, 'ssh-1', connState('ssh-1', 'connected')) + + const state = useAppStore.getState() + expect(state.sshStateByEnvironment.get(envA)?.connectionStates.get('ssh-1')?.status).toBe( + 'connected' + ) + expect(state.sshStateByEnvironment.get(envB)).toBe(bucketBBefore) + expect(state.sshStateByEnvironment.get(envB)?.connectionStates.size).toBe(0) + expect(state.sshConnectionStates).toBe(localStatesBefore) + expect(state.sshConnectionStates.size).toBe(0) + }) + + it('re-fetches the authoritative target list for an unknown target instead of trusting the event', async () => { + const envId = nextEnvId() + // The event races a removal: the authoritative list does not contain it. + installRpcResponses({ targets: [], labels: { 'ssh-gone': 'old devbox' } }) + + applyRuntimeEnvironmentSshStateChanged(envId, 'ssh-gone', connState('ssh-gone', 'disconnected')) + await vi.waitFor(() => { + expect(useAppStore.getState().sshStateByEnvironment.get(envId)?.targetsHydrated).toBe(true) + }) + + const bucket = useAppStore.getState().sshStateByEnvironment.get(envId) + // The trailing event must not resurrect the removed target's state. + expect(bucket?.connectionStates.has('ssh-gone')).toBe(false) + expect(bucket?.removedTargetLabels.get('ssh-gone')).toBe('old devbox') + }) + + it('picks up a just-added target through the forced refresh', async () => { + const envId = nextEnvId() + installRpcResponses({ + targets: [{ id: 'ssh-new', label: 'fresh box' }], + states: { 'ssh-new': connState('ssh-new', 'connecting') } + }) + + applyRuntimeEnvironmentSshStateChanged(envId, 'ssh-new', connState('ssh-new', 'connecting')) + await vi.waitFor(() => { + expect( + useAppStore.getState().sshStateByEnvironment.get(envId)?.targetLabels.get('ssh-new') + ).toBe('fresh box') + }) + + expect( + useAppStore.getState().sshStateByEnvironment.get(envId)?.connectionStates.get('ssh-new') + ?.status + ).toBe('connecting') + }) +}) + +describe('connectRuntimeEnvironmentSshTarget', () => { + it('routes ssh.connect to the owning environment and mirrors the returned state', async () => { + const envId = nextEnvId() + callRuntimeRpcMock.mockResolvedValue({ state: connState('ssh-1', 'connected') } as never) + + const state = await connectRuntimeEnvironmentSshTarget(envId, 'ssh-1') + + expect(state?.status).toBe('connected') + expect(callRuntimeRpcMock).toHaveBeenCalledWith( + { kind: 'environment', environmentId: envId }, + 'ssh.connect', + { targetId: 'ssh-1' }, + expect.anything() + ) + expect( + useAppStore.getState().sshStateByEnvironment.get(envId)?.connectionStates.get('ssh-1')?.status + ).toBe('connected') + expect(useAppStore.getState().sshConnectionStates.size).toBe(0) + }) + + it('propagates connect failures without writing any state', async () => { + const envId = nextEnvId() + callRuntimeRpcMock.mockRejectedValue(new Error('SSH target not found')) + + await expect(connectRuntimeEnvironmentSshTarget(envId, 'ssh-dead')).rejects.toThrow( + 'SSH target not found' + ) + expect(useAppStore.getState().sshStateByEnvironment.has(envId)).toBe(false) + }) +}) + +describe('resyncRuntimeEnvironmentSshTargets', () => { + it('applies the target list even when the removed-labels refresh fails', async () => { + const envId = nextEnvId() + installRpcResponses({ + targets: [{ id: 'ssh-live', label: 'devbox' }], + failRemovedLabels: true + }) + + await resyncRuntimeEnvironmentSshTargets(envId) + + const bucket = useAppStore.getState().sshStateByEnvironment.get(envId) + expect(bucket?.targetLabels.get('ssh-live')).toBe('devbox') + expect(bucket?.targetsHydrated).toBe(true) + }) +}) diff --git a/src/renderer/src/runtime/runtime-environment-ssh-state.ts b/src/renderer/src/runtime/runtime-environment-ssh-state.ts new file mode 100644 index 000000000..263d44483 --- /dev/null +++ b/src/renderer/src/runtime/runtime-environment-ssh-state.ts @@ -0,0 +1,165 @@ +import { useAppStore } from '@/store' +import type { SshConnectionState, SshTarget } from '../../../shared/ssh-types' +import { callRuntimeRpc } from './runtime-rpc-client' + +/** + * Mirrors a remote Orca server's own SSH targets into that environment's + * per-environment SSH bucket (store slice `runtime-environment-ssh`), so a + * desktop client attached to the server gets live reconnect overlays for the + * server's SSH-backed workspaces (STA-1468, desktop topology). Never touches + * the local SSH maps. + */ + +const SSH_RPC_TIMEOUT_MS = 15_000 + +function environmentTarget(environmentId: string): { kind: 'environment'; environmentId: string } { + return { kind: 'environment', environmentId } +} + +async function fetchEnvironmentSshTargets(environmentId: string): Promise { + const { targets } = await callRuntimeRpc<{ targets: SshTarget[] }>( + environmentTarget(environmentId), + 'ssh.listTargets', + undefined, + { timeoutMs: SSH_RPC_TIMEOUT_MS } + ) + return targets +} + +/** Applies the environment's target list, then best-effort removal tombstones. + * Targets land first — a removed-labels failure must not discard them + * (they alone are enough evidence for the ghost-host derivation). */ +async function syncEnvironmentSshTargetMetadata(environmentId: string): Promise { + const targets = await fetchEnvironmentSshTargets(environmentId) + useAppStore.getState().setEnvironmentSshTargetsMetadata(environmentId, targets) + try { + const { labels } = await callRuntimeRpc<{ labels: Record }>( + environmentTarget(environmentId), + 'ssh.listRemovedTargetLabels', + undefined, + { timeoutMs: SSH_RPC_TIMEOUT_MS } + ) + useAppStore.getState().setEnvironmentRemovedSshTargetLabels(environmentId, labels) + } catch { + // Best-effort — a missing map just falls back to the raw target id. + } + return targets +} + +async function fetchEnvironmentSshConnectionStates( + environmentId: string, + targets: readonly SshTarget[] +): Promise { + for (const target of targets) { + try { + const { state } = await callRuntimeRpc<{ state: SshConnectionState | null }>( + environmentTarget(environmentId), + 'ssh.getState', + { targetId: target.id }, + { timeoutMs: SSH_RPC_TIMEOUT_MS } + ) + if (state) { + useAppStore.getState().setEnvironmentSshConnectionState(environmentId, target.id, state) + } + } catch { + // A missing state just reads as 'disconnected'; the overlay's Connect + // action and push events converge it. + } + } +} + +type HydrationEntry = { promise: Promise; rerunRequested: boolean } +const hydrationsInFlight = new Map() + +async function runEnvironmentSshHydration(environmentId: string): Promise { + const targets = await syncEnvironmentSshTargetMetadata(environmentId) + await fetchEnvironmentSshConnectionStates(environmentId, targets) +} + +/** + * Fetches the environment's SSH targets, removal tombstones, and per-target + * connection states into its bucket. Single-flight per environment; a `force` + * request during an in-flight run schedules exactly one follow-up run so a + * refresh triggered by a just-added target can't be swallowed by a stale + * in-flight fetch. + * + * Hosts without the ssh.* RPC methods fail here and leave the bucket + * un-hydrated — reads then resolve to "unknown", never to destructive UI. + */ +export async function hydrateRuntimeEnvironmentSshState( + environmentId: string, + options: { force?: boolean } = {} +): Promise { + const inFlight = hydrationsInFlight.get(environmentId) + if (inFlight) { + if (options.force) { + inFlight.rerunRequested = true + } + return inFlight.promise + } + const bucket = useAppStore.getState().sshStateByEnvironment.get(environmentId) + if (!options.force && bucket?.targetsHydrated) { + return + } + const entry: HydrationEntry = { promise: Promise.resolve(), rerunRequested: false } + entry.promise = (async () => { + try { + await runEnvironmentSshHydration(environmentId) + while (entry.rerunRequested) { + entry.rerunRequested = false + await runEnvironmentSshHydration(environmentId) + } + } finally { + hydrationsInFlight.delete(environmentId) + } + })() + hydrationsInFlight.set(environmentId, entry) + return entry.promise +} + +/** + * Applies a `sshStateChanged` runtime client event from `environmentId` to + * that environment's bucket. For a target the bucket doesn't know yet + * (added after hydration, or a disconnect racing a removal), the authoritative + * target list is re-fetched instead of trusting the event: the forced + * hydration also re-reads the state, so a removed target's trailing event + * can't resurrect it. + */ +export function applyRuntimeEnvironmentSshStateChanged( + environmentId: string, + targetId: string, + state: SshConnectionState +): void { + const store = useAppStore.getState() + const bucket = store.sshStateByEnvironment.get(environmentId) + if (bucket?.targetsHydrated && bucket.targetLabels.has(targetId)) { + store.setEnvironmentSshConnectionState(environmentId, targetId, state) + return + } + void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {}) +} + +/** Connects the environment's own SSH target via its runtime RPC and mirrors + * the returned state into the bucket (ssh.connect can resolve before the + * push event lands). */ +export async function connectRuntimeEnvironmentSshTarget( + environmentId: string, + targetId: string +): Promise { + const { state } = await callRuntimeRpc<{ state: SshConnectionState | null }>( + environmentTarget(environmentId), + 'ssh.connect', + { targetId }, + { timeoutMs: 60_000 } + ) + if (state) { + useAppStore.getState().setEnvironmentSshConnectionState(environmentId, targetId, state) + } + return state +} + +/** Resyncs the environment's target metadata after a failed connect so a + * stale overlay converges to the ghost/re-adopted state (STA-1468). */ +export async function resyncRuntimeEnvironmentSshTargets(environmentId: string): Promise { + await syncEnvironmentSshTargetMetadata(environmentId) +} diff --git a/src/renderer/src/runtime/runtime-file-client.test.ts b/src/renderer/src/runtime/runtime-file-client.test.ts index f1ce3f69e..90366acbf 100644 --- a/src/renderer/src/runtime/runtime-file-client.test.ts +++ b/src/renderer/src/runtime/runtime-file-client.test.ts @@ -3,6 +3,7 @@ preload API plus remote fallbacks; keeping route coverage together makes local versus environment behavior easy to audit. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { + cancelRuntimeFileList, copyRuntimePath, createRuntimePath, deleteRuntimePath, @@ -37,6 +38,8 @@ const fsDeletePath = vi.fn() const fsStat = vi.fn() const fsPathExists = vi.fn() const fsSearch = vi.fn() +const fsListFiles = vi.fn() +const fsCancelListFiles = vi.fn() const fsDownloadFile = vi.fn() const fsSaveDownloadedFile = vi.fn() const fsStartDownloadedFile = vi.fn() @@ -63,6 +66,9 @@ beforeEach(() => { fsStat.mockReset() fsPathExists.mockReset() fsSearch.mockReset() + fsListFiles.mockReset() + fsCancelListFiles.mockReset() + fsCancelListFiles.mockResolvedValue(undefined) fsDownloadFile.mockReset() fsSaveDownloadedFile.mockReset() fsStartDownloadedFile.mockReset() @@ -102,6 +108,8 @@ beforeEach(() => { stat: fsStat, pathExists: fsPathExists, search: fsSearch, + listFiles: fsListFiles, + cancelListFiles: fsCancelListFiles, downloadFile: fsDownloadFile, saveDownloadedFile: fsSaveDownloadedFile, startDownloadedFile: fsStartDownloadedFile, @@ -1357,6 +1365,56 @@ describe('runtime file client', () => { }) }) + it('passes the cancellation token through the IPC file listing path (#7721)', async () => { + fsListFiles.mockResolvedValue(['src/index.ts']) + + await expect( + listRuntimeFiles( + { + settings: {}, + worktreeId: 'wt-1', + worktreePath: '/remote/repo', + connectionId: 'ssh-1' + }, + { + rootPath: '/remote/repo', + requestToken: 'token-1' + } + ) + ).resolves.toEqual(['src/index.ts']) + + expect(fsListFiles).toHaveBeenCalledWith({ + rootPath: '/remote/repo', + connectionId: 'ssh-1', + excludePaths: undefined, + requestToken: 'token-1' + }) + }) + + it('cancelRuntimeFileList aborts the IPC listing but not environment listings (#7721)', () => { + cancelRuntimeFileList( + { + settings: {}, + worktreeId: 'wt-1', + worktreePath: '/remote/repo', + connectionId: 'ssh-1' + }, + 'token-1' + ) + expect(fsCancelListFiles).toHaveBeenCalledWith({ requestToken: 'token-1' }) + + fsCancelListFiles.mockClear() + cancelRuntimeFileList( + { + settings: { activeRuntimeEnvironmentId: 'env-1' }, + worktreeId: 'wt-1', + worktreePath: '/remote/repo' + }, + 'token-2' + ) + expect(fsCancelListFiles).not.toHaveBeenCalled() + }) + it('routes markdown document listing and stat through the selected runtime', async () => { runtimeEnvironmentCall.mockResolvedValue({ id: 'rpc-1', diff --git a/src/renderer/src/runtime/runtime-file-client.ts b/src/renderer/src/runtime/runtime-file-client.ts index e9161f754..eddda11a6 100644 --- a/src/renderer/src/runtime/runtime-file-client.ts +++ b/src/renderer/src/runtime/runtime-file-client.ts @@ -654,14 +654,15 @@ export async function searchRuntimeFiles( export async function listRuntimeFiles( context: RuntimeFileOperationArgs, - args: { rootPath: string; excludePaths?: string[] } + args: { rootPath: string; excludePaths?: string[]; requestToken?: string } ): Promise { const target = getActiveRuntimeTarget(context.settings) if (target.kind !== 'environment' || !context.worktreeId) { return window.api.fs.listFiles({ rootPath: args.rootPath, connectionId: context.connectionId, - excludePaths: args.excludePaths + excludePaths: args.excludePaths, + requestToken: args.requestToken }) } return callRuntimeRpc( @@ -675,6 +676,24 @@ export async function listRuntimeFiles( ) } +/** + * Best-effort abort of an in-flight listRuntimeFiles call (#7721). Switching + * workspaces must stop the previous workspace's full-tree scan — over SSH an + * abandoned scan keeps loading the relay and starves fs.readDir/fs.stat. + */ +export function cancelRuntimeFileList( + context: RuntimeFileOperationArgs, + requestToken: string +): void { + const target = getActiveRuntimeTarget(context.settings) + if (target.kind !== 'environment' || !context.worktreeId) { + void window.api.fs.cancelListFiles({ requestToken }).catch(() => { + /* cancellation is advisory; the request path has its own timeouts */ + }) + } + // Environment runtimes bound files.listAll with their own RPC timeout. +} + export async function listRuntimeMarkdownDocuments( context: RuntimeFileOperationArgs, rootPath: string diff --git a/src/renderer/src/runtime/runtime-rpc-client.test.ts b/src/renderer/src/runtime/runtime-rpc-client.test.ts index 97280cb35..515f85735 100644 --- a/src/renderer/src/runtime/runtime-rpc-client.test.ts +++ b/src/renderer/src/runtime/runtime-rpc-client.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { callRuntimeRpc, assertRuntimeEnvironmentCapability, + clearRecentRuntimeCompatibilityFailure, clearRuntimeCompatibilityCacheForTests, getActiveRuntimeTarget, RuntimeRpcCallError, @@ -263,6 +264,175 @@ describe('runtime RPC client routing', () => { ]) }) + it('lets background compatibility checks reuse a recent foreground failure', async () => { + runtimeEnvironmentCall.mockResolvedValue({ + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'remote-runtime' } + }) + const target = { kind: 'environment', environmentId: 'env-offline' } as const + + await expect(callRuntimeRpc(target, 'git.status')).rejects.toThrow('offline') + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { + reuseRecentCompatibilityFailure: true + }) + ).rejects.toThrow('offline') + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual(['status.get']) + }) + + it('re-probes after a status success clears a recent compatibility failure', async () => { + let statusCalls = 0 + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + if (method === 'status.get') { + statusCalls += 1 + if (statusCalls === 1) { + return Promise.resolve({ + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + graphStatus: 'ready', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: method, + ok: true, + result: { ok: true }, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + const target = { kind: 'environment', environmentId: 'env-back-online' } as const + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + clearRecentRuntimeCompatibilityFailure('env-back-online') + await expect( + callRuntimeRpc(target, 'worktree.detectedList', undefined, { + reuseRecentCompatibilityFailure: true + }) + ).resolves.toEqual({ ok: true }) + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get', + 'status.get', + 'worktree.detectedList' + ]) + }) + + it('keeps a proven-compatible cache entry when clearing recent failures', async () => { + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + if (method === 'status.get') { + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + graphStatus: 'ready', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: method, + ok: true, + result: { ok: true }, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + const target = { kind: 'environment', environmentId: 'env-still-ok' } as const + + await expect(callRuntimeRpc(target, 'repo.list')).resolves.toEqual({ ok: true }) + clearRecentRuntimeCompatibilityFailure('env-still-ok') + await expect(callRuntimeRpc(target, 'git.status')).resolves.toEqual({ ok: true }) + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get', + 'repo.list', + 'git.status' + ]) + }) + + it('re-probes when a status success clears a still-pending compatibility probe', async () => { + // Reconnect race: the offline probe stays queued on the dropped connection + // (pending, not yet failed) while a fresh status publish reports the host + // reachable. The clear must drop that doomed pending probe so the next + // reuse-flagged call starts a fresh probe instead of coalescing onto it. + let rejectFirstStatus!: (error: Error) => void + let statusCalls = 0 + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + if (method === 'status.get') { + statusCalls += 1 + if (statusCalls === 1) { + return new Promise((_, reject) => { + rejectFirstStatus = reject + }) + } + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + graphStatus: 'ready', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: method, + ok: true, + result: { ok: true }, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + const target = { kind: 'environment', environmentId: 'env-reconnect' } as const + + const pendingResult = callRuntimeRpc(target, 'repo.list', undefined, { + reuseRecentCompatibilityFailure: true + }).then( + () => 'resolved', + (error) => `rejected:${error.message}` + ) + // Let the first status.get register its in-flight cache entry. + await Promise.resolve() + + clearRecentRuntimeCompatibilityFailure('env-reconnect') + + const secondCall = callRuntimeRpc(target, 'worktree.detectedList', undefined, { + reuseRecentCompatibilityFailure: true + }) + await Promise.resolve() + // The doomed pending probe rejects; it must not fail the fresh re-probe. + rejectFirstStatus(new Error('stale connection closed')) + + await expect(secondCall).resolves.toEqual({ ok: true }) + await expect(pendingResult).resolves.toBe('rejected:stale connection closed') + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get', + 'status.get', + 'worktree.detectedList' + ]) + }) + it('checks advertised runtime capabilities after protocol compatibility', async () => { runtimeEnvironmentCall.mockResolvedValue({ id: 'status', diff --git a/src/renderer/src/runtime/runtime-rpc-client.ts b/src/renderer/src/runtime/runtime-rpc-client.ts index b9b1cb330..4b47315db 100644 --- a/src/renderer/src/runtime/runtime-rpc-client.ts +++ b/src/renderer/src/runtime/runtime-rpc-client.ts @@ -13,7 +13,9 @@ const RECENT_RUNTIME_COMPATIBILITY_FAILURE_TTL_MS = 60_000 type RuntimeCompatibilityCacheEntry = { check: Promise failedAt: number | null - reuseFailure: boolean + // True only once status.get settled and proved compatible. Stays false while + // the probe is in flight, so a recovery clear can drop a doomed pending probe. + provenCompatible: boolean } const runtimeCompatibilityChecks = new Map() @@ -106,7 +108,7 @@ async function ensureRuntimeEnvironmentCompatible( const entry: RuntimeCompatibilityCacheEntry = { check: Promise.resolve(), failedAt: null, - reuseFailure: options.reuseRecentCompatibilityFailure === true + provenCompatible: false } const check = (async () => { const response = await window.api.runtimeEnvironments.call({ @@ -123,6 +125,9 @@ async function ensureRuntimeEnvironmentCompatible( rememberRuntimeEnvironmentCompatibility(environmentId, entry) try { await check + if (runtimeCompatibilityChecks.get(environmentId) === entry) { + entry.provenCompatible = true + } } catch (error) { if (runtimeCompatibilityChecks.get(environmentId) === entry) { // Why: startup asks each remote for repos, groups, then folders; an @@ -148,10 +153,7 @@ function getCachedRuntimeCompatibilityCheck( runtimeCompatibilityChecks.delete(environmentId) return null } - if ( - cached.failedAt !== null && - (!cached.reuseFailure || options.reuseRecentCompatibilityFailure !== true) - ) { + if (cached.failedAt !== null && options.reuseRecentCompatibilityFailure !== true) { return null } runtimeCompatibilityChecks.delete(environmentId) @@ -176,6 +178,22 @@ function rememberRuntimeEnvironmentCompatibility( } } +// Why: a live status.get answer proves any cached compatibility verdict that is +// not a settled success is stale. Drop settled failures AND still-pending probes +// (a probe queued on the dropped connection is doomed, and a reachability- +// triggered refresh must not coalesce onto it) so the refresh re-probes. Only +// proven-compatible successes stay cached. +export function clearRecentRuntimeCompatibilityFailure(environmentId: string): void { + const trimmed = environmentId.trim() + if (!trimmed) { + return + } + const cached = runtimeCompatibilityChecks.get(trimmed) + if (cached && !cached.provenCompatible) { + runtimeCompatibilityChecks.delete(trimmed) + } +} + export function clearRuntimeCompatibilityCache(environmentId?: string | null): void { const trimmed = environmentId?.trim() if (trimmed) { @@ -193,7 +211,7 @@ export function markRuntimeEnvironmentCompatible(environmentId: string): void { rememberRuntimeEnvironmentCompatibility(trimmed, { check: Promise.resolve(), failedAt: null, - reuseFailure: false + provenCompatible: true }) } diff --git a/src/renderer/src/runtime/web-session-tabs-sync.test.ts b/src/renderer/src/runtime/web-session-tabs-sync.test.ts index be97ef98b..7090ac68b 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.test.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.test.ts @@ -22,6 +22,7 @@ import type { BrowserPage, BrowserWorkspace, Tab, TerminalTab } from '../../../s import type { OpenFile } from '../store/slices/editor' import { _getWebSessionTabsTrackingCountsForTest, + acceptReplayedWebSessionTabsSnapshot, applyFreshWebSessionTabsSnapshot, applyWebSessionTabsSnapshot, applyWebSessionTabsSnapshots, @@ -145,6 +146,46 @@ describe('applyWebSessionTabsSnapshot', () => { expect(shouldApplyWebSessionTabsSnapshot(sameEpochOlder, ENV)).toBe(false) }) + it('accepts a replayed same-epoch same-version snapshot after a transport reconnect', () => { + // Why: after a shared-control reconnect the server re-emits the current + // snapshot with an UNCHANGED epoch/version (the host did not restart). + // Without the replay reset the monotonic gate rejects it and the mirror + // stays frozen (#7718). + const snapshot = makeSnapshot([], { snapshotVersion: 5, activeTabType: null }) + + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + // Same frame again during normal operation: still rejected as stale. + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(false) + + acceptReplayedWebSessionTabsSnapshot(ENV, snapshot.worktree) + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + + // The replay reset re-primes tracking: ordering protection resumes for + // subsequent frames (an older same-epoch frame is still rejected). + const older = makeSnapshot([], { snapshotVersion: 4, activeTabType: null }) + expect(shouldApplyWebSessionTabsSnapshot(older, ENV)).toBe(false) + const newer = makeSnapshot([], { snapshotVersion: 6, activeTabType: null }) + expect(shouldApplyWebSessionTabsSnapshot(newer, ENV)).toBe(true) + }) + + it('scopes the replay reset to the replayed environment and worktree', () => { + const snapshot = makeSnapshot([], { snapshotVersion: 5, activeTabType: null }) + const otherWorktree = makeSnapshot([], { + worktree: 'repo::/other-worktree', + snapshotVersion: 5, + activeTabType: null + }) + + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + expect(shouldApplyWebSessionTabsSnapshot(otherWorktree, ENV)).toBe(true) + + acceptReplayedWebSessionTabsSnapshot(ENV, snapshot.worktree) + + // Only the replayed worktree re-applies; the other stays gated. + expect(shouldApplyWebSessionTabsSnapshot(otherWorktree, ENV)).toBe(false) + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + }) + it('ignores remote snapshots for the local floating workspace', () => { const floatingTab: TerminalTab = { id: 'floating-tab-1', diff --git a/src/renderer/src/runtime/web-session-tabs-sync.ts b/src/renderer/src/runtime/web-session-tabs-sync.ts index 8d0eba136..47942c674 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.ts @@ -66,6 +66,7 @@ import { endWebRuntimeWakeTerminalRespawn, shouldSkipWebRuntimeWakeTerminalRespawn } from './web-runtime-wake-terminal-respawn' +import { isRuntimeSubscriptionReplayResponse } from '../../../shared/runtime-subscription-replay' const WEB_SESSION_GROUP_PREFIX = 'web-session-tabs:' @@ -172,6 +173,18 @@ export function getLastKnownHostTerminalTabCount( ) } +// Why: a post-reconnect subscription replay re-emits the current snapshot with +// an unchanged epoch/version; dropping the freshness entry lets the monotonic +// gate accept that replay as authoritative instead of freezing the mirror +// (#7718). Normal-operation ordering protection is untouched — this only runs +// for responses the connection tagged as reconnect replays. +export function acceptReplayedWebSessionTabsSnapshot( + environmentId: string, + worktreeId: string +): void { + latestSessionTabsSnapshotByWorktree.delete(sessionTabsFreshnessKey(environmentId, worktreeId)) +} + export function shouldApplyWebSessionTabsSnapshot( snapshot: RuntimeMobileSessionTabsResult, environmentId: string @@ -2500,7 +2513,13 @@ export function useWebSessionTabsSync(): void { return } const event = response.result as SessionTabsStreamEvent + const replayed = isRuntimeSubscriptionReplayResponse(response) if (event.type === 'snapshots') { + if (replayed) { + for (const snapshot of event.snapshots) { + acceptReplayedWebSessionTabsSnapshot(environmentId, snapshot.worktree) + } + } useAppStore.setState((state) => applyFreshWebSessionTabsSnapshots(state, event.snapshots, environmentId) ) @@ -2509,6 +2528,9 @@ export function useWebSessionTabsSync(): void { if (event.type !== 'snapshot' && event.type !== 'updated') { return } + if (replayed) { + acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) + } useAppStore.setState((state) => applyFreshWebSessionTabsSnapshot(state, event, environmentId) ) @@ -2587,6 +2609,9 @@ export function useWebSessionTabsSync(): void { if (event.type !== 'snapshot' && event.type !== 'updated') { return } + if (isRuntimeSubscriptionReplayResponse(response)) { + acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) + } const fresh = shouldApplyWebSessionTabsSnapshot(event, environmentId) const syncState = useAppStore.getState() const localWorktreeTabs = syncState.tabsByWorktree[activeWorktreeId] ?? [] diff --git a/src/renderer/src/store/index.ts b/src/renderer/src/store/index.ts index e75bbffa5..19941c75c 100644 --- a/src/renderer/src/store/index.ts +++ b/src/renderer/src/store/index.ts @@ -23,6 +23,7 @@ import { createOpenCodeUsageSlice } from './slices/opencode-usage' import { createBrowserSlice } from './slices/browser' import { createRateLimitSlice } from './slices/rate-limits' import { createSshSlice } from './slices/ssh' +import { createRuntimeEnvironmentSshSlice } from './slices/runtime-environment-ssh' import { createAgentStatusSlice } from './slices/agent-status' import { createPaneForegroundAgentSlice } from './slices/pane-foreground-agent' import { createDiffCommentsSlice } from './slices/diffComments' @@ -61,6 +62,7 @@ export const useAppStore = create()((...a) => ({ ...createBrowserSlice(...a), ...createRateLimitSlice(...a), ...createSshSlice(...a), + ...createRuntimeEnvironmentSshSlice(...a), ...createAgentStatusSlice(...a), ...createPaneForegroundAgentSlice(...a), ...createDiffCommentsSlice(...a), diff --git a/src/renderer/src/store/slices/diffComments.test.ts b/src/renderer/src/store/slices/diffComments.test.ts index e4862f129..f1538a53f 100644 --- a/src/renderer/src/store/slices/diffComments.test.ts +++ b/src/renderer/src/store/slices/diffComments.test.ts @@ -128,6 +128,7 @@ import { createOpenCodeUsageSlice } from './opencode-usage' import { createBrowserSlice } from './browser' import { createRateLimitSlice } from './rate-limits' import { createSshSlice } from './ssh' +import { createRuntimeEnvironmentSshSlice } from './runtime-environment-ssh' import { createAgentStatusSlice } from './agent-status' import { createPaneForegroundAgentSlice } from './pane-foreground-agent' import { createDiffCommentsSlice } from './diffComments' @@ -165,6 +166,7 @@ function createTestStore() { ...createBrowserSlice(...a), ...createRateLimitSlice(...a), ...createSshSlice(...a), + ...createRuntimeEnvironmentSshSlice(...a), ...createAgentStatusSlice(...a), ...createPaneForegroundAgentSlice(...a), ...createDiffCommentsSlice(...a), diff --git a/src/renderer/src/store/slices/editor.ts b/src/renderer/src/store/slices/editor.ts index 5b451cbbc..4fdd5fb76 100644 --- a/src/renderer/src/store/slices/editor.ts +++ b/src/renderer/src/store/slices/editor.ts @@ -251,8 +251,21 @@ export type OpenFile = { // disk while it's open, we keep the tab around so the user can still see // (and potentially save) their in-memory content. The tab surfaces this as // a strikethrough label plus a "deleted"/"renamed" suffix. Cleared if the - // file reappears on disk at its original path. - externalMutation?: 'deleted' | 'renamed' + // file reappears on disk at its original path. 'changed' means the file was + // rewritten on disk while this tab held unsaved edits (issue #7265): the + // buffer is preserved and the editor shows a changed-on-disk banner instead + // of tab strikethrough. + externalMutation?: 'deleted' | 'renamed' | 'changed' + /** Why: signature of the disk content this tab's edits are based on (last + * load or save). Persisted with dirty drafts so a restore can re-derive a + * changed-on-disk conflict from ground truth — an agent write that landed + * while the app was closed must not be clobbered by a resumed autosave. */ + lastKnownDiskSignature?: string + /** Why: set at hydration for restored dirty tabs; suspends autosave until + * the restored-tab conflict scan has compared disk against the baseline. + * Without this hard gate the scan's async read merely races the autosave + * timer, and a slow (SSH/runtime) read loses the race. Not persisted. */ + pendingDiskBaselineVerification?: boolean /** Why: diff bodies are cached in EditorPanel. Re-selecting an existing diff * tab from the tree bumps this so the panel refetches instead of reusing a * stale snapshot. */ @@ -497,7 +510,9 @@ export type EditorSlice = { setActiveFile: (fileId: string) => void reorderFiles: (fileIds: string[]) => void markFileDirty: (fileId: string, dirty: boolean) => void - setExternalMutation: (fileId: string, mutation: 'deleted' | 'renamed' | null) => void + setExternalMutation: (fileId: string, mutation: 'deleted' | 'renamed' | 'changed' | null) => void + setLastKnownDiskSignature: (fileId: string, signature: string) => void + clearPendingDiskBaselineVerification: (fileId: string) => void clearUntitled: (fileId: string) => void openDiff: ( worktreeId: string, @@ -2469,6 +2484,32 @@ export const createEditorSlice: StateCreator = (s } }), + setLastKnownDiskSignature: (fileId, signature) => + set((s) => { + const file = s.openFiles.find((f) => f.id === fileId) + if (!file || file.lastKnownDiskSignature === signature) { + return s + } + return { + openFiles: s.openFiles.map((f) => + f.id === fileId ? { ...f, lastKnownDiskSignature: signature } : f + ) + } + }), + + clearPendingDiskBaselineVerification: (fileId) => + set((s) => { + const file = s.openFiles.find((f) => f.id === fileId) + if (!file?.pendingDiskBaselineVerification) { + return s + } + return { + openFiles: s.openFiles.map((f) => + f.id === fileId ? { ...f, pendingDiskBaselineVerification: undefined } : f + ) + } + }), + clearUntitled: (fileId) => set((s) => ({ openFiles: s.openFiles.map((f) => (f.id === fileId ? { ...f, isUntitled: undefined } : f)) @@ -4300,6 +4341,15 @@ export const createEditorSlice: StateCreator = (s isDirty: pf.dirtyDraftContent !== undefined, isPreview: pf.isPreview, runtimeEnvironmentId: pf.runtimeEnvironmentId, + lastKnownDiskSignature: pf.lastKnownDiskSignature, + // Why: hard-suspends autosave until the restored-tab conflict scan + // verifies disk against the baseline — an async race would let a + // slow remote read lose to the autosave timer and clobber an + // offline agent write. + pendingDiskBaselineVerification: + pf.dirtyDraftContent !== undefined && pf.lastKnownDiskSignature !== undefined + ? true + : undefined, mode: 'edit' }) } diff --git a/src/renderer/src/store/slices/repos-host-identity-routing.test.ts b/src/renderer/src/store/slices/repos-host-identity-routing.test.ts index 22690115f..ebdc85fd4 100644 --- a/src/renderer/src/store/slices/repos-host-identity-routing.test.ts +++ b/src/renderer/src/store/slices/repos-host-identity-routing.test.ts @@ -26,6 +26,7 @@ const remoteDuplicate: Repo = { } const reposRemove = vi.fn() +const reposRemoveForHost = vi.fn() const reposUpdate = vi.fn() const reposReorder = vi.fn() const ptyKill = vi.fn() @@ -59,6 +60,7 @@ function projectHostSetup(overrides: Pick): P beforeEach(() => { clearRuntimeCompatibilityCacheForTests() reposRemove.mockReset() + reposRemoveForHost.mockReset() reposUpdate.mockReset() reposReorder.mockReset() ptyKill.mockReset() @@ -71,6 +73,7 @@ beforeEach(() => { api: { repos: { remove: reposRemove, + removeForHost: reposRemoveForHost, update: reposUpdate, reorder: reposReorder }, @@ -260,11 +263,88 @@ describe('repo slice host identity routing', () => { expect(store.getState().projects).toEqual([ expect.objectContaining({ id: 'repo:same-repo', sourceRepoIds: ['same-repo'] }) ]) - expect(reposRemove).toHaveBeenCalledWith({ repoId: 'same-repo' }) + // Why: the id also exists on runtime:env-1, so the local-side removal must be + // host-scoped in main to avoid deleting the other host's persisted repo row. + expect(reposRemoveForHost).toHaveBeenCalledWith({ repoId: 'same-repo', hostId: 'local' }) + expect(reposRemove).not.toHaveBeenCalled() expect(ptyKill).toHaveBeenCalledWith('local-pty') expect(ptyKill).not.toHaveBeenCalledWith('remote-pty') }) + it('removeProject with an explicit hostId routes to that host, not the focused one', async () => { + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-explicit-host', + ok: true, + result: { status: 'removed' }, + _meta: { runtimeId: 'runtime-remote' } + }) + const localWorktree = makeWorktree({ id: 'same-repo::/local/wt', repoId: 'same-repo' }) + const remoteWorktree = makeWorktree({ + id: 'same-repo::/remote/wt', + repoId: 'same-repo', + hostId: 'runtime:env-1' + }) + const store = createTestStore() + // Focus is local (no active runtime env). Without deriving the target from the + // explicit hostId, this would route to the focused (local) host and delete the + // wrong row. It must target runtime:env-1 via that host's RPC. + store.setState({ + repos: [localDuplicate, remoteDuplicate], + worktreesByRepo: { 'same-repo': [localWorktree, remoteWorktree] } + }) + + await store.getState().removeProject('same-repo', { hostId: 'runtime:env-1' }) + + // Routes to the runtime host's repo.rm (not the local removeForHost/remove), + // and the local row is left intact. + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'repo.rm', + params: { repo: 'same-repo' }, + timeoutMs: 15_000 + }) + expect(reposRemoveForHost).not.toHaveBeenCalled() + expect(reposRemove).not.toHaveBeenCalled() + expect(store.getState().repos).toEqual([localDuplicate]) + expect(store.getState().worktreesByRepo['same-repo']).toEqual([localWorktree]) + }) + + it('removeProject of an SSH host row routes local even when a runtime is focused', async () => { + // Regression: removing an SSH host's repo (explicit ssh hostId) must NOT route + // repo.rm to the focused runtime env. settingsForRepoOwner clears the focused + // runtime for SSH owners, so removal stays on the host-scoped local path. + const sshDuplicate: Repo = { + id: 'same-repo', + path: '/home/orca/project', + displayName: 'SSH', + badgeColor: '#222', + addedAt: 3, + connectionId: 'ssh-1', + executionHostId: 'ssh:ssh-1' + } + const sshWorktree = makeWorktree({ + id: 'same-repo::/home/orca/wt', + repoId: 'same-repo', + hostId: 'ssh:ssh-1' + }) + const store = createTestStore() + // A runtime env is focused, but the row being removed is SSH-owned. + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + repos: [localDuplicate, sshDuplicate], + worktreesByRepo: { 'same-repo': [sshWorktree] } + }) + + await store.getState().removeProject('same-repo', { hostId: 'ssh:ssh-1' }) + + // Host-scoped local removal (id also exists on local), never the runtime RPC. + expect(reposRemoveForHost).toHaveBeenCalledWith({ repoId: 'same-repo', hostId: 'ssh:ssh-1' }) + expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith( + expect.objectContaining({ method: 'repo.rm' }) + ) + expect(store.getState().repos).toEqual([localDuplicate]) + }) + it('removes a runtime duplicate without purging legacy local worktrees', async () => { runtimeEnvironmentCall.mockResolvedValue({ id: 'rpc-duplicate-remove', diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index da0cb011d..55429bb6e 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -48,6 +48,7 @@ import { isPathInsideOrEqual } from '../../../../shared/cross-platform-path' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree-id' import { selectProjectGroupRemovalTargets } from './project-group-removal-targets' import { reconcileFetchedRepos } from './repo-identity-reconcile' +import { pruneSupersededSshRepoRows } from './superseded-ssh-repo-rows' import { splitRepoReorderByHost } from './repo-reorder-host-split' import { omitSparsePresetsForRepos } from './sparse-presets' import { @@ -74,7 +75,8 @@ import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, toRuntimeExecutionHostId, - toSshExecutionHostId + toSshExecutionHostId, + type ExecutionHostId } from '../../../../shared/execution-host' import { cleanupEphemeralVmRuntimesForDeleted } from '@/lib/ephemeral-vm-runtime-cleanup' import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope' @@ -1038,8 +1040,12 @@ async function listRuntimeEnvironmentsForAllHostLoad(): Promise<{ id: string }[] } } -function settingsForRepoOwner(state: Pick, repoId: string) { - const repo = findRepoForHost(state.repos, repoId, { settings: state.settings }) +function settingsForRepoOwner( + state: Pick, + repoId: string, + hostId?: ExecutionHostId +) { + const repo = findRepoForHost(state.repos, repoId, { settings: state.settings, hostId }) if (!repo) { return state.settings } @@ -1371,7 +1377,9 @@ export type RepoSlice = { groupId: string | null, order?: number ) => Promise - removeProject: (projectId: string) => Promise + // options.hostId disambiguates which host's row to remove when the same repo + // id exists on multiple hosts; without it the focused host is assumed. + removeProject: (projectId: string, options?: { hostId?: ExecutionHostId }) => Promise updateProject: (projectId: string, updates: ProjectUpdate) => Promise updateRepo: (projectId: string, updates: RepoUpdate) => Promise setActiveRepo: (projectId: string | null) => void @@ -1408,18 +1416,26 @@ export const createRepoSlice: StateCreator = (set, return } set((s) => { - const validRepoIds = new Set(reconciledRepos.map((repo) => repo.id)) + // Why: after re-adoption re-points a repo onto a re-added SSH target, the + // per-host merge leaves the stale row on the old (removed) target id — a + // ghost a terminal pane can bind to and fail with "SSH target not found". + // Drop rows on unknown SSH targets that a live-host sibling supersedes. + const prunedRepos = pruneSupersededSshRepoRows( + reconciledRepos, + new Set(s.sshTargetLabels.keys()) + ) + const validRepoIds = new Set(prunedRepos.map((repo) => repo.id)) const mergedProjectCompatibility = mergeFetchedProjectCompatibilityForHost({ previous: { projects: s.projects, projectHostSetups: s.projectHostSetups }, fetched: projectCompatibility, - repos: reconciledRepos, + repos: prunedRepos, hostId }) return { - repos: reconciledRepos, + repos: prunedRepos, ...mergedProjectCompatibility, folderWorkspacePathStatuses: {}, activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, @@ -2539,9 +2555,15 @@ export const createRepoSlice: StateCreator = (set, } }, - removeProject: async (projectId) => { + removeProject: async (projectId, options) => { try { - const ownerRepo = findRepoForHost(get().repos, projectId, { settings: get().settings }) + // Why: pass an explicit hostId (e.g. when removing an SSH host's root repo) + // so a duplicate id across hosts resolves to the intended row instead of + // falling back to the focused host. + const ownerRepo = findRepoForHost(get().repos, projectId, { + settings: get().settings, + hostId: options?.hostId + }) if (!ownerRepo) { return } @@ -2556,9 +2578,23 @@ export const createRepoSlice: StateCreator = (set, runtimeOwnedSshTargetIds: [ownerRepo.connectionId as string] }) } - const target = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId)) + // Why: derive the runtime target from the owner's own settings, passing the + // explicit options.hostId so a duplicate repo id across hosts resolves to the + // intended row. settingsForRepoOwner clears the focused runtime for SSH/local + // owners (routing local) and pins runtime owners to their environment, so an + // SSH host removal never routes repo.rm to the focused runtime. + const target = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId, options?.hostId)) + // Why: the same repo id can exist on multiple hosts (local + an SSH target, + // or a re-added SSH target). Main's repos:remove is repo-id-only and would + // delete every host's row. Scope the local-side removal to the owning host + // so a cross-host duplicate id keeps its other rows. + const idExistsOnOtherHost = get().repos.some( + (repo) => repo.id === projectId && getRepoExecutionHostId(repo) !== ownerHostId + ) await (target.kind === 'local' - ? window.api.repos.remove({ repoId: projectId }) + ? idExistsOnOtherHost + ? window.api.repos.removeForHost({ repoId: projectId, hostId: ownerHostId }) + : window.api.repos.remove({ repoId: projectId }) : callRuntimeRpc(target, 'repo.rm', { repo: projectId }, { timeoutMs: 15_000 })) get().clearOrcaHookTrustForRepo(projectId) diff --git a/src/renderer/src/store/slices/runtime-environment-ssh.test.ts b/src/renderer/src/store/slices/runtime-environment-ssh.test.ts new file mode 100644 index 000000000..22b501588 --- /dev/null +++ b/src/renderer/src/store/slices/runtime-environment-ssh.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, it } from 'vitest' +import type { SshConnectionState } from '../../../../shared/ssh-types' +import type { RuntimeStatus } from '../../../../shared/runtime-types' +import { createTestStore } from './store-test-helpers' +import { + selectRuntimeAwareSshStatus, + selectRuntimeAwareSshTargetLabel, + selectRuntimeAwareSshTargetRemoved +} from './runtime-environment-ssh' + +const ENV_A = 'env-a' +const ENV_B = 'env-b' + +function connState( + targetId: string, + status: SshConnectionState['status'] = 'connected' +): SshConnectionState { + return { targetId, status, error: null, reconnectAttempt: 0 } +} + +function markReachable(store: ReturnType, environmentId: string): void { + store.getState().setRuntimeEnvironmentStatus(environmentId, { + status: { runtimeId: environmentId } as RuntimeStatus, + checkedAt: Date.now() + }) +} + +describe('runtime-environment-ssh slice', () => { + it('routes state into the owning environment bucket without touching local maps or other buckets', () => { + const store = createTestStore() + store.getState().setEnvironmentSshTargetsMetadata(ENV_B, [{ id: 'ssh-b', label: 'b-box' }]) + const localStatesBefore = store.getState().sshConnectionStates + const localLabelsBefore = store.getState().sshTargetLabels + const bucketBBefore = store.getState().sshStateByEnvironment.get(ENV_B) + + store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a')) + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }]) + store.getState().setEnvironmentRemovedSshTargetLabels(ENV_A, { 'ssh-dead': 'old box' }) + + const state = store.getState() + // Local maps: bit-identical (same references, still empty). + expect(state.sshConnectionStates).toBe(localStatesBefore) + expect(state.sshTargetLabels).toBe(localLabelsBefore) + expect(state.sshConnectionStates.size).toBe(0) + expect(state.sshTargetsHydrated).toBe(false) + // Environment B's bucket: untouched reference. + expect(state.sshStateByEnvironment.get(ENV_B)).toBe(bucketBBefore) + // Environment A's bucket: populated. + const bucketA = state.sshStateByEnvironment.get(ENV_A) + expect(bucketA?.connectionStates.get('ssh-a')?.status).toBe('connected') + expect(bucketA?.targetLabels.get('ssh-a')).toBe('a-box') + expect(bucketA?.removedTargetLabels.get('ssh-dead')).toBe('old box') + expect(bucketA?.targetsHydrated).toBe(true) + }) + + it('local slice writes never leak into environment buckets', () => { + const store = createTestStore() + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }]) + const bucketBefore = store.getState().sshStateByEnvironment.get(ENV_A) + + store.getState().setSshConnectionState('ssh-a', connState('ssh-a', 'disconnected')) + store.getState().setSshTargetsMetadata([{ id: 'ssh-a', label: 'local a' } as never]) + + expect(store.getState().sshStateByEnvironment.get(ENV_A)).toBe(bucketBefore) + expect(store.getState().sshStateByEnvironment.get(ENV_A)?.connectionStates.size).toBe(0) + }) + + it('keeps references stable when applying an identical state or target list', () => { + const store = createTestStore() + store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a')) + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }]) + const mapBefore = store.getState().sshStateByEnvironment + const bucketBefore = mapBefore.get(ENV_A) + + store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a')) + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }]) + store.getState().setEnvironmentRemovedSshTargetLabels(ENV_A, {}) + + expect(store.getState().sshStateByEnvironment).toBe(mapBefore) + expect(store.getState().sshStateByEnvironment.get(ENV_A)).toBe(bucketBefore) + }) + + it('flips the hydrated flag on the first fetch of an empty target list', () => { + const store = createTestStore() + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, []) + expect(store.getState().sshStateByEnvironment.get(ENV_A)?.targetsHydrated).toBe(true) + }) + + it('drops only the detached environment bucket on retain', () => { + const store = createTestStore() + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }]) + store.getState().setEnvironmentSshTargetsMetadata(ENV_B, [{ id: 'ssh-b', label: 'b-box' }]) + store.getState().setSshTargetsMetadata([{ id: 'ssh-local', label: 'local' } as never]) + const bucketB = store.getState().sshStateByEnvironment.get(ENV_B) + const localLabels = store.getState().sshTargetLabels + + store.getState().retainEnvironmentSshState([ENV_B]) + + expect(store.getState().sshStateByEnvironment.has(ENV_A)).toBe(false) + expect(store.getState().sshStateByEnvironment.get(ENV_B)).toBe(bucketB) + expect(store.getState().sshTargetLabels).toBe(localLabels) + }) + + it('detaching an environment through setRuntimeEnvironments drops its bucket', () => { + const store = createTestStore() + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }]) + store.getState().setEnvironmentSshTargetsMetadata(ENV_B, [{ id: 'ssh-b', label: 'b-box' }]) + + store.getState().setRuntimeEnvironments([{ id: ENV_B, name: 'B', createdAt: 0 } as never]) + + expect(store.getState().sshStateByEnvironment.has(ENV_A)).toBe(false) + expect(store.getState().sshStateByEnvironment.has(ENV_B)).toBe(true) + }) + + it('markEnvironmentSshStateStale downgrades to unknown but keeps labels for display', () => { + const store = createTestStore() + markReachable(store, ENV_A) + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }]) + store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a')) + expect(selectRuntimeAwareSshStatus(store.getState(), ENV_A, 'ssh-a')).toBe('connected') + + store.getState().markEnvironmentSshStateStale(ENV_A) + + const bucket = store.getState().sshStateByEnvironment.get(ENV_A) + expect(bucket?.targetsHydrated).toBe(false) + expect(bucket?.connectionStates.size).toBe(0) + expect(bucket?.targetLabels.get('ssh-a')).toBe('a-box') + // Un-hydrated bucket reads as unknown — no overlay, no removal evidence. + expect(selectRuntimeAwareSshStatus(store.getState(), ENV_A, 'ssh-a')).toBeNull() + expect(selectRuntimeAwareSshTargetRemoved(store.getState(), ENV_A, 'ssh-a')).toBe(false) + }) + + describe('selectors', () => { + it('resolve the local maps when the owning environment is null', () => { + const store = createTestStore() + store.getState().setSshConnectionState('ssh-local', connState('ssh-local', 'disconnected')) + store.getState().setSshTargetsMetadata([{ id: 'ssh-local', label: 'local box' } as never]) + // A same-id target in a bucket must not shadow the local resolution. + markReachable(store, ENV_A) + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, []) + + const state = store.getState() + expect(selectRuntimeAwareSshStatus(state, null, 'ssh-local')).toBe('disconnected') + expect(selectRuntimeAwareSshTargetLabel(state, null, 'ssh-local')).toBe('local box') + expect(selectRuntimeAwareSshTargetRemoved(state, null, 'ssh-local')).toBe(false) + expect(selectRuntimeAwareSshTargetRemoved(state, null, 'ssh-gone')).toBe(true) + }) + + it('resolve the owning environment bucket, not local state, for a remote-owned target', () => { + const store = createTestStore() + markReachable(store, ENV_A) + // Same target id exists locally as connected — must not leak into the + // environment read. + store.getState().setSshConnectionState('ssh-1', connState('ssh-1', 'connected')) + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-1', label: 'devbox' }]) + store + .getState() + .setEnvironmentSshConnectionState(ENV_A, 'ssh-1', connState('ssh-1', 'disconnected')) + + const state = store.getState() + expect(selectRuntimeAwareSshStatus(state, ENV_A, 'ssh-1')).toBe('disconnected') + expect(selectRuntimeAwareSshTargetLabel(state, ENV_A, 'ssh-1')).toBe('devbox') + expect(selectRuntimeAwareSshTargetRemoved(state, ENV_A, 'ssh-1')).toBe(false) + }) + + it('return unknown (null status) for an unreachable environment even with a hydrated bucket', () => { + const store = createTestStore() + markReachable(store, ENV_A) + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-1', label: 'devbox' }]) + store + .getState() + .setEnvironmentSshConnectionState(ENV_A, 'ssh-1', connState('ssh-1', 'disconnected')) + // Environment probe now records unreachable. + store.getState().setRuntimeEnvironmentStatus(ENV_A, { status: null, checkedAt: Date.now() }) + + const state = store.getState() + expect(selectRuntimeAwareSshStatus(state, ENV_A, 'ssh-1')).toBeNull() + expect(selectRuntimeAwareSshTargetRemoved(state, ENV_A, 'ssh-1')).toBe(false) + }) + + it('never report removal from an un-hydrated bucket, and report it from a hydrated one', () => { + const store = createTestStore() + markReachable(store, ENV_A) + const before = store.getState() + expect(selectRuntimeAwareSshTargetRemoved(before, ENV_A, 'ssh-ghost')).toBe(false) + expect(selectRuntimeAwareSshStatus(before, ENV_A, 'ssh-ghost')).toBeNull() + + store.getState().setEnvironmentSshTargetsMetadata(ENV_A, []) + const after = store.getState() + expect(selectRuntimeAwareSshTargetRemoved(after, ENV_A, 'ssh-ghost')).toBe(true) + // Removal tombstones win the label fallback for ghost hosts. + store.getState().setEnvironmentRemovedSshTargetLabels(ENV_A, { 'ssh-ghost': 'old devbox' }) + expect(selectRuntimeAwareSshTargetLabel(store.getState(), ENV_A, 'ssh-ghost')).toBe( + 'old devbox' + ) + }) + }) +}) diff --git a/src/renderer/src/store/slices/runtime-environment-ssh.ts b/src/renderer/src/store/slices/runtime-environment-ssh.ts new file mode 100644 index 000000000..16ea3929d --- /dev/null +++ b/src/renderer/src/store/slices/runtime-environment-ssh.ts @@ -0,0 +1,263 @@ +import type { StateCreator } from 'zustand' +import type { AppState } from '../types' +import type { + SshConnectionState, + SshConnectionStatus, + SshTarget +} from '../../../../shared/ssh-types' +import { sshConnectionStatesEqual, sshTargetLabelsEqual } from './ssh-target-cleanup' + +/** + * SSH state of one remote Orca server's own SSH targets, mirrored on this + * client. Kept strictly separate from the local `SshSlice` maps so a remote + * machine's targets can never pollute local SSH settings, pickers, or the + * execution-host registry — and vice versa (STA-1468, desktop topology). + */ +export type RuntimeEnvironmentSshBucket = { + connectionStates: Map + targetLabels: Map + removedTargetLabels: Map + /** Mirrors the local `sshTargetsHydrated` positive-evidence rule: absence + * from `targetLabels` only counts as target removal once a target list + * actually loaded from that environment (even an empty one). */ + targetsHydrated: boolean +} + +export type RuntimeEnvironmentSshSlice = { + /** + * Per-runtime-environment SSH state buckets, keyed by environment id. + * Do NOT read this map directly from components — use the + * `selectRuntimeAwareSsh*` selectors below, which route between the local + * SSH maps (`environmentId === null`) and the owning environment's bucket. + */ + sshStateByEnvironment: Map + setEnvironmentSshConnectionState: ( + environmentId: string, + targetId: string, + state: SshConnectionState + ) => void + setEnvironmentSshTargetsMetadata: ( + environmentId: string, + targets: Pick[] + ) => void + setEnvironmentRemovedSshTargetLabels: ( + environmentId: string, + labels: Record + ) => void + /** Transport to the environment dropped: its mirrored SSH state can no + * longer be trusted (it may hold a pre-drop "connected"). Downgrades the + * bucket to unhydrated and clears connection states so reads resolve to + * "unknown" until a reconnect re-hydrates. */ + markEnvironmentSshStateStale: (environmentId: string) => void + removeEnvironmentSshState: (environmentId: string) => void + /** Drops buckets for environments no longer in the saved set. */ + retainEnvironmentSshState: (environmentIds: Iterable) => void +} + +const EMPTY_BUCKET: RuntimeEnvironmentSshBucket = { + connectionStates: new Map(), + targetLabels: new Map(), + removedTargetLabels: new Map(), + targetsHydrated: false +} + +function getBucket( + buckets: Map, + environmentId: string +): RuntimeEnvironmentSshBucket { + return buckets.get(environmentId) ?? EMPTY_BUCKET +} + +function withBucket( + s: Pick, + environmentId: string, + bucket: RuntimeEnvironmentSshBucket +): Pick { + const next = new Map(s.sshStateByEnvironment) + next.set(environmentId, bucket) + return { sshStateByEnvironment: next } +} + +function removedLabelsEqual(current: Map, labels: Record): boolean { + const entries = Object.entries(labels) + return ( + entries.length === current.size && entries.every(([id, label]) => current.get(id) === label) + ) +} + +export const createRuntimeEnvironmentSshSlice: StateCreator< + AppState, + [], + [], + RuntimeEnvironmentSshSlice +> = (set) => ({ + sshStateByEnvironment: new Map(), + + setEnvironmentSshConnectionState: (environmentId, targetId, state) => + set((s) => { + const bucket = getBucket(s.sshStateByEnvironment, environmentId) + if (sshConnectionStatesEqual(bucket.connectionStates.get(targetId), state)) { + return s + } + const connectionStates = new Map(bucket.connectionStates) + connectionStates.set(targetId, state) + return withBucket(s, environmentId, { ...bucket, connectionStates }) + }), + + setEnvironmentSshTargetsMetadata: (environmentId, targets) => + set((s) => { + const bucket = getBucket(s.sshStateByEnvironment, environmentId) + if (sshTargetLabelsEqual(bucket.targetLabels, targets)) { + // Why: an unchanged (even empty) list is still a successful load — the + // hydration flag must flip on the first fetch of an empty target set. + return bucket.targetsHydrated + ? s + : withBucket(s, environmentId, { ...bucket, targetsHydrated: true }) + } + return withBucket(s, environmentId, { + ...bucket, + targetLabels: new Map(targets.map((target) => [target.id, target.label])), + targetsHydrated: true + }) + }), + + setEnvironmentRemovedSshTargetLabels: (environmentId, labels) => + set((s) => { + const bucket = getBucket(s.sshStateByEnvironment, environmentId) + if (removedLabelsEqual(bucket.removedTargetLabels, labels)) { + return s + } + return withBucket(s, environmentId, { + ...bucket, + removedTargetLabels: new Map(Object.entries(labels)) + }) + }), + + markEnvironmentSshStateStale: (environmentId) => + set((s) => { + const bucket = s.sshStateByEnvironment.get(environmentId) + if (!bucket || (!bucket.targetsHydrated && bucket.connectionStates.size === 0)) { + return s + } + // Labels are kept so a re-hydrating overlay can still show a friendly + // host name; hydration=false alone forces reads back to "unknown". + return withBucket(s, environmentId, { + ...bucket, + connectionStates: new Map(), + targetsHydrated: false + }) + }), + + removeEnvironmentSshState: (environmentId) => + set((s) => { + if (!s.sshStateByEnvironment.has(environmentId)) { + return s + } + const next = new Map(s.sshStateByEnvironment) + next.delete(environmentId) + return { sshStateByEnvironment: next } + }), + + retainEnvironmentSshState: (environmentIds) => + set((s) => { + const keep = new Set(environmentIds) + let changed = false + const next = new Map(s.sshStateByEnvironment) + for (const id of next.keys()) { + if (!keep.has(id)) { + next.delete(id) + changed = true + } + } + return changed ? { sshStateByEnvironment: next } : s + }) +}) + +type RuntimeAwareSshReadState = Pick< + AppState, + | 'sshConnectionStates' + | 'sshTargetLabels' + | 'removedSshTargetLabels' + | 'sshTargetsHydrated' + | 'sshStateByEnvironment' +> & + Partial> + +function isEnvironmentReachable(state: RuntimeAwareSshReadState, environmentId: string): boolean { + return Boolean(state.runtimeStatusByEnvironmentId?.get(environmentId)?.status) +} + +/** + * Reconnect-overlay status for an SSH target owned by `environmentId` (a + * remote Orca server) or by this machine (`environmentId === null`). + * + * Returns null when the state is unknown — environment unreachable or its + * bucket not hydrated — so callers show nothing rather than another machine's + * stale state. The runtime environment's own disconnected UI outranks any SSH + * overlay in that case. + */ +export function selectRuntimeAwareSshStatus( + state: RuntimeAwareSshReadState, + environmentId: string | null, + targetId: string +): SshConnectionStatus | null { + if (environmentId === null) { + return state.sshConnectionStates.get(targetId)?.status ?? 'disconnected' + } + if (!isEnvironmentReachable(state, environmentId)) { + return null + } + const bucket = state.sshStateByEnvironment.get(environmentId) + if (!bucket?.targetsHydrated) { + return null + } + return bucket.connectionStates.get(targetId)?.status ?? 'disconnected' +} + +export function selectRuntimeAwareSshTargetLabel( + state: RuntimeAwareSshReadState, + environmentId: string | null, + targetId: string +): string { + if (environmentId === null) { + return ( + state.sshTargetLabels.get(targetId) ?? + // Fall back to the removed target's last known label (ghost host) before + // the raw id, so a removed host shows its name instead of ssh--. + state.removedSshTargetLabels.get(targetId) ?? + targetId + ) + } + const bucket = state.sshStateByEnvironment.get(environmentId) + return bucket?.targetLabels.get(targetId) ?? bucket?.removedTargetLabels.get(targetId) ?? targetId +} + +/** + * True only on positive evidence that the target was removed on its owning + * host: a removal tombstone, or a hydrated target list that lacks the id. + * An unreachable environment or un-hydrated bucket never reports removal, so + * destructive "remove workspace" UI cannot be offered out of ignorance. + */ +export function selectRuntimeAwareSshTargetRemoved( + state: RuntimeAwareSshReadState, + environmentId: string | null, + targetId: string +): boolean { + if (environmentId === null) { + return ( + state.removedSshTargetLabels.has(targetId) || + (state.sshTargetsHydrated && !state.sshTargetLabels.has(targetId)) + ) + } + if (!isEnvironmentReachable(state, environmentId)) { + return false + } + const bucket = state.sshStateByEnvironment.get(environmentId) + if (!bucket) { + return false + } + return ( + bucket.removedTargetLabels.has(targetId) || + (bucket.targetsHydrated && !bucket.targetLabels.has(targetId)) + ) +} diff --git a/src/renderer/src/store/slices/runtime-status.test.ts b/src/renderer/src/store/slices/runtime-status.test.ts index 1300633a9..325acdf87 100644 --- a/src/renderer/src/store/slices/runtime-status.test.ts +++ b/src/renderer/src/store/slices/runtime-status.test.ts @@ -2,6 +2,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { create } from 'zustand' import type { RuntimeStatus } from '../../../../shared/runtime-types' import { createCompatibleRuntimeStatusResponse } from '../../runtime/runtime-compatibility-test-fixture' +import { + callRuntimeRpc, + clearRuntimeCompatibilityCacheForTests +} from '../../runtime/runtime-rpc-client' import { createRuntimeStatusSlice, type RuntimeStatusSlice } from './runtime-status' function createSliceStore() { @@ -162,6 +166,125 @@ describe('runtime-status slice', () => { ) }) + it('drops a recent compatibility failure once a status refresh succeeds', async () => { + clearRuntimeCompatibilityCacheForTests() + let offline = true + const call = vi.fn().mockImplementation(({ method }: { method: string }) => { + if (offline || method === 'status.get') { + return Promise.resolve( + offline + ? { + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'runtime-a' } + } + : createCompatibleRuntimeStatusResponse('runtime-a') + ) + } + return Promise.resolve({ id: method, ok: true, result: { ok: true }, _meta: {} }) + }) + const getStatus = vi.fn().mockResolvedValue(createCompatibleRuntimeStatusResponse('runtime-a')) + vi.stubGlobal('window', { api: { runtimeEnvironments: { getStatus, call } } }) + const store = createSliceStore() + const target = { kind: 'environment', environmentId: 'env-a' } as const + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + // Reuse-flagged callers stay pinned to the recent failure until recovery. + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + + offline = false + await store.getState().refreshRuntimeEnvironmentStatus('env-a') + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).resolves.toEqual({ ok: true }) + clearRuntimeCompatibilityCacheForTests() + }) + + it('drops a recent compatibility failure on a direct non-null status publish', async () => { + // Why: paths like Settings "Connect" publish the host online via + // setRuntimeEnvironmentStatus directly (not refreshRuntimeEnvironmentStatus) + // and then trigger a reuse-flagged repo.list. The stale failure must drop so + // that reuse-flagged catalog fetch re-probes the now-reachable host. + clearRuntimeCompatibilityCacheForTests() + let offline = true + const call = vi.fn().mockImplementation(({ method }: { method: string }) => { + if (offline || method === 'status.get') { + return Promise.resolve( + offline + ? { + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'runtime-a' } + } + : createCompatibleRuntimeStatusResponse('runtime-a') + ) + } + return Promise.resolve({ id: method, ok: true, result: { ok: true }, _meta: {} }) + }) + vi.stubGlobal('window', { api: { runtimeEnvironments: { call } } }) + const store = createSliceStore() + const target = { kind: 'environment', environmentId: 'env-a' } as const + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + + offline = false + store.getState().setRuntimeEnvironmentStatus('env-a', { status: makeStatus(), checkedAt: 1 }) + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).resolves.toEqual({ ok: true }) + clearRuntimeCompatibilityCacheForTests() + }) + + it('preserves a recent compatibility failure on a null (offline) status publish', async () => { + // Why: recording an unreachable host must not undermine the fanout fix — a + // null status is not proof of reachability, so reuse-flagged sweeps keep + // reusing the one recent failure instead of re-probing per repo. + clearRuntimeCompatibilityCacheForTests() + let offline = true + const call = vi.fn().mockImplementation(({ method }: { method: string }) => { + if (offline || method === 'status.get') { + return Promise.resolve( + offline + ? { + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'runtime-a' } + } + : createCompatibleRuntimeStatusResponse('runtime-a') + ) + } + return Promise.resolve({ id: method, ok: true, result: { ok: true }, _meta: {} }) + }) + vi.stubGlobal('window', { api: { runtimeEnvironments: { call } } }) + const store = createSliceStore() + const target = { kind: 'environment', environmentId: 'env-a' } as const + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + + // A null publish (host still unreachable) must keep the failure pinned even + // after the transport would answer, so the reuse-flagged caller does not probe. + offline = false + store.getState().setRuntimeEnvironmentStatus('env-a', { status: null, checkedAt: 1 }) + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + clearRuntimeCompatibilityCacheForTests() + }) + it('records null and returns false when a runtime refresh fails', async () => { const getStatus = vi.fn().mockRejectedValue(new Error('closed')) stubRuntimeEnvironmentApi({ getStatus }) diff --git a/src/renderer/src/store/slices/runtime-status.ts b/src/renderer/src/store/slices/runtime-status.ts index 970f322fe..e9dae52e2 100644 --- a/src/renderer/src/store/slices/runtime-status.ts +++ b/src/renderer/src/store/slices/runtime-status.ts @@ -2,7 +2,10 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' import type { RuntimeStatus } from '../../../../shared/runtime-types' -import { unwrapRuntimeRpcResult } from '@/runtime/runtime-rpc-client' +import { + clearRecentRuntimeCompatibilityFailure, + unwrapRuntimeRpcResult +} from '@/runtime/runtime-rpc-client' /** Live status for one saved runtime environment, as last observed by the * renderer. `status === null` records a probe that failed or timed out so the @@ -63,14 +66,23 @@ export const createRuntimeStatusSlice: StateCreator environment.id)) + // A detached environment's mirrored SSH state must not outlive it. + get().retainEnvironmentSshState?.(environments.map((environment) => environment.id)) }, - setRuntimeEnvironmentStatus: (environmentId, status) => + setRuntimeEnvironmentStatus: (environmentId, status) => { + // Why: a non-null status proves the runtime just answered, so drop any stale + // "offline" compat failure before this online transition fires the + // reuse-flagged background refetches — a recovered host must re-probe. + if (status.status !== null) { + clearRecentRuntimeCompatibilityFailure(environmentId) + } set((s) => { const next = new Map(s.runtimeStatusByEnvironmentId) next.set(environmentId, status) return { runtimeStatusByEnvironmentId: next } - }), + }) + }, clearRuntimeEnvironmentStatus: (environmentId) => set((s) => { @@ -103,6 +115,8 @@ export const createRuntimeStatusSlice: StateCreator(response) + // setRuntimeEnvironmentStatus drops any stale compat failure on a non-null + // (reachable) status, so a recovered host's reuse-flagged refetches re-probe. get().setRuntimeEnvironmentStatus(environmentId, { status, checkedAt: Date.now() }) return true } catch { diff --git a/src/renderer/src/store/slices/ssh.test.ts b/src/renderer/src/store/slices/ssh.test.ts index af8f17fd3..ef5ebf677 100644 --- a/src/renderer/src/store/slices/ssh.test.ts +++ b/src/renderer/src/store/slices/ssh.test.ts @@ -146,7 +146,7 @@ describe('createSshSlice', () => { it('keeps SSH target label references stable when refreshed metadata is unchanged', () => { const store = createTestStore() const labels = new Map([['ssh-1', 'Remote']]) - store.setState({ sshTargetLabels: labels }) + store.setState({ sshTargetLabels: labels, sshTargetsHydrated: true }) const previousState = store.getState() store.getState().setSshTargetsMetadata([{ id: 'ssh-1', label: 'Remote' }]) @@ -155,6 +155,18 @@ describe('createSshSlice', () => { expect(store.getState().sshTargetLabels).toBe(labels) }) + it('marks targets hydrated on the first load, even when the list is empty', () => { + const store = createTestStore() + expect(store.getState().sshTargetsHydrated).toBe(false) + + store.getState().setSshTargetsMetadata([]) + + // Why: an empty target set is still positive knowledge — the overlay's + // targetRemoved derivation may only trust absence after a real load. + expect(store.getState().sshTargetsHydrated).toBe(true) + expect(store.getState().sshTargetLabels.size).toBe(0) + }) + it('keeps SSH connection state references stable when duplicate state arrives', () => { const store = createTestStore() const sshConnectionStates = new Map([ diff --git a/src/renderer/src/store/slices/ssh.ts b/src/renderer/src/store/slices/ssh.ts index b7d2b9eb4..6b80e0543 100644 --- a/src/renderer/src/store/slices/ssh.ts +++ b/src/renderer/src/store/slices/ssh.ts @@ -33,6 +33,15 @@ export type SshSlice = { /** Maps target IDs to their user-facing labels. Populated during hydration * so components can look up labels without per-component IPC calls. */ sshTargetLabels: Map + /** Maps REMOVED target IDs to their last known label (from re-adoption + * tombstones). Lets ghost-host UI show a friendly name instead of the raw id + * for a workspace still pinned to a deleted target. */ + removedSshTargetLabels: Map + /** True once a target list actually loaded (even an empty one). Distinguishes + * "this client knows the target set" from "never hydrated" (e.g. a paired + * client on a host without the ssh RPC), so absence from sshTargetLabels + * only counts as removal evidence when this is set. */ + sshTargetsHydrated: boolean remoteWorkspaceHydratedTargetIds: Set remoteWorkspaceSyncStatusByTargetId: Record sshCredentialQueue: SshCredentialRequest[] @@ -50,6 +59,7 @@ export type SshSlice = { detectedPortsByConnection: Record setSshConnectionState: (targetId: string, state: SshConnectionState) => void setSshTargetLabels: (labels: Map) => void + setRemovedSshTargetLabels: (labels: Record) => void setSshTargetsMetadata: (targets: Pick[]) => void clearRemovedSshTargetState: (targetId: string) => void markRemoteWorkspaceHydrated: (targetId: string) => void @@ -65,6 +75,8 @@ export type SshSlice = { export const createSshSlice: StateCreator = (set) => ({ sshConnectionStates: new Map(), sshTargetLabels: new Map(), + removedSshTargetLabels: new Map(), + sshTargetsHydrated: false, remoteWorkspaceHydratedTargetIds: new Set(), remoteWorkspaceSyncStatusByTargetId: {}, sshCredentialQueue: [], @@ -90,13 +102,18 @@ export const createSshSlice: StateCreator = (set) => }), setSshTargetLabels: (labels) => set({ sshTargetLabels: labels }), + setRemovedSshTargetLabels: (labels) => + set({ removedSshTargetLabels: new Map(Object.entries(labels)) }), setSshTargetsMetadata: (targets) => set((s) => { if (sshTargetLabelsEqual(s.sshTargetLabels, targets)) { - return s + // Why: an unchanged (even empty) list is still a successful load — the + // hydration flag must flip on the first fetch of an empty target set. + return s.sshTargetsHydrated ? s : { sshTargetsHydrated: true } } return { - sshTargetLabels: new Map(targets.map((target) => [target.id, target.label])) + sshTargetLabels: new Map(targets.map((target) => [target.id, target.label])), + sshTargetsHydrated: true } }), clearRemovedSshTargetState: (targetId) => diff --git a/src/renderer/src/store/slices/store-test-helpers.ts b/src/renderer/src/store/slices/store-test-helpers.ts index b1e09bf4e..df36fa5a9 100644 --- a/src/renderer/src/store/slices/store-test-helpers.ts +++ b/src/renderer/src/store/slices/store-test-helpers.ts @@ -31,6 +31,7 @@ import { createOpenCodeUsageSlice } from './opencode-usage' import { createBrowserSlice } from './browser' import { createRateLimitSlice } from './rate-limits' import { createSshSlice } from './ssh' +import { createRuntimeEnvironmentSshSlice } from './runtime-environment-ssh' import { createAgentStatusSlice } from './agent-status' import { createPaneForegroundAgentSlice } from './pane-foreground-agent' import { createDiffCommentsSlice } from './diffComments' @@ -77,6 +78,7 @@ export function createTestStore() { ...createBrowserSlice(...a), ...createRateLimitSlice(...a), ...createSshSlice(...a), + ...createRuntimeEnvironmentSshSlice(...a), ...createAgentStatusSlice(...a), ...createPaneForegroundAgentSlice(...a), ...createDiffCommentsSlice(...a), diff --git a/src/renderer/src/store/slices/superseded-ssh-repo-rows.test.ts b/src/renderer/src/store/slices/superseded-ssh-repo-rows.test.ts new file mode 100644 index 000000000..64299ac37 --- /dev/null +++ b/src/renderer/src/store/slices/superseded-ssh-repo-rows.test.ts @@ -0,0 +1,56 @@ +import { describe, it, expect } from 'vitest' +import { pruneSupersededSshRepoRows } from './superseded-ssh-repo-rows' +import type { Repo } from '../../../../shared/types' + +function repo(overrides: Partial): Repo { + return { + id: 'r', + path: '/p', + displayName: 'r', + badgeColor: '#000', + addedAt: 1, + ...overrides + } +} + +describe('pruneSupersededSshRepoRows', () => { + it('drops a stale dead-SSH row when a live-host sibling shares the id', () => { + // The re-adoption leftover: same id on a dead target + a live one. + const repos = [ + repo({ id: 'shared', connectionId: 'ssh-dead' }), + repo({ id: 'shared', connectionId: 'ssh-live' }) + ] + const result = pruneSupersededSshRepoRows(repos, new Set(['ssh-live'])) + expect(result.map((r) => r.connectionId)).toEqual(['ssh-live']) + }) + + it('KEEPS a lone project-only ghost (no live sibling) so it can still be forgotten', () => { + const repos = [repo({ id: 'ghost', connectionId: 'ssh-dead' })] + const result = pruneSupersededSshRepoRows(repos, new Set()) + expect(result).toHaveLength(1) + expect(result[0].connectionId).toBe('ssh-dead') + }) + + it('drops a dead-SSH row superseded by a LOCAL sibling', () => { + // A repo id on both local and a removed SSH host: the local row is the live + // sibling, so the SSH ghost is a re-adoption/duplicate leftover → drop it. + const repos = [repo({ id: 'shared' }), repo({ id: 'shared', connectionId: 'ssh-dead' })] + const result = pruneSupersededSshRepoRows(repos, new Set()) + expect(result.map((r) => r.connectionId ?? 'local')).toEqual(['local']) + }) + + it('leaves live SSH rows untouched', () => { + const repos = [repo({ id: 'a', connectionId: 'ssh-live' }), repo({ id: 'b' })] + const result = pruneSupersededSshRepoRows(repos, new Set(['ssh-live'])) + expect(result).toHaveLength(2) + }) + + it('never prunes runtime-owned SSH rows', () => { + const repos = [ + repo({ id: 'shared', connectionId: 'runtime-ssh-abc' }), + repo({ id: 'shared', connectionId: 'ssh-live' }) + ] + const result = pruneSupersededSshRepoRows(repos, new Set(['ssh-live'])) + expect(result).toHaveLength(2) + }) +}) diff --git a/src/renderer/src/store/slices/superseded-ssh-repo-rows.ts b/src/renderer/src/store/slices/superseded-ssh-repo-rows.ts new file mode 100644 index 000000000..c97d9bb96 --- /dev/null +++ b/src/renderer/src/store/slices/superseded-ssh-repo-rows.ts @@ -0,0 +1,50 @@ +import type { Repo } from '../../../../shared/types' +import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host' + +/** + * Drops repo rows left stranded on a removed SSH target after re-adoption + * re-pointed the same repo onto a re-added host. + * + * Re-adoption (main) rewrites a repo's connectionId from the old (dead) target + * id to the new one, but the renderer's per-host repo merge preserves rows on + * "other hosts" — and the dead SSH host still looks like another host, so its + * stale row lingers. A terminal pane bound to that ghost row then fails with + * "SSH target not found". + * + * A row is superseded (and pruned) only when ALL hold: + * - it targets an SSH connection that is NOT a currently-known target, and + * - the same repo id also exists on a DIFFERENT host that IS known/live. + * + * This never removes a legitimate lone project-only ghost host (its repo id + * exists only on the dead host, so there is no live sibling to supersede it) — + * those are kept on purpose so the sidebar can still surface and forget them. + */ +export function pruneSupersededSshRepoRows( + repos: readonly Repo[], + knownSshTargetIds: ReadonlySet +): Repo[] { + const isDeadSshRow = (repo: Repo): boolean => { + const connectionId = repo.connectionId?.trim() + if (!connectionId || isRuntimeOwnedSshTargetId(connectionId)) { + return false + } + return !knownSshTargetIds.has(connectionId) + } + + // Repo ids that have at least one row on a known/live host (local or a live + // SSH/runtime target). Only these can supersede a dead-host sibling. + const idsWithLiveHost = new Set() + for (const repo of repos) { + if (!isDeadSshRow(repo)) { + idsWithLiveHost.add(repo.id) + } + } + + return repos.filter((repo) => { + if (!isDeadSshRow(repo)) { + return true + } + // Keep a lone ghost (no live sibling); drop only a superseded leftover. + return !idsWithLiveHost.has(repo.id) + }) +} diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 3a0205cbe..04748058e 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -745,6 +745,7 @@ export type UISlice = { | 'create-worktree' | 'edit-meta' | 'delete-worktree' + | 'forget-ssh-workspace' | 'confirm-add-project-from-folder' | 'confirm-non-git-folder' | 'confirm-remove-folder' diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index bd42ac04b..04db206bc 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -177,7 +177,11 @@ export type WorktreeSlice = { prefetchWorktreeCreateBase: (repoId: string, baseBranch?: string) => Promise removeWorktree: ( worktreeId: string, - force?: boolean + force?: boolean, + // 'forget-local' drops the workspace from Orca only (no remote Git/FS work) + // for workspaces pinned to a removed/disconnected SSH host. Reuses the same + // renderer-side teardown/purge as a normal remove. + options?: { mode?: 'remove' | 'forget-local' } ) => Promise<({ ok: true } & RemoveWorktreeResult) | { ok: false; error: string }> markWorktreesDeleting: (worktreeIds: readonly string[]) => void forceDeletePreservedBranch: ( diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index b9b5b0bdb..8929f5759 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -132,6 +132,7 @@ function createTestStore() { openModal: vi.fn(), shutdownWorktreeTerminals: vi.fn().mockResolvedValue(undefined), shutdownWorktreeBrowsers: vi.fn().mockResolvedValue(undefined), + ptyIdsByTabId: {}, tabsByWorktree: {}, tabBarOrderByWorktree: {}, pendingReconnectTabByWorktree: {}, @@ -5811,6 +5812,103 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => { expect(store.getState().hasHydratedWorktreePurge).toBe(true) }) + it('reuses an offline runtime preflight across hydrated all-worktree refresh repos', async () => { + const store = createTestStore() + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + const repos = Array.from({ length: WORKTREE_REFRESH_CONCURRENCY + 2 }, (_, index) => ({ + id: `runtime-repo-${index}`, + path: `/remote/repos/${index}`, + displayName: `runtime-repo-${index}`, + badgeColor: '#000', + addedAt: 0, + executionHostId: 'runtime:env-offline' + })) + + runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + if (args.method === 'status.get') { + return Promise.resolve({ + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'runtime-offline' } + }) + } + return runtimeEnvironmentCall(args) + }) + + try { + store.setState({ + hasHydratedWorktreePurge: true, + repos + } as unknown as Partial) + + await store.getState().fetchAllWorktrees() + } finally { + consoleError.mockRestore() + } + + expect(runtimeEnvironmentTransportCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get' + ]) + expect(runtimeEnvironmentCall).not.toHaveBeenCalled() + expect(mockApi.worktrees.listDetected).not.toHaveBeenCalled() + }) + + it('does not coalesce a foreground re-probe onto a background reuse:true scan for a remote repo', async () => { + // Why: the reuse flag is part of the coalescing key for remote targets, so a + // foreground fetchWorktrees (reuse:false) must run its own compat-preflighted + // scan instead of sharing a background reuse:true scan that may have reused a + // stale failure — the foreground caller must always re-probe. + const store = createTestStore() + const remote = makeWorktree({ id: 'repo1::/remote/wt', repoId: 'repo1', path: '/remote/wt' }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + hasHydratedWorktreePurge: true, + repos: [ + { + id: 'repo1', + path: '/r1', + displayName: 'R1', + badgeColor: '#000', + addedAt: 0, + executionHostId: 'runtime:env-1' + } + ] + } as Partial) + + let scanStartedCount = 0 + const scanReleases: (() => void)[] = [] + runtimeEnvironmentCall.mockImplementation(({ method }: RuntimeEnvironmentCallRequest) => { + if (method === 'worktree.detectedList') { + scanStartedCount += 1 + return new Promise((resolve) => { + scanReleases.push(() => + resolve({ + id: 'rpc', + ok: true, + result: makeDetectedResult('repo1', [remote]), + _meta: { runtimeId: 'runtime-remote' } + }) + ) + }) + } + return Promise.resolve({ id: method, ok: true, result: {}, _meta: {} }) + }) + + const background = store.getState().fetchAllWorktrees() + const foreground = store.getState().fetchWorktrees('repo1') + // Flush microtasks so both compat preflights settle and both scans block. + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(scanStartedCount).toBe(2) + + scanReleases.forEach((release) => release()) + await Promise.all([background, foreground]) + expect(store.getState().worktreesByRepo.repo1?.map((worktree) => worktree.id)).toEqual([ + remote.id + ]) + }) + it('preserves floating workspace state while purging a real stale worktree', async () => { const store = createTestStore() const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' }) diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 0ff92d352..36d70b5d3 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -84,6 +84,10 @@ const folderWorkspaceWorktreeCache = new WeakMap() const hostedReviewPushTargetLookupsInFlight = new Set() const detectedWorktreeRefreshesInFlight = new Map>() +type BackgroundRuntimeRefreshOptions = { + reuseRecentCompatibilityFailure?: boolean +} + async function mapReposForWorktreeRefresh( repos: readonly TRepo[], mapper: (repo: TRepo) => Promise @@ -857,7 +861,8 @@ function settingsForWorktreeOwner( async function listDetectedWorktreesForRepo( settings: AppState['settings'], - repoId: string + repoId: string, + options: BackgroundRuntimeRefreshOptions = {} ): Promise { const target = getActiveRuntimeTarget(settings) if (target.kind === 'local') { @@ -875,7 +880,10 @@ async function listDetectedWorktreesForRepo( target, 'worktree.detectedList', { repo: repoId }, - { timeoutMs: 15_000 } + { + timeoutMs: 15_000, + reuseRecentCompatibilityFailure: options.reuseRecentCompatibilityFailure + } ) } catch (error) { if (!isRuntimeMethodNotFoundError(error)) { @@ -885,7 +893,10 @@ async function listDetectedWorktreesForRepo( target, 'worktree.list', { repo: repoId, limit: REMOTE_WORKTREE_LIST_PARITY_LIMIT }, - { timeoutMs: 15_000 } + { + timeoutMs: 15_000, + reuseRecentCompatibilityFailure: options.reuseRecentCompatibilityFailure + } ) return toLegacyDetectedWorktreeResult(repoId, legacy) } @@ -894,22 +905,38 @@ async function listDetectedWorktreesForRepo( function detectedWorktreeRefreshKey( settings: AppState['settings'], repoId: string, - options: { executionHostId: ExecutionHostId; requireAuthoritative?: boolean } + options: { + executionHostId: ExecutionHostId + requireAuthoritative?: boolean + reuseRecentCompatibilityFailure?: boolean + } ): string { const target = getActiveRuntimeTarget(settings) const targetKey = target.kind === 'local' ? 'local' : `runtime:${target.environmentId}` - return [ + const parts = [ repoId, options.executionHostId, targetKey, options.requireAuthoritative === true ? 'authoritative' : 'best-effort' - ].join('\n') + ] + // Why: only remote targets run a compat preflight, so a foreground (reuse:false) + // refresh must not coalesce onto a background reuse:true scan that reused a + // stale failure — it must re-probe. Local targets have no preflight; keep them + // coalesced so a foreground/background collision stays one git scan. + if (target.kind === 'environment') { + parts.push(options.reuseRecentCompatibilityFailure === true ? 'reuse-failure' : 'reprobe') + } + return parts.join('\n') } async function listDetectedWorktreesForRepoCoalesced( settings: AppState['settings'], repoId: string, - options: { executionHostId: ExecutionHostId; requireAuthoritative?: boolean } + options: { + executionHostId: ExecutionHostId + requireAuthoritative?: boolean + reuseRecentCompatibilityFailure?: boolean + } ): Promise { const key = detectedWorktreeRefreshKey(settings, repoId, options) const existing = detectedWorktreeRefreshesInFlight.get(key) @@ -918,7 +945,9 @@ async function listDetectedWorktreesForRepoCoalesced( } // Why: startup/event fan-out can ask for the same repo/host refresh many // times at once; share only the scan promise so state merge semantics stay local. - const refresh = listDetectedWorktreesForRepo(settings, repoId) + const refresh = listDetectedWorktreesForRepo(settings, repoId, { + reuseRecentCompatibilityFailure: options.reuseRecentCompatibilityFailure + }) detectedWorktreeRefreshesInFlight.set(key, refresh) try { return await refresh @@ -929,7 +958,10 @@ async function listDetectedWorktreesForRepoCoalesced( } } -async function listWorktreeLineageForRuntime(settings: AppState['settings']): Promise<{ +async function listWorktreeLineageForRuntime( + settings: AppState['settings'], + options: BackgroundRuntimeRefreshOptions = {} +): Promise<{ worktreeLineageById: Record workspaceLineageByChildKey: Record }> { @@ -956,7 +988,10 @@ async function listWorktreeLineageForRuntime(settings: AppState['settings']): Pr await callRuntimeRpc<{ lineage: Record workspaceLineage?: Record - }>(target, 'worktree.lineageList', undefined, { timeoutMs: 15_000 }) + }>(target, 'worktree.lineageList', undefined, { + timeoutMs: 15_000, + reuseRecentCompatibilityFailure: options.reuseRecentCompatibilityFailure + }) ) } @@ -1062,9 +1097,10 @@ function applyWorktreeLineageUpdate( async function refreshWorktreeLineageForSettings( settings: AppState['settings'], - set: Parameters>[0] + set: Parameters>[0], + options: BackgroundRuntimeRefreshOptions = {} ): Promise { - const lineage = await listWorktreeLineageForRuntime(settings) + const lineage = await listWorktreeLineageForRuntime(settings, options) const hostId = getSettingsFocusedExecutionHostId(settings) set((s) => ({ worktreeLineageById: mergeLineageForHost(s, hostId, lineage.worktreeLineageById), @@ -1084,7 +1120,9 @@ async function refreshRemoteWorktreeLineageBestEffort( return } try { - const lineage = await listWorktreeLineageForRuntime(settings) + const lineage = await listWorktreeLineageForRuntime(settings, { + reuseRecentCompatibilityFailure: true + }) const hostId = getSettingsFocusedExecutionHostId(settings) set((s) => ({ worktreeLineageById: mergeLineageForHost(s, hostId, lineage.worktreeLineageById), @@ -2361,46 +2399,59 @@ export const createWorktreeSlice: StateCreator // double-probe the IPC for the per-repo success signal. if (get().hasHydratedWorktreePurge) { await mapReposForWorktreeRefresh(repos, async (r) => { - const hostId = getRepoExecutionHostId(r) - const setup = getProjectHostSetupForRepoHost(get(), r.id, hostId) - const settings = settingsForKnownRepoOwner(get().settings, r) - const detected = await listDetectedWorktreesForRepoCoalesced(settings, r.id, { - executionHostId: hostId - }) - const worktrees = sanitizeHostedReviewLinksForBranchClears( - toVisibleWorktrees(detected, hostId, setup), - get().worktreesByRepo[r.id] - ) - set((s) => { - const matchOptions = worktreeHostMatchOptions(s, r.id, hostId) - const removedIds = getRemovedWorktreeIdsAfterAuthoritativeScan(s, r.id, detected, hostId) - const mergedWorktrees = mergeWorktreesForHost( - s.worktreesByRepo[r.id], - worktrees, - hostId, - matchOptions + try { + const hostId = getRepoExecutionHostId(r) + const setup = getProjectHostSetupForRepoHost(get(), r.id, hostId) + const settings = settingsForKnownRepoOwner(get().settings, r) + const detected = await listDetectedWorktreesForRepoCoalesced(settings, r.id, { + executionHostId: hostId, + reuseRecentCompatibilityFailure: true + }) + const worktrees = sanitizeHostedReviewLinksForBranchClears( + toVisibleWorktrees(detected, hostId, setup), + get().worktreesByRepo[r.id] ) - const mergedDetected = mergeDetectedWorktreesForHost( - s.detectedWorktreesByRepo[r.id], - detected, - hostId, - setup, - matchOptions - ) - if ( - areWorktreesEqual(s.worktreesByRepo[r.id], mergedWorktrees) && - areDetectedWorktreeResultsEqual(s.detectedWorktreesByRepo[r.id], mergedDetected) && - removedIds.length === 0 - ) { - return s + set((s) => { + const matchOptions = worktreeHostMatchOptions(s, r.id, hostId) + const removedIds = getRemovedWorktreeIdsAfterAuthoritativeScan( + s, + r.id, + detected, + hostId + ) + const mergedWorktrees = mergeWorktreesForHost( + s.worktreesByRepo[r.id], + worktrees, + hostId, + matchOptions + ) + const mergedDetected = mergeDetectedWorktreesForHost( + s.detectedWorktreesByRepo[r.id], + detected, + hostId, + setup, + matchOptions + ) + if ( + areWorktreesEqual(s.worktreesByRepo[r.id], mergedWorktrees) && + areDetectedWorktreeResultsEqual(s.detectedWorktreesByRepo[r.id], mergedDetected) && + removedIds.length === 0 + ) { + return s + } + return { + worktreesByRepo: { ...s.worktreesByRepo, [r.id]: mergedWorktrees }, + detectedWorktreesByRepo: { ...s.detectedWorktreesByRepo, [r.id]: mergedDetected }, + sortEpoch: s.sortEpoch + 1, + ...(removedIds.length > 0 ? buildWorktreePurgeState(s, removedIds) : {}) + } + }) + } catch (err) { + if (notifyRuntimeScopeForbiddenIfNeeded(err)) { + return } - return { - worktreesByRepo: { ...s.worktreesByRepo, [r.id]: mergedWorktrees }, - detectedWorktreesByRepo: { ...s.detectedWorktreesByRepo, [r.id]: mergedDetected }, - sortEpoch: s.sortEpoch + 1, - ...(removedIds.length > 0 ? buildWorktreePurgeState(s, removedIds) : {}) - } - }) + console.error(`Failed to fetch worktrees for repo ${r.id}:`, err) + } }) return } @@ -2430,7 +2481,7 @@ export const createWorktreeSlice: StateCreator const detected = await listDetectedWorktreesForRepoCoalesced( settingsForKnownRepoOwner(get().settings, r), r.id, - { executionHostId: hostId } + { executionHostId: hostId, reuseRecentCompatibilityFailure: true } ) const current = get().worktreesByRepo[r.id] const list = sanitizeHostedReviewLinksForBranchClears( @@ -2543,7 +2594,9 @@ export const createWorktreeSlice: StateCreator try { // Why: lineage is a focused-host refresh — fetch from the focused host and // host-merge so other hosts' previously fetched lineage is preserved. - await refreshWorktreeLineageForSettings(get().settings, set) + await refreshWorktreeLineageForSettings(get().settings, set, { + reuseRecentCompatibilityFailure: true + }) } catch (err) { console.error('Failed to fetch worktree lineage:', err) } @@ -3091,7 +3144,8 @@ export const createWorktreeSlice: StateCreator }) }, - removeWorktree: async (worktreeId, force) => { + removeWorktree: async (worktreeId, force, options) => { + const forgetLocalOnly = options?.mode === 'forget-local' set((s) => ({ deleteStateByWorktreeId: { ...s.deleteStateByWorktreeId, @@ -3104,22 +3158,30 @@ export const createWorktreeSlice: StateCreator })) try { - const repoIdForTrust = getRepoIdFromWorktreeId(worktreeId) - const trustDecision = await ensureHooksConfirmed(get(), repoIdForTrust, 'archive') - const skipArchive = trustDecision === 'skip' + // Why: forget-local touches no remote, so there is no archive hook to run + // and no need to prompt for hook trust. + const skipArchive = forgetLocalOnly + ? true + : (await ensureHooksConfirmed(get(), getRepoIdFromWorktreeId(worktreeId), 'archive')) === + 'skip' const worktreeBeforeRemoval = get() .allWorktrees() .find((entry) => entry.id === worktreeId) + // Why: forget-local always clears Orca's own records via the local IPC + // handler regardless of the workspace's execution host — the whole point + // is that the remote (SSH relay / runtime) is gone or unreachable. const target = getActiveRuntimeTarget(settingsForWorktreeOwner(get(), worktreeId)) - const removalResult = await (target.kind === 'local' - ? window.api.worktrees.remove({ worktreeId, force, skipArchive }) - : callRuntimeRpc( - target, - 'worktree.rm', - { worktree: toRuntimeWorktreeSelector(worktreeId), force, runHooks: !skipArchive }, - { timeoutMs: 60_000 } - )) + const removalResult = await (forgetLocalOnly + ? window.api.worktrees.forgetLocal({ worktreeId }) + : target.kind === 'local' + ? window.api.worktrees.remove({ worktreeId, force, skipArchive }) + : callRuntimeRpc( + target, + 'worktree.rm', + { worktree: toRuntimeWorktreeSelector(worktreeId), force, runHooks: !skipArchive }, + { timeoutMs: 60_000 } + )) const worktreeDisplayName = worktreeBeforeRemoval?.displayName?.trim() if (worktreeDisplayName) { diff --git a/src/renderer/src/store/types.ts b/src/renderer/src/store/types.ts index b5c6f446f..3a266d678 100644 --- a/src/renderer/src/store/types.ts +++ b/src/renderer/src/store/types.ts @@ -21,6 +21,7 @@ import type { OpenCodeUsageSlice } from './slices/opencode-usage' import type { BrowserSlice } from './slices/browser' import type { RateLimitSlice } from './slices/rate-limits' import type { SshSlice } from './slices/ssh' +import type { RuntimeEnvironmentSshSlice } from './slices/runtime-environment-ssh' import type { AgentStatusSlice } from './slices/agent-status' import type { PaneForegroundAgentSlice } from './slices/pane-foreground-agent' import type { DiffCommentsSlice } from './slices/diffComments' @@ -56,6 +57,7 @@ export type AppState = RepoSlice & BrowserSlice & RateLimitSlice & SshSlice & + RuntimeEnvironmentSshSlice & AgentStatusSlice & PaneForegroundAgentSlice & DiffCommentsSlice & diff --git a/src/renderer/src/web/web-preload-api.test.ts b/src/renderer/src/web/web-preload-api.test.ts index 4a1d7b36f..bf46bd403 100644 --- a/src/renderer/src/web/web-preload-api.test.ts +++ b/src/renderer/src/web/web-preload-api.test.ts @@ -592,6 +592,104 @@ describe('web MiniMax preload API', () => { }) }) +describe('web AI Vault preload API', () => { + beforeEach(() => { + vi.resetModules() + }) + + afterEach(() => { + vi.unstubAllGlobals() + vi.doUnmock('./web-runtime-client') + }) + + it('routes session scans through the paired runtime host', async () => { + const runtimeCalls: { method: string; params: unknown }[] = [] + const scanResult = { + sessions: [], + issues: [], + scannedAt: '2026-07-04T00:00:00.000Z' + } + vi.doMock('./web-runtime-client', () => ({ + WebRuntimeClient: class { + call(method: string, params?: unknown): Promise> { + runtimeCalls.push({ method, params }) + return Promise.resolve({ + id: `call-${runtimeCalls.length}`, + ok: true, + result: scanResult, + _meta: { runtimeId: 'runtime-1' } + }) + } + + close(): void {} + } + })) + + const globals = installBrowserGlobals('Linux') + writeStoredRuntimeEnvironment(globals.storage) + const { installWebPreloadApi } = await import('./web-preload-api') + installWebPreloadApi() + + await expect( + globals.window.api.aiVault.listSessions({ + executionHostScope: 'all', + limit: 25, + force: true, + scopePaths: ['/srv/app'] + }) + ).resolves.toEqual(scanResult) + expect(runtimeCalls).toEqual([ + { + method: 'aiVault.listSessions', + params: { + limit: 25, + force: true, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:web-env-1' + } + } + ]) + }) + + it('returns unavailable history for explicit non-runtime host scopes', async () => { + const runtimeCalls: { method: string; params: unknown }[] = [] + vi.doMock('./web-runtime-client', () => ({ + WebRuntimeClient: class { + call(method: string, params?: unknown): Promise> { + runtimeCalls.push({ method, params }) + return Promise.resolve({ + id: `call-${runtimeCalls.length}`, + ok: true, + result: { sessions: [], issues: [], scannedAt: '2026-07-04T00:00:00.000Z' }, + _meta: { runtimeId: 'runtime-1' } + }) + } + + close(): void {} + } + })) + + const globals = installBrowserGlobals('Linux') + writeStoredRuntimeEnvironment(globals.storage) + const { installWebPreloadApi } = await import('./web-preload-api') + installWebPreloadApi() + + await expect( + globals.window.api.aiVault.listSessions({ executionHostScope: 'local' }) + ).resolves.toEqual({ + sessions: [], + issues: [ + expect.objectContaining({ + executionHostId: 'local', + agent: 'codex' + }) + ], + scannedAt: expect.any(String) + }) + expect(runtimeCalls).toEqual([]) + }) +}) + describe('web UI preload API', () => { beforeEach(() => { vi.resetModules() diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 55001c554..36f13fe2b 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -10,6 +10,7 @@ import type { NativeChatAppendedMessages } from '../../../preload/api-types' import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import type { AiVaultListArgs, AiVaultListResult } from '../../../shared/ai-vault-types' import { buildNativeChatUnsubscribe } from '../../../shared/native-chat-stream-unsubscribe' import type { ComputerUsePermissionSetupResult, @@ -34,6 +35,7 @@ import type { WorkspaceSessionState } from '../../../shared/types' import type { SkillDiscoveryResult } from '../../../shared/skills' +import type { SshConnectionState, SshTarget } from '../../../shared/ssh-types' import { getDefaultOnboardingState, getDefaultSettings, @@ -48,7 +50,13 @@ import { legacyBaseRefSearchResult } from '../../../shared/base-ref-search-resul import { EMPTY_PTY_MAIN_DELIVERY_DIAGNOSTICS } from '../../../shared/pty-delivery-diagnostics' import { createE2EConfig } from '../../../shared/e2e-config' import { relativePathInsideRoot } from '../../../shared/cross-platform-path' -import { LOCAL_EXECUTION_HOST_ID, normalizeExecutionHostId } from '../../../shared/execution-host' +import { + LOCAL_EXECUTION_HOST_ID, + normalizeExecutionHostScope, + normalizeExecutionHostId, + toRuntimeExecutionHostId, + type ExecutionHostId +} from '../../../shared/execution-host' import { toRuntimeWorktreeSelector } from '../runtime/runtime-worktree-selector' import { normalizeDisabledTuiAgents } from '../../../shared/tui-agent-selection' import { @@ -630,15 +638,7 @@ function createWebPreloadApi(): Partial { memory: { getSnapshot: () => Promise.resolve(createEmptyMemorySnapshot()) }, - aiVault: { - listSessions: () => - Promise.resolve({ - sessions: [], - issues: [], - scannedAt: new Date().toISOString() - }), - onWindowFocused: () => () => {} - }, + aiVault: createAiVaultApi(), preflight: createPreflightApi(), notifications: createNotificationsApi(), rateLimits: createRateLimitsApi(), @@ -1120,6 +1120,48 @@ function createRuntimeEnvironmentsApi(): NonNullable['runtim } } +function createAiVaultApi(): NonNullable['aiVault']> { + return { + listSessions: (args?: AiVaultListArgs) => { + const environment = requireActiveEnvironment() + const executionHostId = toRuntimeExecutionHostId(environment.id) + const requestedScope = normalizeExecutionHostScope( + args?.executionHostScope ?? executionHostId + ) + if (requestedScope !== 'all' && requestedScope !== executionHostId) { + return Promise.resolve(webAiVaultUnavailableResult(requestedScope)) + } + // Why: the browser client has no local filesystem; every history scan + // runs on the paired server and must be stamped as that runtime host. + return callRuntimeResult('aiVault.listSessions', { + limit: args?.limit, + force: args?.force, + scopePaths: args?.scopePaths, + executionHostId + }) + }, + onWindowFocused: () => noopUnsubscribe + } +} + +function webAiVaultUnavailableResult(executionHostId: ExecutionHostId): AiVaultListResult { + return { + sessions: [], + issues: [ + { + executionHostId, + agent: 'codex', + path: executionHostId, + message: translate( + 'auto.web.webPreloadApi.aiVaultUnavailableForHost', + 'Agent Session History is not available for this execution host.' + ) + } + ], + scannedAt: new Date().toISOString() + } +} + function createReposApi(): NonNullable['repos']> { return { list: async () => (await callRuntimeResult<{ repos: Repo[] }>('repo.list')).repos, @@ -1131,6 +1173,12 @@ function createReposApi(): NonNullable['repos']> { await callRuntimeResult('repo.rm', { repo: repoId }) invalidateRuntimeWorktreeCaches() }, + // Why: host-scoped forget targets a disconnected/removed SSH host owned by + // the desktop app. A paired web client talks to a single Orca runtime and + // has no ghost-host state to reconcile. + removeForHost: () => { + throw new Error('Forgetting a host is unavailable in paired web clients.') + }, reorder: async ({ orderedIds }) => callRuntimeResult('repo.reorder', { orderedIds }), update: async ({ repoId, updates }) => (await callRuntimeResult<{ repo: Repo }>('repo.update', { repo: repoId, updates })).repo, @@ -1294,6 +1342,11 @@ function createWorktreesApi(): NonNullable['worktrees']> { force }) }, + // Why: forget-locally clears a workspace pinned to a disconnected/removed + // SSH host on the desktop app; a paired web client has no such ghost state. + forgetLocal: () => { + throw new Error('Forgetting a workspace is unavailable in paired web clients.') + }, forceDeletePreservedBranch: ({ worktreeId, branchName, expectedHead }) => callRuntimeResult('worktree.forceDeleteBranch', { worktree: toRuntimeWorktreeSelector(worktreeId), @@ -1460,6 +1513,10 @@ function createFileApi(): NonNullable['fs']> { ) return result.files.map((entry) => entry.relativePath) }, + cancelListFiles: async () => { + // Why: the paired-web path lists files over runtime RPC with its own + // request timeout; there is no host-side scan to abort from here. + }, search: async (args) => { const file = await resolveRuntimeFilePath(args.rootPath) return callRuntimeResult('files.search', { @@ -2227,6 +2284,9 @@ function createWebUiApi(): NonNullable['ui']> { onCloseTerminal: () => noopUnsubscribe, onSleepWorktree: () => noopUnsubscribe, onTerminalZoom: () => noopUnsubscribe, + // Why: a paired web client has no OS sleep signal; occlusion-driven + // visibilitychange already covers its wake recovery. + onSystemResumed: () => noopUnsubscribe, onFileDrop: () => noopUnsubscribe, syncTrafficLights: () => {}, setMarkdownEditorFocused: () => {}, @@ -2235,9 +2295,6 @@ function createWebUiApi(): NonNullable['ui']> { setShortcutRecorderFocused: () => {}, onRichMarkdownContextCommand: () => noopUnsubscribe, onFullscreenChanged: () => noopUnsubscribe, - // Why: web clients run in a browser tab; the host OS resume signal only - // exists in the Electron shell. - onSystemResumed: () => noopUnsubscribe, minimize: () => {}, maximize: () => {}, onMaximizeChanged: () => noopUnsubscribe, @@ -2636,18 +2693,51 @@ function createPtyApi(): NonNullable['pty']> { function createSshApi(): NonNullable['ssh']> { return { - listTargets: () => Promise.resolve([]), + // Why: SSH connections are owned by the paired host. Read/connect route to + // its runtime RPC so remote worktrees can show real connection state and + // reconnect (STA-1468); target management stays desktop-only. + listTargets: async () => { + if (!requireActiveEnvironmentOrNull()) { + return [] + } + const { targets } = await callRuntimeResult<{ targets: SshTarget[] }>('ssh.listTargets') + return targets + }, + listRemovedTargetLabels: async () => { + if (!requireActiveEnvironmentOrNull()) { + return {} + } + const { labels } = await callRuntimeResult<{ labels: Record }>( + 'ssh.listRemovedTargetLabels' + ) + return labels + }, addTarget: () => Promise.reject(new Error('SSH target management is unavailable in the web client.')), updateTarget: () => Promise.reject(new Error('SSH target management is unavailable in the web client.')), removeTarget: () => Promise.resolve(), importConfig: () => Promise.resolve([]), - connect: () => Promise.resolve(null), + connect: async (args) => { + const { state } = await callRuntimeResult<{ state: SshConnectionState | null }>( + 'ssh.connect', + { targetId: args.targetId } + ) + return state + }, disconnect: () => Promise.resolve(), terminateSessions: () => Promise.resolve(), resetRelay: () => Promise.resolve(), - getState: () => Promise.resolve(null), + getState: async (args) => { + if (!requireActiveEnvironmentOrNull()) { + return null + } + const { state } = await callRuntimeResult<{ state: SshConnectionState | null }>( + 'ssh.getState', + { targetId: args.targetId } + ) + return state + }, needsPassphrasePrompt: () => Promise.resolve(false), testConnection: () => Promise.resolve({ diff --git a/src/shared/agent-detection.ts b/src/shared/agent-detection.ts index 7ff722ca9..dbb13895a 100644 --- a/src/shared/agent-detection.ts +++ b/src/shared/agent-detection.ts @@ -3,7 +3,9 @@ * * Why shared: main and renderer both consume OSC titles for facts, stats, and * UI state. Keep existing imports stable while the implementation stays split - * into focused modules that satisfy max-lines. + * into focused modules that satisfy max-lines. (main's #7612 split into + * `terminal-title-*` modules coexists — those files stay on disk for their + * direct `resolveTerminalTitleAgentType`/`synthetic-agent-title` consumers.) */ export type { AgentStatus } from './agent-title-core' diff --git a/src/shared/agent-prompt-injection.test.ts b/src/shared/agent-prompt-injection.test.ts new file mode 100644 index 000000000..5ad3e42d4 --- /dev/null +++ b/src/shared/agent-prompt-injection.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { + AGENT_PROMPT_BRACKETED_PASTE_END, + AGENT_PROMPT_BRACKETED_PASTE_START, + buildAgentPromptPasteBytes, + buildAgentPromptSubmitBytes, + iterateAgentPromptPasteChunks, + sanitizeAgentPromptText +} from './agent-prompt-injection' + +const BEGIN = AGENT_PROMPT_BRACKETED_PASTE_START +const END = AGENT_PROMPT_BRACKETED_PASTE_END + +describe('agent prompt injection bytes', () => { + it('always bracket-pastes prompts so agent TUIs treat newlines as content', () => { + expect(buildAgentPromptPasteBytes('line one\nline two')).toBe( + `${BEGIN}line one\nline two${END}` + ) + }) + + it('keeps submit separate from the paste frame', () => { + expect(buildAgentPromptPasteBytes('hello')).not.toContain('\r') + expect(buildAgentPromptSubmitBytes()).toBe('\r') + }) + + it('sanitizes embedded escape bytes before framing', () => { + const bytes = buildAgentPromptPasteBytes('before\x1b[201~after\x1b') + expect(bytes).toBe(`${BEGIN}before[201~after${END}`) + expect(bytes.slice(BEGIN.length, -END.length)).not.toContain('\x1b') + }) + + it('exposes the sanitizer for tests and diagnostics', () => { + expect(sanitizeAgentPromptText('a\x1bb')).toBe('ab') + }) + + it('chunks without changing the reconstructed paste frame', () => { + const prompt = `header\n${'abc123'.repeat(200)}` + const chunks = [...iterateAgentPromptPasteChunks(prompt, 31)] + expect(chunks.length).toBeGreaterThan(1) + expect(chunks.join('')).toBe(buildAgentPromptPasteBytes(prompt)) + expect(chunks.join('')).toContain(`${BEGIN}header\n`) + expect(chunks.join('')).toContain(END) + }) +}) diff --git a/src/shared/agent-prompt-injection.ts b/src/shared/agent-prompt-injection.ts new file mode 100644 index 000000000..1d57fb060 --- /dev/null +++ b/src/shared/agent-prompt-injection.ts @@ -0,0 +1,43 @@ +import { iterateTerminalInputChunks, TERMINAL_INPUT_CHUNK_MAX_BYTES } from './terminal-input' + +export const AGENT_PROMPT_BRACKETED_PASTE_START = '\x1b[200~' +export const AGENT_PROMPT_BRACKETED_PASTE_END = '\x1b[201~' +export const AGENT_PROMPT_SUBMIT = '\r' + +// Why: Codex/Claude can need a render turn after bracketed-paste end before +// Enter is accepted as submit, not paste content. Match the proven runtime gap. +export const AGENT_PROMPT_SUBMIT_DELAY_MS = 500 + +const ESCAPE = '\x1b' +const INERT_ESCAPE = '' + +export function sanitizeAgentPromptText(text: string): string { + let escapeIndex = text.indexOf(ESCAPE) + if (escapeIndex === -1) { + return text + } + + let sanitized = '' + let start = 0 + while (escapeIndex !== -1) { + sanitized += `${text.slice(start, escapeIndex)}${INERT_ESCAPE}` + start = escapeIndex + ESCAPE.length + escapeIndex = text.indexOf(ESCAPE, start) + } + return sanitized + text.slice(start) +} + +export function buildAgentPromptPasteBytes(prompt: string): string { + return `${AGENT_PROMPT_BRACKETED_PASTE_START}${sanitizeAgentPromptText(prompt)}${AGENT_PROMPT_BRACKETED_PASTE_END}` +} + +export function buildAgentPromptSubmitBytes(): string { + return AGENT_PROMPT_SUBMIT +} + +export function* iterateAgentPromptPasteChunks( + prompt: string, + maxChunkBytes = TERMINAL_INPUT_CHUNK_MAX_BYTES +): Generator { + yield* iterateTerminalInputChunks(buildAgentPromptPasteBytes(prompt), maxChunkBytes) +} diff --git a/src/shared/file-listing-cancellation.ts b/src/shared/file-listing-cancellation.ts new file mode 100644 index 000000000..3296b80c9 --- /dev/null +++ b/src/shared/file-listing-cancellation.ts @@ -0,0 +1,38 @@ +/** + * Cancellation identity for workspace file-list scans (fs.listFiles). + * + * Why a dedicated error class: the readdir fallback wraps budget errors into + * "install rg" guidance and Quick Open surfaces load errors verbatim, so a + * cancelled scan must stay distinguishable from a genuine listing failure at + * every layer (relay rg/git/readdir, main-process local scan, renderer). + */ +export class FileListingCancelledError extends Error { + constructor(message = 'File listing cancelled') { + super(message) + this.name = 'FileListingCancelledError' + } +} + +/** + * Build the rejection for an aborted scan, preferring the abort reason so a + * superseded scan reports "superseded" rather than a generic cancellation. + * Only FileListingCancelledError reasons pass through — a bare abort() sets + * signal.reason to a DOMException that must not leak past the classifier. + */ +export function fileListingCancellationError(signal?: AbortSignal): Error { + const reason = signal?.reason + if (reason instanceof FileListingCancelledError) { + return reason + } + return new FileListingCancelledError() +} + +export function isFileListingCancellation(error: unknown): boolean { + return error instanceof FileListingCancelledError +} + +export function throwIfFileListingCancelled(signal?: AbortSignal): void { + if (signal?.aborted) { + throw fileListingCancellationError(signal) + } +} diff --git a/src/shared/quick-open-readdir-walk.test.ts b/src/shared/quick-open-readdir-walk.test.ts index 66029032a..cb73572bc 100644 --- a/src/shared/quick-open-readdir-walk.test.ts +++ b/src/shared/quick-open-readdir-walk.test.ts @@ -24,6 +24,7 @@ import { listQuickOpenFilesWithReaddir, parseQuickOpenGitLsFilesEntry } from './quick-open-readdir-walk' +import { isFileListingCancellation } from './file-listing-cancellation' const tempDirs: string[] = [] const SHA1 = '0123456789abcdef0123456789abcdef01234567' @@ -259,4 +260,35 @@ describe('quick-open readdir walk', () => { }) ).resolves.toEqual(['packages/app [one] space/src/main.ts']) }) + + it('stops the walk with a cancellation error when the signal aborts (#7721)', async () => { + const root = await makeTempRoot() + await writeRel(root, 'src/a.ts') + await writeRel(root, 'src/b.ts') + + const controller = new AbortController() + controller.abort() + + const rejection = listQuickOpenFilesWithReaddir(root, { signal: controller.signal }) + await expect(rejection).rejects.toSatisfy(isFileListingCancellation) + // Cancellation must never be mistaken for a budget error, which callers + // translate into "install rg" guidance. + await rejection.catch((err) => expect(isQuickOpenReaddirBudgetError(err)).toBe(false)) + }) + + it('stops nested-repo expansion when the signal aborts (#7721)', async () => { + const root = await makeTempRoot() + await writeRel(root, 'src/kept.ts') + + const controller = new AbortController() + controller.abort() + + await expect( + expandQuickOpenGitFilesWithNestedRepos({ + rootPath: root, + gitPaths: ['src/kept.ts'], + signal: controller.signal + }) + ).rejects.toSatisfy(isFileListingCancellation) + }) }) diff --git a/src/shared/quick-open-readdir-walk.ts b/src/shared/quick-open-readdir-walk.ts index 5d3a0a52f..90ce3ea9f 100644 --- a/src/shared/quick-open-readdir-walk.ts +++ b/src/shared/quick-open-readdir-walk.ts @@ -1,5 +1,6 @@ import { lstat, readdir } from 'node:fs/promises' import { join, relative } from 'node:path' +import { throwIfFileListingCancelled } from './file-listing-cancellation' import { HIDDEN_DIR_BLOCKLIST, shouldExcludeQuickOpenRelPath, @@ -157,6 +158,7 @@ export async function listQuickOpenFilesWithReaddir( opts: { excludePathPrefixes?: readonly string[] budget?: QuickOpenReaddirBudget + signal?: AbortSignal } = {} ): Promise { const files: string[] = [] @@ -164,6 +166,9 @@ export async function listQuickOpenFilesWithReaddir( const excludePathPrefixes = opts.excludePathPrefixes ?? [] async function walk(dir: string): Promise { + // Why: an abandoned scan (workspace switch) must stop consuming IO and + // event-loop time on the single-threaded relay, not just run to budget. + throwIfFileListingCancelled(opts.signal) assertWithinDeadline(budget) let entries @@ -176,6 +181,7 @@ export async function listQuickOpenFilesWithReaddir( } for (const entry of entries) { + throwIfFileListingCancelled(opts.signal) assertWithinDeadline(budget) const name = entry.name @@ -206,6 +212,7 @@ export async function expandQuickOpenGitFilesWithNestedRepos(opts: { gitPaths: Iterable excludePathPrefixes?: readonly string[] budget?: QuickOpenReaddirBudget + signal?: AbortSignal }): Promise { const files = new Set() const excludePathPrefixes = opts.excludePathPrefixes ?? [] @@ -224,6 +231,7 @@ export async function expandQuickOpenGitFilesWithNestedRepos(opts: { } for (const rawPath of opts.gitPaths) { + throwIfFileListingCancelled(opts.signal) assertWithinDeadline(budget) const { kind, relPath } = await classifyQuickOpenGitEntry(opts.rootPath, rawPath) @@ -240,7 +248,8 @@ export async function expandQuickOpenGitFilesWithNestedRepos(opts: { // nested repo so the walk prunes excluded subtrees during traversal // instead of burning the shared budget and filtering them at the end. excludePathPrefixes: rebaseExcludePrefixesForNestedRepo(excludePathPrefixes, relPath), - budget + budget, + signal: opts.signal }) for (const nestedFile of nestedFiles) { addFinalPath(`${relPath}/${nestedFile}`) diff --git a/src/shared/remote-runtime-client.test.ts b/src/shared/remote-runtime-client.test.ts index ccb09c15d..5febb2f2d 100644 --- a/src/shared/remote-runtime-client.test.ts +++ b/src/shared/remote-runtime-client.test.ts @@ -104,6 +104,37 @@ describe('subscribeRemoteRuntimeRequest', () => { } }) + it('closes a half-open subscription socket via client liveness so callers can resubscribe', async () => { + // Why: dedicated stream sockets (terminal.multiplex, browser.screencast) + // must not hang forever when a tunnel goes half-open — no close frame, no + // pongs, no data (#7718). Client liveness surfaces onError/onClose so the + // renderer's onTransportClose resubscribe path can run. + const server = await createSubscriptionServer({ disableAutoPong: true }) + const onResponse = vi.fn() + const onError = vi.fn() + const onClose = vi.fn() + + const subscription = await subscribeRemoteRuntimeRequest( + server.pairing, + 'terminal.multiplex', + {}, + 1000, + { onResponse, onError, onClose }, + { pingIntervalMs: 50, livenessTimeoutMs: 200 } + ) + + await vi.waitFor(() => expect(onResponse).toHaveBeenCalled()) + await vi.waitFor( + () => + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ code: 'remote_runtime_unavailable' }) + ), + { timeout: 5000 } + ) + expect(onClose).toHaveBeenCalledOnce() + subscription.close() + }) + it('closes established subscription sockets after terminal protocol errors', async () => { const offSpy = vi.spyOn(WebSocketClient.prototype, 'off') try { @@ -223,6 +254,9 @@ describe('sendRemoteRuntimeRequest', () => { async function createSubscriptionServer( options: { sendMismatchedResponseAfterSubscribe?: boolean + // Why: half-open simulation — the socket stays open but never answers + // protocol pings, like a wedged tunnel that swallows frames silently. + disableAutoPong?: boolean } = {} ): Promise<{ pairing: PairingOffer @@ -233,7 +267,7 @@ async function createSubscriptionServer( const nextBinary = new Promise((resolve) => { resolveBinary = resolve }) - const wss = new WebSocketServer({ port: 0 }) + const wss = new WebSocketServer({ port: 0, autoPong: options.disableAutoPong !== true }) servers.push(wss) wss.on('connection', (ws) => { diff --git a/src/shared/remote-runtime-client.ts b/src/shared/remote-runtime-client.ts index 2f9c2f59b..ecd9f1df7 100644 --- a/src/shared/remote-runtime-client.ts +++ b/src/shared/remote-runtime-client.ts @@ -24,6 +24,11 @@ import { // unaffected; the class lives in a ws-free module so type-only consumers // (and mobile's typecheck) don't compile this file's Node-only deps. import { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { + startRemoteRuntimeSocketLiveness, + type RemoteRuntimeSocketLivenessMonitor, + type RemoteRuntimeSocketLivenessOptions +} from './remote-runtime-socket-liveness' export { RemoteRuntimeClientError } from './remote-runtime-client-error' @@ -354,7 +359,8 @@ export async function subscribeRemoteRuntimeRequest( method: string, params: unknown, timeoutMs: number, - callbacks: RemoteRuntimeSubscriptionCallbacks + callbacks: RemoteRuntimeSubscriptionCallbacks, + livenessOptions?: RemoteRuntimeSocketLivenessOptions ): Promise { return await new Promise((resolve, reject) => { const requestId = randomUUID() @@ -364,8 +370,11 @@ export async function subscribeRemoteRuntimeRequest( let state: HandshakeState = 'awaiting_ready' let settled = false let ws: WebSocket | null = null + let liveness: RemoteRuntimeSocketLivenessMonitor | null = null const cleanupSocketListeners = (): WebSocket | null => { + liveness?.stop() + liveness = null const socket = ws if (!socket) { return null @@ -374,6 +383,8 @@ export async function subscribeRemoteRuntimeRequest( socket.off('error', onError) socket.off('close', onClose) socket.off('message', onMessage) + socket.off('pong', onLivenessSignal) + socket.off('ping', onLivenessSignal) ws = null // Why: startup failures detach Orca callbacks before closing the ws, // but ws can still emit a late transport error while close is in flight. @@ -485,6 +496,7 @@ export async function subscribeRemoteRuntimeRequest( } function onMessage(data: WebSocket.RawData, isBinary: boolean): void { + liveness?.noteActivity() if (isBinary) { handleBinaryFrame(new Uint8Array(data as Buffer)) return @@ -515,10 +527,46 @@ export async function subscribeRemoteRuntimeRequest( handleRpcFrame(plaintext) } + function onLivenessSignal(): void { + liveness?.noteActivity() + } + ws.once('open', onOpen) ws.once('error', onError) ws.on('close', onClose) ws.on('message', onMessage) + ws.on('pong', onLivenessSignal) + ws.on('ping', onLivenessSignal) + + // Why: dedicated stream sockets (terminal.multiplex, browser.screencast) + // ride the same tunnels as shared control; a half-open drop must surface + // as a close so the renderer's onTransportClose resubscribe path runs + // instead of freezing the stream forever (#7718/#7489). + const monitoredWs = ws + liveness = startRemoteRuntimeSocketLiveness({ + ping: () => { + if (monitoredWs.readyState === WebSocket.OPEN) { + monitoredWs.ping() + } + }, + onDead: () => { + // Why: fail() first so listeners detach before terminate's close event; + // otherwise the close handler would emit a second onClose to callers. + fail( + new RemoteRuntimeClientError( + 'remote_runtime_unavailable', + 'Remote Orca runtime stopped responding; the stream connection was reset.' + ) + ) + try { + // Why: close() on a half-open socket can hang for the OS TCP timeout. + monitoredWs.terminate() + } catch { + // Best-effort terminate; the subscription is already settled. + } + }, + options: livenessOptions + }) function handleReadyFrame(frame: string): void { let ready: unknown diff --git a/src/shared/remote-runtime-request-websocket.ts b/src/shared/remote-runtime-request-websocket.ts index 40b4e999d..e5b0ad821 100644 --- a/src/shared/remote-runtime-request-websocket.ts +++ b/src/shared/remote-runtime-request-websocket.ts @@ -22,6 +22,10 @@ export type RemoteRuntimeWebSocketCallbacks = { onClose: (ws: WebSocket, code: number, reason: Buffer) => void onError: (ws: WebSocket, error: RemoteRuntimeClientError) => void onTextFrame: (ws: WebSocket, frame: string) => void + // Why: protocol-level pongs (and server heartbeat pings) are the liveness + // signal for detecting half-open tunnels that never deliver `close` (#7718). + onPong?: (ws: WebSocket) => void + onPing?: (ws: WebSocket) => void } export function openRemoteRuntimeWebSocket( @@ -64,6 +68,8 @@ export function openRemoteRuntimeWebSocket( } callbacks.onTextFrame(ws, data.toString()) } + const onPong = (): void => callbacks.onPong?.(ws) + const onPing = (): void => callbacks.onPing?.(ws) const cleanup = (): void => { if (cleanedUp) { return @@ -73,6 +79,8 @@ export function openRemoteRuntimeWebSocket( ws.off('error', onError) ws.off('close', onClose) ws.off('message', onMessage) + ws.off('pong', onPong) + ws.off('ping', onPing) // Why: a manually closed ws can still emit a late transport error; keep // that from becoming an unhandled EventEmitter error after detaching Orca. if (ws.readyState !== WebSocket.CLOSED) { @@ -84,6 +92,8 @@ export function openRemoteRuntimeWebSocket( ws.on('error', onError) ws.on('close', onClose) ws.on('message', onMessage) + ws.on('pong', onPong) + ws.on('ping', onPing) return { ok: true, socket: { ws, sharedKey, cleanup } } } diff --git a/src/shared/remote-runtime-shared-control-connection.test.ts b/src/shared/remote-runtime-shared-control-connection.test.ts index e807a519b..250ec27bf 100644 --- a/src/shared/remote-runtime-shared-control-connection.test.ts +++ b/src/shared/remote-runtime-shared-control-connection.test.ts @@ -13,6 +13,7 @@ import { import { encodePairingOffer, parsePairingCode, type PairingOffer } from './pairing' import { RemoteRuntimeSharedControlConnection } from './remote-runtime-shared-control-connection' import * as sharedControlProtocol from './remote-runtime-shared-control-protocol' +import { isRuntimeSubscriptionReplayResponse } from './runtime-subscription-replay' const TEST_PROJECT_PATH = path.join('tmp', 'project') @@ -406,6 +407,83 @@ describe('RemoteRuntimeSharedControlConnection', () => { connection.close() }) + it('detects a half-open socket via client liveness, reconnects, and tags the replayed response', async () => { + // Why: the server keeps the TCP connection open but stops answering — + // no close frame, no pongs (autoPong disabled), no responses. This is the + // half-open devtunnel scenario from #7718: edge-triggered reconnect never + // fires, so client liveness must terminate the socket itself. + const server = await createServer({ disableAutoPong: true }) + const connection = new RemoteRuntimeSharedControlConnection(server.pairing, { + liveness: { pingIntervalMs: 50, livenessTimeoutMs: 200 } + }) + const onResponse = vi.fn() + const onClose = vi.fn() + + await connection.subscribe('runtime.clientEvents.subscribe', null, 1000, { + onResponse, + onError: vi.fn(), + onClose + }) + await vi.waitFor(() => expect(onResponse).toHaveBeenCalled()) + expect(isRuntimeSubscriptionReplayResponse(onResponse.mock.calls[0]?.[0])).toBe(false) + + // Liveness terminates the silent socket and the reconnect path replays + // the subscription on a fresh connection. + await vi.waitFor(() => expect(server.connectionCount()).toBeGreaterThanOrEqual(2), { + timeout: 5000 + }) + await vi.waitFor( + () => + expect( + server.requests.filter((request) => request.method === 'runtime.clientEvents.subscribe') + .length + ).toBeGreaterThanOrEqual(2), + { timeout: 5000 } + ) + // The first response after the reconnect replay carries the replay tag so + // snapshot freshness gates can accept the re-emitted snapshot. + await vi.waitFor( + () => + expect( + onResponse.mock.calls.some(([response]) => isRuntimeSubscriptionReplayResponse(response)) + ).toBe(true), + { timeout: 5000 } + ) + expect(onClose).not.toHaveBeenCalled() + + connection.close() + }) + + it('tears down the socket when a request times out and reconnects active subscriptions', async () => { + const server = await createServer({ silentMethods: ['worktree.hang'] }) + const connection = new RemoteRuntimeSharedControlConnection(server.pairing) + const onResponse = vi.fn() + const onClose = vi.fn() + + await connection.subscribe('runtime.clientEvents.subscribe', null, 1000, { + onResponse, + onError: vi.fn(), + onClose + }) + await vi.waitFor(() => expect(onResponse).toHaveBeenCalled()) + + // Why: mirrors RemoteRuntimeRequestConnection — a request the server never + // answered marks the socket as suspect and must not leave it 'ready'. + await expect(connection.request('worktree.hang', undefined, 50)).rejects.toThrow('Timed out') + + await vi.waitFor(() => expect(server.connectionCount()).toBe(2), { timeout: 5000 }) + await vi.waitFor( + () => + expect( + server.requests.filter((request) => request.method === 'runtime.clientEvents.subscribe') + ).toHaveLength(2), + { timeout: 5000 } + ) + expect(onClose).not.toHaveBeenCalled() + + connection.close() + }) + it('rejects pending requests and records close diagnostics when the socket closes', async () => { const server = await createServer({ closeBeforeResponse: true }) const connection = new RemoteRuntimeSharedControlConnection(server.pairing) @@ -434,6 +512,10 @@ async function createServer( closeAfterFirstStreamingResponse?: boolean closeBeforeResponse?: boolean suppressReadyFrame?: boolean + // Why: half-open simulation — the socket stays open but never answers + // protocol pings, like a wedged tunnel that swallows frames silently. + disableAutoPong?: boolean + silentMethods?: string[] } = {} ): Promise { const serverKeyPair = generateKeyPair() @@ -441,7 +523,7 @@ async function createServer( const delayedResponses: (() => void)[] = [] let connectionCount = 0 let closedAfterFirstStreamingResponse = false - const wss = new WebSocketServer({ port: 0 }) + const wss = new WebSocketServer({ port: 0, autoPong: options.disableAutoPong !== true }) servers.push(wss) wss.on('connection', (ws) => { @@ -531,10 +613,14 @@ function handleRequest( sendUnknownResponseBeforeResponse?: boolean closeAfterStreamingResponse?: () => boolean closeBeforeResponse?: boolean + silentMethods?: string[] }, delayedResponses: (() => void)[] ): void { requests.push(request) + if (options.silentMethods?.includes(request.method)) { + return + } if (options.closeBeforeResponse) { ws.close(4001, 'test close') return diff --git a/src/shared/remote-runtime-shared-control-connection.ts b/src/shared/remote-runtime-shared-control-connection.ts index 2ea957e9f..585d3478c 100644 --- a/src/shared/remote-runtime-shared-control-connection.ts +++ b/src/shared/remote-runtime-shared-control-connection.ts @@ -12,13 +12,14 @@ import { } from './remote-runtime-shared-control-ready' import { scheduleSharedControlReconnectOrFinish } from './remote-runtime-shared-control-reconnect' import { requestSharedControl } from './remote-runtime-shared-control-requests' -import { scheduleSharedControlStableReset } from './remote-runtime-shared-control-stability' +import { SharedControlReadyStableResetTimer } from './remote-runtime-shared-control-stability' import * as sharedControlState from './remote-runtime-shared-control-state' import { sendSharedControlRequest, sendSharedControlSubscription } from './remote-runtime-shared-control-send' import { closeSharedControlSocket } from './remote-runtime-shared-control-socket-close' +import type { RemoteRuntimeSocketLivenessOptions } from './remote-runtime-socket-liveness' import * as sharedControlSubscriptions from './remote-runtime-shared-control-subscriptions' import { startSharedControlSubscription } from './remote-runtime-shared-control-subscription-start' import type { @@ -37,7 +38,7 @@ export class RemoteRuntimeSharedControlConnection { private sharedKey: Uint8Array | null = null private socketCleanup: (() => void) | null = null private reconnectTimer: ReturnType | null = null - private readyStableTimer: ReturnType | null = null + private readonly readyStableReset: SharedControlReadyStableResetTimer private reconnectAttempt = 0 private intentionallyClosed = false private lastConnectedAt: number | null = null @@ -46,11 +47,20 @@ export class RemoteRuntimeSharedControlConnection { private readonly pendingRequests = new Map>() private readonly subscriptions = new Map>() private readonly readyWaiters: SharedControlReadyWaiter[] = [] + private everReady = false constructor( private readonly pairing: PairingOffer, - private readonly options: { environmentId?: string; reconnectStableResetMs?: number } = {} - ) {} + private readonly options: { + environmentId?: string + reconnectStableResetMs?: number + liveness?: RemoteRuntimeSocketLivenessOptions + } = {} + ) { + this.readyStableReset = new SharedControlReadyStableResetTimer( + options.reconnectStableResetMs ?? 30_000 + ) + } request( method: string, @@ -64,7 +74,10 @@ export class RemoteRuntimeSharedControlConnection { timeoutMs, ensureReady: () => this.ensureReadyWithTimeout(timeoutMs), send: (requestId, requestMethod, requestParams) => - this.sendRequest(requestId, requestMethod, requestParams) + this.sendRequest(requestId, requestMethod, requestParams), + // Why: a timed-out request marks the socket as suspect (#7718) — tear + // it down so reconnect+replay runs instead of keeping a zombie socket. + onTimeout: (error) => this.handleSocketClosed(error) }) } @@ -145,7 +158,11 @@ export class RemoteRuntimeSharedControlConnection { this.lastError = error.message this.handleSocketClosed(error) }, - onTextFrame: (frame) => this.handleTextFrame(frame) + onTextFrame: (frame) => this.handleTextFrame(frame), + liveness: { + options: this.options.liveness, + onDead: (error) => this.handleSocketClosed(error) + } }) if (!opened.ok) { this.handleSocketClosed(opened.error) @@ -205,8 +222,11 @@ export class RemoteRuntimeSharedControlConnection { private replaySubscriptions(): void { sharedControlSubscriptions.replaySharedControlSubscriptions({ subscriptions: this.subscriptions, - send: (subscription) => this.sendSubscription(subscription) + send: (subscription) => this.sendSubscription(subscription), + // Why: only reconnects tag replays; first connects stay on the gated path. + tagReplayedResponses: this.everReady }) + this.everReady = true } private closeSubscription(requestId: string): void { @@ -260,7 +280,7 @@ export class RemoteRuntimeSharedControlConnection { socketCleanup: cleanup, ws, error, - clearReadyStableTimer: () => this.clearReadyStableTimer() + clearReadyStableTimer: () => this.readyStableReset.clear() }) this.ws = null this.sharedKey = null @@ -292,24 +312,12 @@ export class RemoteRuntimeSharedControlConnection { } private scheduleReconnectAttemptReset(): void { - this.clearReadyStableTimer() - this.readyStableTimer = scheduleSharedControlStableReset({ - delayMs: this.options.reconnectStableResetMs ?? 30_000, + this.readyStableReset.schedule({ getState: () => this.state, getSocket: () => this.ws, reset: () => { this.reconnectAttempt = 0 - }, - clearCurrent: () => { - this.readyStableTimer = null } }) } - - private clearReadyStableTimer(): void { - if (this.readyStableTimer) { - clearTimeout(this.readyStableTimer) - this.readyStableTimer = null - } - } } diff --git a/src/shared/remote-runtime-shared-control-open.ts b/src/shared/remote-runtime-shared-control-open.ts index 6381f58dd..ddb3eb0cd 100644 --- a/src/shared/remote-runtime-shared-control-open.ts +++ b/src/shared/remote-runtime-shared-control-open.ts @@ -7,6 +7,10 @@ import { type RemoteRuntimeWebSocket } from './remote-runtime-request-websocket' import { formatSharedControlCloseMessage } from './remote-runtime-shared-control-protocol' +import { + startRemoteRuntimeSocketLiveness, + type RemoteRuntimeSocketLivenessOptions +} from './remote-runtime-socket-liveness' export function openSharedControlSocket( pairing: PairingOffer, @@ -15,9 +19,17 @@ export function openSharedControlSocket( onClose: (close: { code: number; reason: string }, error: RemoteRuntimeClientError) => void onError: (error: RemoteRuntimeClientError) => void onTextFrame: (frame: string) => void + // Why: reconnect is edge-triggered on `close`, but a half-open tunnel + // never delivers one. Liveness pings and declares the socket dead when + // the server goes silent, so the close/reconnect path can run (#7718). + liveness?: { + options?: RemoteRuntimeSocketLivenessOptions + onDead: (error: RemoteRuntimeClientError) => void + } } ): { ok: true; socket: RemoteRuntimeWebSocket } | { ok: false; error: RemoteRuntimeClientError } { - return openRemoteRuntimeWebSocket(pairing, { + let noteActivity: () => void = () => {} + const opened = openRemoteRuntimeWebSocket(pairing, { onClose: (ws, code, reason) => { if (callbacks.getCurrentSocket() === ws) { callbacks.onClose( @@ -33,8 +45,62 @@ export function openSharedControlSocket( }, onTextFrame: (ws, frame) => { if (callbacks.getCurrentSocket() === ws) { + noteActivity() callbacks.onTextFrame(frame) } + }, + onPong: (ws) => { + if (callbacks.getCurrentSocket() === ws) { + noteActivity() + } + }, + onPing: (ws) => { + if (callbacks.getCurrentSocket() === ws) { + noteActivity() + } } }) + if (!opened.ok || !callbacks.liveness) { + return opened + } + + const { ws, sharedKey, cleanup } = opened.socket + const liveness = callbacks.liveness + const monitor = startRemoteRuntimeSocketLiveness({ + ping: () => { + if (ws.readyState === 1) { + ws.ping() + } + }, + onDead: () => { + if (callbacks.getCurrentSocket() !== ws) { + return + } + try { + // Why: close() on a half-open socket can hang for the OS TCP timeout. + ws.terminate() + } catch { + // Best-effort terminate; the dead callback resets connection state. + } + liveness.onDead( + remoteRuntimeUnavailableError( + 'Remote Orca runtime stopped responding; resetting the control connection.' + ) + ) + }, + options: liveness.options + }) + noteActivity = monitor.noteActivity + + return { + ok: true, + socket: { + ws, + sharedKey, + cleanup: () => { + monitor.stop() + cleanup() + } + } + } } diff --git a/src/shared/remote-runtime-shared-control-requests.ts b/src/shared/remote-runtime-shared-control-requests.ts index bbd8900b9..5f8d0ca2b 100644 --- a/src/shared/remote-runtime-shared-control-requests.ts +++ b/src/shared/remote-runtime-shared-control-requests.ts @@ -1,5 +1,9 @@ import { randomUUID } from 'node:crypto' -import { remoteRuntimeTimeoutError } from './remote-runtime-request-frames' +import type { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { + remoteRuntimeTimeoutError, + remoteRuntimeUnavailableError +} from './remote-runtime-request-frames' import type { RuntimeRpcResponse } from './runtime-rpc-envelope' import { toRemoteRuntimeClientError } from './remote-runtime-shared-control-protocol' import { rejectSharedControlPendingRequest } from './remote-runtime-shared-control-state' @@ -12,6 +16,7 @@ export function requestSharedControl(args: { timeoutMs: number ensureReady: () => Promise send: (requestId: string, method: string, params: unknown) => void + onTimeout?: (error: RemoteRuntimeClientError) => void }): Promise> { const requestId = randomUUID() return new Promise>((resolve, reject) => { @@ -22,6 +27,15 @@ export function requestSharedControl(args: { } args.pendingRequests.delete(requestId) pending.reject(remoteRuntimeTimeoutError()) + // Why: a request the server never answered means the socket is suspect + // (half-open tunnels swallow frames silently); mirror + // RemoteRuntimeRequestConnection and hand the connection a teardown + // error so reconnect+replay runs instead of keeping a zombie socket. + args.onTimeout?.( + remoteRuntimeUnavailableError( + 'Remote Orca runtime did not answer in time; resetting the control connection.' + ) + ) }, args.timeoutMs) args.pendingRequests.set(requestId, { method: args.method, diff --git a/src/shared/remote-runtime-shared-control-stability.ts b/src/shared/remote-runtime-shared-control-stability.ts index 9e1024e69..867d5a654 100644 --- a/src/shared/remote-runtime-shared-control-stability.ts +++ b/src/shared/remote-runtime-shared-control-stability.ts @@ -21,3 +21,35 @@ export function scheduleSharedControlStableReset(args: { } return timer } + +// Why: owns the ready-stable timer's lifecycle so the connection only wires +// state accessors; scheduling always replaces any earlier pending timer. +export class SharedControlReadyStableResetTimer { + private timer: ReturnType | null = null + + constructor(private readonly delayMs: number) {} + + schedule(args: { + getState: () => SharedControlConnectionState + getSocket: () => WebSocket | null + reset: () => void + }): void { + this.clear() + this.timer = scheduleSharedControlStableReset({ + delayMs: this.delayMs, + getState: args.getState, + getSocket: args.getSocket, + reset: args.reset, + clearCurrent: () => { + this.timer = null + } + }) + } + + clear(): void { + if (this.timer) { + clearTimeout(this.timer) + this.timer = null + } + } +} diff --git a/src/shared/remote-runtime-shared-control-state.ts b/src/shared/remote-runtime-shared-control-state.ts index 9c22198f7..72f139a49 100644 --- a/src/shared/remote-runtime-shared-control-state.ts +++ b/src/shared/remote-runtime-shared-control-state.ts @@ -9,6 +9,7 @@ import type { SharedControlReadyWaiter } from './remote-runtime-shared-control-types' import { getSubscriptionId, isEndResult } from './remote-runtime-shared-control-protocol' +import { tagRuntimeSubscriptionReplayResponse } from './runtime-subscription-replay' export function buildSharedControlDiagnostics(args: { state: SharedControlConnectionState @@ -149,7 +150,14 @@ export function handleSharedControlSubscriptionResponse( subscription.remoteSubscriptionId = subscriptionId } } - subscription.callbacks.onResponse(response) + let delivered = response + if (subscription.pendingReplayTag) { + subscription.pendingReplayTag = false + if (response.ok) { + delivered = tagRuntimeSubscriptionReplayResponse(response) + } + } + subscription.callbacks.onResponse(delivered) if (response.ok && isEndResult(response.result)) { finishSharedControlSubscription(subscriptions, subscription, false) } diff --git a/src/shared/remote-runtime-shared-control-subscriptions.ts b/src/shared/remote-runtime-shared-control-subscriptions.ts index 466d11354..d4122eac9 100644 --- a/src/shared/remote-runtime-shared-control-subscriptions.ts +++ b/src/shared/remote-runtime-shared-control-subscriptions.ts @@ -90,6 +90,9 @@ export function sendSharedControlCleanupRequest(args: { export function replaySharedControlSubscriptions(args: { subscriptions: Map> send: (subscription: SharedControlLogicalSubscription) => void + // Why: true only for a reconnect of a previously-ready connection; first + // connects deliver their initial snapshot through the normal gated path. + tagReplayedResponses?: boolean }): void { for (const subscription of args.subscriptions.values()) { if (subscription.closeAfterReady) { @@ -97,6 +100,9 @@ export function replaySharedControlSubscriptions(args: { } subscription.sent = false subscription.remoteSubscriptionId = null + if (args.tagReplayedResponses) { + subscription.pendingReplayTag = true + } args.send(subscription) } } diff --git a/src/shared/remote-runtime-shared-control-types.ts b/src/shared/remote-runtime-shared-control-types.ts index 9f784faa8..4eb671ea3 100644 --- a/src/shared/remote-runtime-shared-control-types.ts +++ b/src/shared/remote-runtime-shared-control-types.ts @@ -30,6 +30,10 @@ export type SharedControlLogicalSubscription = { closed: boolean closeAfterReady: boolean remoteSubscriptionId: string | null + // Why: set while awaiting the first response after a reconnect replay; that + // response is the authoritative re-emitted snapshot and gets tagged so + // monotonic freshness gates don't drop it (#7718). + pendingReplayTag?: boolean } export type SharedControlReadyWaiter = { diff --git a/src/shared/remote-runtime-socket-liveness.ts b/src/shared/remote-runtime-socket-liveness.ts new file mode 100644 index 000000000..2903a72c7 --- /dev/null +++ b/src/shared/remote-runtime-socket-liveness.ts @@ -0,0 +1,75 @@ +// Why: a half-open tunnel (devtunnel/NAT drop) never delivers a ws `close`, +// so edge-triggered reconnect logic on the client side never fires while the +// server has long since reaped its end (#7718/#7489). This monitor gives +// client sockets a level-based liveness check: ping on a cadence and declare +// the socket dead when no inbound traffic (frames, pings, or pongs) arrives +// within the window, so the existing close/reconnect path can run. + +// Why: pings ride the RFC 6455 control-frame layer, which every supported +// server (and the `ws` package it embeds) answers automatically — this stays +// backward compatible with old servers that predate client-side liveness. +export const REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS = 10_000 +// Why: just under two server heartbeat periods (15s), so a dead link is +// detected on a similar horizon to the server's own ping/terminate reaper. +export const REMOTE_RUNTIME_SOCKET_LIVENESS_TIMEOUT_MS = 25_000 + +export type RemoteRuntimeSocketLivenessOptions = { + pingIntervalMs?: number + livenessTimeoutMs?: number +} + +export type RemoteRuntimeSocketLivenessMonitor = { + noteActivity: () => void + stop: () => void +} + +export function startRemoteRuntimeSocketLiveness(args: { + ping: () => void + onDead: () => void + options?: RemoteRuntimeSocketLivenessOptions + now?: () => number +}): RemoteRuntimeSocketLivenessMonitor { + const now = args.now ?? Date.now + const pingIntervalMs = args.options?.pingIntervalMs ?? REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS + const livenessTimeoutMs = + args.options?.livenessTimeoutMs ?? REMOTE_RUNTIME_SOCKET_LIVENESS_TIMEOUT_MS + let lastActivityAt = now() + let stopped = false + + const timer = setInterval(() => { + if (stopped) { + return + } + if (now() - lastActivityAt > livenessTimeoutMs) { + stop() + args.onDead() + return + } + try { + args.ping() + } catch { + // Why: ping() can throw while a socket is mid-teardown; the liveness + // window (or the close handler) settles the socket's fate either way. + } + }, pingIntervalMs) + // Why: mobile typechecks shared code with DOM timer types where unref is absent. + const unrefable = timer as unknown as { unref?: () => void } + if (typeof unrefable.unref === 'function') { + unrefable.unref() + } + + function stop(): void { + if (stopped) { + return + } + stopped = true + clearInterval(timer) + } + + return { + noteActivity: () => { + lastActivityAt = now() + }, + stop + } +} diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index f73c4010f..2ebc69005 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -4,10 +4,15 @@ import type { WorktreeSetupLaunch, WorktreeStartupLaunch } from './types' +import type { SshConnectionState } from './ssh-types' export type RuntimeClientEvent = | { type: 'reposChanged' } | { type: 'worktreesChanged'; repoId: string } + // Why: SSH connections live on the runtime host; paired clients have no IPC + // channel for ssh:state-changed, so without this event their reconnect + // overlays never learn the host connected (STA-1468). + | { type: 'sshStateChanged'; targetId: string; state: SshConnectionState } | { type: 'linearLinkedIssueUpdated' worktreeId: string diff --git a/src/shared/runtime-subscription-replay.ts b/src/shared/runtime-subscription-replay.ts new file mode 100644 index 000000000..b290f1f2c --- /dev/null +++ b/src/shared/runtime-subscription-replay.ts @@ -0,0 +1,25 @@ +// Why: after a shared-control reconnect, the client replays its logical +// subscriptions and the server re-emits each stream's current snapshot. When +// the host did not restart, that snapshot carries the same publicationEpoch/ +// snapshotVersion the client already applied, so monotonic freshness gates +// (e.g. shouldApplyWebSessionTabsSnapshot) would silently drop it and leave +// mirrors frozen (#7718). The connection tags the first response delivered +// after a replay so consumers can treat it as authoritative. The tag is added +// client-side after wire parsing — nothing changes on the protocol, so old +// servers are unaffected. + +const RUNTIME_SUBSCRIPTION_REPLAY_FLAG = '_replayedAfterReconnect' + +export function tagRuntimeSubscriptionReplayResponse( + response: TResponse +): TResponse { + return { ...response, [RUNTIME_SUBSCRIPTION_REPLAY_FLAG]: true } +} + +export function isRuntimeSubscriptionReplayResponse(response: unknown): boolean { + return ( + typeof response === 'object' && + response !== null && + (response as Record)[RUNTIME_SUBSCRIPTION_REPLAY_FLAG] === true + ) +} diff --git a/src/shared/ssh-types.ts b/src/shared/ssh-types.ts index a6b4fa55e..8627f485b 100644 --- a/src/shared/ssh-types.ts +++ b/src/shared/ssh-types.ts @@ -51,6 +51,23 @@ export type SshTarget = { systemSshConnectionReuse?: boolean } +/** Identity of a removed SSH target, recorded so that re-adding the same host + * can re-point orphaned repos/worktrees from the old (deleted) target id to + * the new one. Repos store only the target id, so without this record the old + * workspaces are stranded on a dead id when the target is removed. */ +export type RemovedSshTargetTombstone = { + /** The id the removed target had — what orphaned repos/worktrees still point at. */ + oldTargetId: string + /** ssh-config alias, if any — the most stable re-adoption key. */ + configHost?: string + host: string + port: number + username: string + label: string + /** ms epoch when the target was removed, for pruning old tombstones. */ + removedAt: number +} + export type SavedPortForward = { localPort: number remoteHost: string diff --git a/src/shared/telemetry-events.ts b/src/shared/telemetry-events.ts index 5df0c89d8..cb4169cb1 100644 --- a/src/shared/telemetry-events.ts +++ b/src/shared/telemetry-events.ts @@ -1364,6 +1364,25 @@ const terminalPaneSplitSchema = z }) .strict() +// Why: measures the changed-on-disk conflict flow (issue #7265) — how often +// conflicts surface per transport (false-banner detection on ssh/runtime +// echoes) and which resolution users pick. Deliberately path-free. +const editorExternalChangeConflictShownSchema = z + .object({ + surface: z.enum(['edit', 'unstaged-diff']), + transport: z.enum(['local', 'ssh', 'runtime']), + origin: z.enum(['live', 'restore']) + }) + .strict() + +const editorExternalChangeConflictActionSchema = z + .object({ + action: z.enum(['reload', 'keep', 'compare', 'undo_reload', 'save_overwrite']), + surface: z.enum(['edit', 'unstaged-diff']), + transport: z.enum(['local', 'ssh', 'runtime']) + }) + .strict() + // ── Event registry: the one record the validator consumes ─────────────── // // The validator does `eventSchemas[name].safeParse(props)`. `EventMap` is @@ -1451,6 +1470,9 @@ export const eventSchemas = { setup_guide_step_completed: setupGuideStepCompletedSchema, terminal_pane_split: terminalPaneSplitSchema, + editor_external_change_conflict_shown: editorExternalChangeConflictShownSchema, + editor_external_change_conflict_action: editorExternalChangeConflictActionSchema, + smart_sort_class_distribution: smartSortClassDistributionSchema, smart_sort_class_1_promotion: smartSortClass1PromotionSchema, smart_to_recent_switch: smartToRecentSwitchSchema diff --git a/src/shared/terminal-partial-escape-tail.test.ts b/src/shared/terminal-partial-escape-tail.test.ts new file mode 100644 index 000000000..e0ef2095d --- /dev/null +++ b/src/shared/terminal-partial-escape-tail.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest' +import { + advancePartialEscapeTail, + extractPartialEscapeTail, + MAX_PARTIAL_ESCAPE_TAIL_LENGTH +} from './terminal-partial-escape-tail' + +describe('extractPartialEscapeTail', () => { + it('returns empty for parser-clean streams', () => { + expect(extractPartialEscapeTail('')).toBe('') + expect(extractPartialEscapeTail('plain text no escapes')).toBe('') + expect(extractPartialEscapeTail('\x1b[38;5;196mred\x1b[0m done')).toBe('') + expect(extractPartialEscapeTail('\x1b[2J\x1b[H')).toBe('') + }) + + it('returns the dangling CSI when a chunk ends mid-sequence', () => { + expect(extractPartialEscapeTail('hello\x1b[3')).toBe('\x1b[3') + expect(extractPartialEscapeTail('a\x1b[38;5;')).toBe('\x1b[38;5;') + expect(extractPartialEscapeTail('\x1b')).toBe('\x1b') + expect(extractPartialEscapeTail('\x1b[')).toBe('\x1b[') + }) + + it('returns the dangling OSC (unterminated) sequence', () => { + // OSC 0 title with no BEL/ST terminator yet. + expect(extractPartialEscapeTail('\x1b]0;my-title')).toBe('\x1b]0;my-title') + // Terminated OSC is clean. + expect(extractPartialEscapeTail('\x1b]0;title\x07after')).toBe('') + expect(extractPartialEscapeTail('\x1b]0;title\x1b\\after')).toBe('') + }) + + it('treats a fresh ESC as aborting a pending CSI', () => { + // The second ESC starts a new (complete) sequence. + expect(extractPartialEscapeTail('\x1b[3\x1b[0m')).toBe('') + // ...and a new dangling one. + expect(extractPartialEscapeTail('\x1b[3\x1b[')).toBe('\x1b[') + }) + + it('treats CAN/SUB as aborting an in-progress escape back to ground', () => { + // CAN (0x18) / SUB (0x1a) abort the sequence in xterm's VT500 parser. + // esc state: + expect(extractPartialEscapeTail('\x1b\x18')).toBe('') // ESC CAN + expect(extractPartialEscapeTail('\x1b\x1a')).toBe('') // ESC SUB + // escIntermediate state (ESC then an intermediate byte, then CAN): + expect(extractPartialEscapeTail('\x1b \x18')).toBe('') // ESC SP CAN + expect(extractPartialEscapeTail('\x1b#\x1a')).toBe('') // ESC # SUB + // csi/osc/string already aborted — keep them green: + expect(extractPartialEscapeTail('\x1b[38;\x18')).toBe('') // CSI ... CAN + expect(extractPartialEscapeTail('\x1b]0;title\x18')).toBe('') // OSC ... CAN + // A CAN that aborts, followed by a fresh dangling sequence, tracks the new one: + expect(extractPartialEscapeTail('\x1b\x18\x1b[3')).toBe('\x1b[3') + }) + + it('is fold-safe across chunk boundaries', () => { + // extract(a + b) === extract(extract(a) + b) — the invariant ingest relies on. + const cases: [string, string][] = [ + ['first\x1b[3', '8;5;196mred'], + ['\x1b', '[0m'], + ['\x1b]0;ti', 'tle\x07'], + ['clean', '\x1b[1'], + // Fold-safety must hold across the CAN abort too. + ['\x1b', '\x18after'], + ['\x1b ', '\x18after'] + ] + for (const [a, b] of cases) { + expect(extractPartialEscapeTail(extractPartialEscapeTail(a) + b)).toBe( + extractPartialEscapeTail(a + b) + ) + } + }) +}) + +describe('advancePartialEscapeTail', () => { + it('accumulates a split sequence across chunks', () => { + let tail = '' + tail = advancePartialEscapeTail(tail, 'ls\r\n\x1b[3') + expect(tail).toBe('\x1b[3') + tail = advancePartialEscapeTail(tail, '8;5;196m') + expect(tail).toBe('') // sequence completed + }) + + it('abandons tracking (returns empty) past the cap', () => { + // An unterminated OSC longer than the cap degrades to pre-fix behavior. + const huge = `\x1b]0;${'x'.repeat(MAX_PARTIAL_ESCAPE_TAIL_LENGTH + 10)}` + expect(advancePartialEscapeTail('', huge)).toBe('') + }) +}) diff --git a/src/shared/terminal-partial-escape-tail.ts b/src/shared/terminal-partial-escape-tail.ts index ba7efb8e8..1ee606e60 100644 --- a/src/shared/terminal-partial-escape-tail.ts +++ b/src/shared/terminal-partial-escape-tail.ts @@ -79,6 +79,14 @@ export function extractPartialEscapeTail(stream: string): string { state = 'esc' continue } + // CAN/SUB abort an in-progress escape sequence back to ground in every + // non-string state (xterm's VT500 parser). The csi/osc/string cases handle + // this inline below; esc/escIntermediate must too, or `ESC CAN` and + // `ESC CAN` leave a bogus tail instead of dropping to ground. + if ((code === CAN || code === SUB) && (state === 'esc' || state === 'escIntermediate')) { + state = 'ground' + continue + } switch (state) { case 'esc': state = stateAfterEscByte(code) @@ -87,7 +95,7 @@ export function extractPartialEscapeTail(stream: string): string { if (code >= 0x30 && code <= 0x7e) { state = 'ground' } - // 0x20–0x2f stays; C0 executes and stays. + // 0x20–0x2f stays; other C0 executes and stays (CAN/SUB handled above). break case 'csi': if (code === CAN || code === SUB) { diff --git a/src/shared/terminal-query-reply.test.ts b/src/shared/terminal-query-reply.test.ts new file mode 100644 index 000000000..ee26abf16 --- /dev/null +++ b/src/shared/terminal-query-reply.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest' +import { isTerminalQueryReply } from './terminal-query-reply' + +describe('isTerminalQueryReply', () => { + it('matches synthetic query replies that must be sent immediately', () => { + // CPR cursor position report (answer to CSI 6n) — the #7329 culprit. + expect(isTerminalQueryReply('\x1b[3;1R')).toBe(true) + expect(isTerminalQueryReply('\x1b[22;1R')).toBe(true) + // DSR device status. + expect(isTerminalQueryReply('\x1b[0n')).toBe(true) + // DA1/DA2/DA3 device attributes. + expect(isTerminalQueryReply('\x1b[?1;2c')).toBe(true) + expect(isTerminalQueryReply('\x1b[?61;4c')).toBe(true) + expect(isTerminalQueryReply('\x1b[>0;276;0c')).toBe(true) + // Window/cell pixel-size reports. + expect(isTerminalQueryReply('\x1b[6;16;8t')).toBe(true) + expect(isTerminalQueryReply('\x1b[4;384;640t')).toBe(true) + // DECRPM mode report — private (with ?) and ANSI (without ?). + expect(isTerminalQueryReply('\x1b[?2026;2$y')).toBe(true) + expect(isTerminalQueryReply('\x1b[4;1$y')).toBe(true) + // OSC 10/11 color responses (the #7329 culprit) — BEL and ST terminated. + expect(isTerminalQueryReply('\x1b]11;rgb:2828/2c2c/3434\x1b\\')).toBe(true) + expect(isTerminalQueryReply('\x1b]10;rgb:c0c0/c0c0/c0c0\x07')).toBe(true) + // DECXCPR extended cursor position report (answer to CSI ? 6n). + expect(isTerminalQueryReply('\x1b[?12;5R')).toBe(true) + // Text-area size in characters (answer to CSI 18t). + expect(isTerminalQueryReply('\x1b[8;24;80t')).toBe(true) + // Kitty keyboard flags report (answer to CSI ? u) — crossterm probes this + // at startup, so a debounced reply corrupts the same way CPR did. + expect(isTerminalQueryReply('\x1b[?0u')).toBe(true) + expect(isTerminalQueryReply('\x1b[?31u')).toBe(true) + // DCS DECRQSS reports (vim queries cursor style via DCS $ q) + XTVERSION. + expect(isTerminalQueryReply('\x1bP1$r2 q\x1b\\')).toBe(true) + expect(isTerminalQueryReply('\x1bP1$r0m\x1b\\')).toBe(true) + expect(isTerminalQueryReply('\x1bP0$r\x1b\\')).toBe(true) + expect(isTerminalQueryReply('\x1bP>|xterm.js(5.6.0)\x1b\\')).toBe(true) + }) + + it('documents the accepted modified-F3/CPR collision', () => { + // xterm.js encodes Shift+F3 as CSI 1;2R — byte-identical to a CPR report. + // Classified as a reply on purpose: order is still preserved (the immediate + // path flushes pending input first); see the comment in terminal-query-reply.ts. + expect(isTerminalQueryReply('\x1b[1;2R')).toBe(true) + }) + + it('does NOT match ordinary typed input or navigation sequences', () => { + // Plain text. + expect(isTerminalQueryReply('yes')).toBe(false) + expect(isTerminalQueryReply('y')).toBe(false) + expect(isTerminalQueryReply('\r')).toBe(false) + expect(isTerminalQueryReply('\x03')).toBe(false) // Ctrl-C + // Arrow keys / navigation — must stay batched (coalesced auto-repeat). + expect(isTerminalQueryReply('\x1b[A')).toBe(false) + expect(isTerminalQueryReply('\x1b[B')).toBe(false) + expect(isTerminalQueryReply('\x1b[C')).toBe(false) + expect(isTerminalQueryReply('\x1b[D')).toBe(false) + expect(isTerminalQueryReply('\x1b[H')).toBe(false) // Home + expect(isTerminalQueryReply('\x1b[F')).toBe(false) // End + // Function keys (end in ~). + expect(isTerminalQueryReply('\x1b[15~')).toBe(false) + expect(isTerminalQueryReply('\x1b[3~')).toBe(false) // Delete + // Bare Escape key. + expect(isTerminalQueryReply('\x1b')).toBe(false) + // Alt+key (including Alt+Shift+P, whose bytes prefix the DCS grammar). + expect(isTerminalQueryReply('\x1bb')).toBe(false) + expect(isTerminalQueryReply('\x1bP')).toBe(false) + // Kitty-protocol KEYSTROKES (CSI code;mods u, no "?") must stay batched. + expect(isTerminalQueryReply('\x1b[97;5u')).toBe(false) + expect(isTerminalQueryReply('\x1b[13u')).toBe(false) + // Modified F1/F2/F4 (CSI 1; P/Q/S) are keystrokes, not replies. + expect(isTerminalQueryReply('\x1b[1;2P')).toBe(false) + expect(isTerminalQueryReply('\x1b[1;2Q')).toBe(false) + expect(isTerminalQueryReply('\x1b[1;2S')).toBe(false) + // Bracketed paste markers are input framing, not replies. + expect(isTerminalQueryReply('\x1b[200~')).toBe(false) + expect(isTerminalQueryReply('\x1b[201~')).toBe(false) + // Incomplete / non-terminated OSC and DCS must not match. + expect(isTerminalQueryReply('\x1b]11;rgb:2828/2c2c/3434')).toBe(false) + expect(isTerminalQueryReply('\x1bP1$r2 q')).toBe(false) + }) +}) diff --git a/src/shared/terminal-query-reply.ts b/src/shared/terminal-query-reply.ts new file mode 100644 index 000000000..4d009fc0d --- /dev/null +++ b/src/shared/terminal-query-reply.ts @@ -0,0 +1,69 @@ +// Why this module exists: xterm's public onData stream mixes real keystrokes +// with the parser's synthetic replies to terminal queries a program embedded in +// its output (CPR/DSR cursor + device-status reports, DA device attributes, +// DECRPM mode reports, window/cell pixel-size reports, OSC 10/11 color reports, +// kitty keyboard flag reports, DCS-framed DECRQSS/XTVERSION reports). +// A querying program (e.g. starship/orb) reads these replies synchronously in +// raw mode with a short timeout, so on the remote path they must NOT sit behind +// the input debounce — a late reply lands on the shell prompt in cooked mode, +// which echoes it literally and splices it into the next typed line (#7329). +// This classifier lets the transport send replies immediately while keeping +// ordinary typed input (including bursty arrow-key auto-repeat) coalesced. + +const ESC = String.fromCharCode(0x1b) + +// Built via new RegExp from \u-escaped strings so no literal control +// characters appear in the source. // Final bytes of xterm's own query-reply grammars: +// R — CPR / DECXCPR cursor position report (answer to CSI 6n / CSI ? 6n) +// n — DSR device status report (answer to CSI 5n → CSI 0n) +// c — DA1/DA2/DA3 device attributes (answer to CSI c / CSI > c / CSI = c) +// t — window/cell pixel-size + text-area-size reports (CSI 14t/16t/18t) +// y — DECRPM mode report (answer to CSI ? Ps $ p), body ends "$y" +// u — kitty keyboard flags report (answer to CSI ? u), carries "?" +/* oxlint-disable no-control-regex -- grammars match terminal ESC/BEL sequences by definition */ +// Known accepted collision: xterm.js encodes MODIFIED F3 (Shift/Ctrl/Alt+F3) as +// `CSI 1 ; R`, which is indistinguishable from a CPR report (a classic +// VT ambiguity). Such a keystroke is sent immediately instead of debounced — +// byte order is still preserved (the immediate path flushes pending input +// first), it just skips input-intent/activity bookkeeping. Harmless, so we +// keep the reply grammar complete rather than special-casing it. +const CPR_OR_DSR_RE = new RegExp('^\\u001b\\[\\??[0-9;]*[Rn]$') +const DEVICE_ATTRIBUTES_RE = new RegExp('^\\u001b\\[[?>=]?[0-9;]*c$') +// 4/6 = pixel-size reports, 8 = text-area size in characters (answer to CSI 18t). +const WINDOW_SIZE_REPORT_RE = new RegExp('^\\u001b\\[[468];[0-9]+;[0-9]+t$') +// `?` optional: private-mode reports carry it (DECRPM), ANSI-mode reports don't. +const DECRPM_RE = new RegExp('^\\u001b\\[\\??[0-9;]*\\$y$') +// Kitty keyboard protocol flags report: CSI ? flags u. The `?` distinguishes it +// from kitty-protocol *keystrokes* (CSI code;mods u), which must stay batched. +const KITTY_FLAGS_RE = new RegExp('^\\u001b\\[\\?[0-9]+u$') +// OSC color/title responses: ESC ] Ps ; body ST (ST = BEL or ESC backslash). +const OSC_RESPONSE_RE = new RegExp('^\\u001b\\][0-9]+;[^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)$') +// DCS-framed reports xterm emits: DECRQSS "ESC P 1 $ r Pt ST" / "ESC P 0 $ r ST" +// (vim queries cursor style this way) and XTVERSION "ESC P > | text ST". +const DCS_RESPONSE_RE = new RegExp('^\\u001bP(?:[01]\\$r[^\\u001b]*|>\\|[^\\u001b]*)\\u001b\\\\$') +/* oxlint-enable no-control-regex */ + +/** + * True when `data` (from xterm.onData) is a synthetic reply the emulator + * generated in response to a query — not something the user typed. These are + * latency-critical and must bypass input coalescing on the remote transport. + * + * Conservative by design: matches only complete, well-formed reply grammars so + * ordinary keystrokes and navigation sequences (arrows CSI A/B/C/D, Home/End, + * function keys ending in ~, kitty CSI-u keystrokes) are never misclassified + * as replies — with the single documented modified-F3/CPR collision above. + */ +export function isTerminalQueryReply(data: string): boolean { + if (data.length < 3 || data[0] !== ESC) { + return false + } + return ( + CPR_OR_DSR_RE.test(data) || + DEVICE_ATTRIBUTES_RE.test(data) || + WINDOW_SIZE_REPORT_RE.test(data) || + DECRPM_RE.test(data) || + KITTY_FLAGS_RE.test(data) || + OSC_RESPONSE_RE.test(data) || + DCS_RESPONSE_RE.test(data) + ) +} diff --git a/src/shared/terminal-startup-cwd.test.ts b/src/shared/terminal-startup-cwd.test.ts index f87ef7d51..2b1fe0b2f 100644 --- a/src/shared/terminal-startup-cwd.test.ts +++ b/src/shared/terminal-startup-cwd.test.ts @@ -17,70 +17,53 @@ describe('resolveTerminalStartupCwd', () => { expect(resolveTerminalStartupCwd('/repo/app', 'packages/web')).toBe('/repo/app/packages/web') }) - it('rejects sibling paths outside the worktree', () => { - expect(() => resolveTerminalStartupCwd('/repo/app', '/repo/app-other')).toThrow( - 'Terminal cwd must be inside the selected worktree.' - ) + it('allows absolute cwds outside the worktree (#7685)', () => { + // Why: opening/splitting a terminal outside the worktree (e.g. after + // `cd ..`) is allowed; the cwd is resolved, not constrained. + expect(resolveTerminalStartupCwd('/repo/app', '/repo/app-other')).toBe('/repo/app-other') }) - it('rejects parent traversal outside the worktree', () => { - expect(() => resolveTerminalStartupCwd('/repo/app', '../other')).toThrow( - 'Terminal cwd must be inside the selected worktree.' - ) + it('resolves parent traversal to a path outside the worktree (#7685)', () => { + expect(resolveTerminalStartupCwd('/repo/app', '../other')).toBe('/repo/other') }) it('trims whitespace-padded requested cwds before resolving', () => { expect(resolveTerminalStartupCwd('/repo/app', ' packages/web ')).toBe('/repo/app/packages/web') }) - it('falls back to the default cwd when a symlink escapes the worktree', () => { - const canonicalize = (path: string): string | null => - path === '/repo/app/link' ? '/outside/target' : path - expect( - resolveTerminalStartupCwd('/repo/app', 'link', { canonicalizePath: canonicalize }) - ).toBeUndefined() + it('returns undefined for an empty requested cwd', () => { + expect(resolveTerminalStartupCwd('/repo/app', '')).toBeUndefined() + expect(resolveTerminalStartupCwd('/repo/app', ' ')).toBeUndefined() + expect(resolveTerminalStartupCwd('/repo/app', null)).toBeUndefined() }) - it('accepts cwds under a symlinked worktree root', () => { - const canonicalize = (path: string): string | null => path.replace(/^\/tmp\//, '/private/tmp/') - expect( - resolveTerminalStartupCwd('/tmp/repo', 'packages/web', { canonicalizePath: canonicalize }) - ).toBe('/tmp/repo/packages/web') - }) - - it('skips the symlink re-check when a path cannot be canonicalized', () => { - expect( - resolveTerminalStartupCwd('/repo/app', 'missing', { canonicalizePath: () => null }) - ).toBe('/repo/app/missing') - }) - - it('handles Windows path containment without case drift', () => { + it('normalizes Windows separators and allows out-of-worktree drives', () => { expect(resolveTerminalStartupCwd('C:\\Repo\\App', 'packages\\web')).toBe( 'C:/Repo/App/packages/web' ) - expect(() => resolveTerminalStartupCwd('C:\\Repo\\App', 'C:\\Repo\\AppOther')).toThrow( - 'Terminal cwd must be inside the selected worktree.' + expect(resolveTerminalStartupCwd('C:\\Repo\\App', 'C:\\Repo\\AppOther')).toBe( + 'C:/Repo/AppOther' ) }) - it('validates renderer PTY cwd values against raw worktree IDs', () => { + it('resolves renderer PTY cwd values against raw worktree IDs', () => { expect( resolveTerminalStartupCwdForWorkspace({ workspaceId: 'repo-1::/repo/app', requestedCwd: '/repo/app/packages/web' }) ).toBe('/repo/app/packages/web') - expect(() => + expect( resolveTerminalStartupCwdForWorkspace({ workspaceId: 'repo-1::/repo/app', requestedCwd: '/repo/app-other' }) - ).toThrow('Terminal cwd must be inside the selected worktree.') + ).toBe('/repo/app-other') }) it('passes floating terminal cwds through untouched', () => { // Why: floating terminal cwds are validated against trusted-directory - // grants in main and have no worktree root to contain within. + // grants in main and have no worktree root to resolve against. expect( resolveTerminalStartupCwdForWorkspace({ workspaceId: FLOATING_TERMINAL_WORKTREE_ID, @@ -89,7 +72,7 @@ describe('resolveTerminalStartupCwd', () => { ).toBe('/Volumes/work/notes') }) - it('refuses the requested cwd when no workspace root is resolvable', () => { + it('falls back to the provider default when no workspace root is resolvable', () => { expect( resolveTerminalStartupCwdForWorkspace({ workspaceId: undefined, @@ -104,7 +87,7 @@ describe('resolveTerminalStartupCwd', () => { ).toBeUndefined() }) - it('validates renderer PTY cwd values against folder workspace keys', () => { + it('resolves renderer PTY cwd values against folder workspace keys', () => { expect( resolveTerminalStartupCwdForWorkspace({ workspaceId: folderWorkspaceKey('folder-1'), @@ -112,12 +95,12 @@ describe('resolveTerminalStartupCwd', () => { resolveFolderWorkspacePath: (id) => (id === 'folder-1' ? '/repo/app' : null) }) ).toBe('/repo/app/packages/web') - expect(() => + expect( resolveTerminalStartupCwdForWorkspace({ workspaceId: folderWorkspaceKey('folder-1'), requestedCwd: '../other', resolveFolderWorkspacePath: (id) => (id === 'folder-1' ? '/repo/app' : null) }) - ).toThrow('Terminal cwd must be inside the selected worktree.') + ).toBe('/repo/other') }) }) diff --git a/src/shared/terminal-startup-cwd.ts b/src/shared/terminal-startup-cwd.ts index b71b737fa..ae97ca6dd 100644 --- a/src/shared/terminal-startup-cwd.ts +++ b/src/shared/terminal-startup-cwd.ts @@ -1,60 +1,33 @@ import { FLOATING_TERMINAL_WORKTREE_ID } from './constants' -import { isPathInsideOrEqual, resolveRuntimePath } from './cross-platform-path' +import { resolveRuntimePath } from './cross-platform-path' import { parseWorkspaceKey } from './workspace-scope' import { splitWorktreeIdForFilesystem } from './worktree-id' -export type TerminalStartupCwdOptions = { - // Why: the string containment check can't see symlinks; only local callers - // can canonicalize — SSH worktree paths live on the remote host. - canonicalizePath?: (path: string) => string | null -} - export function resolveTerminalStartupCwd( worktreePath: string, - requestedCwd?: string | null, - options?: TerminalStartupCwdOptions + requestedCwd?: string | null ): string | undefined { const trimmedCwd = requestedCwd?.trim() if (!trimmedCwd) { return undefined } - const resolvedCwd = resolveRuntimePath(worktreePath, trimmedCwd) - if (!isPathInsideOrEqual(worktreePath, resolvedCwd)) { - // Why: remote/session clients can request terminal cwd; never let that - // become a shell outside the selected workspace. - throw new Error('Terminal cwd must be inside the selected worktree.') - } - const canonicalizePath = options?.canonicalizePath - if (canonicalizePath) { - const canonicalWorktreePath = canonicalizePath(worktreePath) - const canonicalCwd = canonicalizePath(resolvedCwd) - if ( - canonicalWorktreePath && - canonicalCwd && - !isPathInsideOrEqual(canonicalWorktreePath, canonicalCwd) - ) { - // Why: a symlink escaping the worktree can be legitimate (e.g. a pnpm - // store link), so fall back to the default cwd instead of failing the - // spawn — but never grant the requested out-of-worktree shell. - return undefined - } - } - return resolvedCwd + // Why: resolve relative requests against the worktree root and normalize + // `..`; the cwd is intentionally not constrained to the worktree, so opening + // or splitting a terminal outside it (e.g. after `cd ..`) is allowed. (#7685) + return resolveRuntimePath(worktreePath, trimmedCwd) } export function resolveTerminalStartupCwdForWorkspace(args: { workspaceId?: string requestedCwd?: string | null resolveFolderWorkspacePath?: (folderWorkspaceId: string) => string | null | undefined - canonicalizePath?: (path: string) => string | null }): string | undefined { if (!args.requestedCwd || args.requestedCwd.trim().length === 0) { return undefined } if (args.workspaceId === FLOATING_TERMINAL_WORKTREE_ID) { - // Why: floating terminals have no worktree root to contain within; their - // cwd was already validated against the trusted-directory grants in - // resolveFloatingTerminalCwd. + // Why: floating terminals have no worktree root; their cwd was already + // resolved against the trusted-directory grants in resolveFloatingTerminalCwd. return args.requestedCwd } const workspacePath = resolveTerminalWorkspacePath( @@ -62,14 +35,11 @@ export function resolveTerminalStartupCwdForWorkspace(args: { args.resolveFolderWorkspacePath ) if (!workspacePath) { - // Why: without a resolvable workspace root we cannot enforce the - // in-worktree containment check, so refuse the requested cwd rather - // than trusting an unvalidated path. + // Why: without a worktree root we can't anchor a relative request, so fall + // back to the provider default rather than guessing a base. return undefined } - return resolveTerminalStartupCwd(workspacePath, args.requestedCwd, { - canonicalizePath: args.canonicalizePath - }) + return resolveTerminalStartupCwd(workspacePath, args.requestedCwd) } function resolveTerminalWorkspacePath( diff --git a/src/shared/terminal-title-agent-type.ts b/src/shared/terminal-title-agent-type.ts index 3671ef929..21c206dff 100644 --- a/src/shared/terminal-title-agent-type.ts +++ b/src/shared/terminal-title-agent-type.ts @@ -1,6 +1,193 @@ -import { getAgentLabel, titleHasAgentName } from './agent-detection' +import { + AGY_AGENT_NAME_RE, + DROID_AGENT_NAME_RE, + HERMES_AGENT_NAME_RE, + titleHasAgentName +} from './agent-name-token-match' +import { + getPiCompatibleSyntheticAgentLabel, + isLegacyPiCompatibleTitle +} from './pi-compatible-synthetic-title' import type { TuiAgent } from './types' +export const CLAUDE_IDLE = '\u2733' // ✳ (eight-spoked asterisk — Claude Code idle prefix) +const CLAUDE_MANAGEMENT_TITLE_RE = + /^\s*(?:"(?:.*[\\/])?claude(?:\.(?:exe|cmd|bat|ps1))?"|'(?:.*[\\/])?claude(?:\.(?:exe|cmd|bat|ps1))?'|(?:.*[\\/])?claude(?:\.(?:exe|cmd|bat|ps1))?)\s+agents\s*$/i + +export const GEMINI_WORKING = '\u2726' // ✦ +export const GEMINI_SILENT_WORKING = '\u23F2' // ⏲ +export const GEMINI_IDLE = '\u25C7' // ◇ +export const GEMINI_PERMISSION = '\u270B' // ✋ + +export function containsBrailleSpinner(title: string): boolean { + for (const char of title) { + const codePoint = char.codePointAt(0) + if (codePoint !== undefined && codePoint >= 0x2800 && codePoint <= 0x28ff) { + return true + } + } + return false +} + +export function isGeminiTerminalTitle(title: string): boolean { + // Why: Gemini OSC glyphs are stronger evidence than any cwd/session text. + if ( + title.includes(GEMINI_PERMISSION) || + title.includes(GEMINI_WORKING) || + title.includes(GEMINI_SILENT_WORKING) || + title.includes(GEMINI_IDLE) + ) { + return true + } + // Why: Pi/OMP titles include cwd/session text; substring matching made + // paths like "gemini-project" masquerade as Gemini CLI. + if (isPiAgentTitle(title)) { + return false + } + return titleHasAgentName(title, 'gemini') +} + +export function isPiTerminalTitle(title: string): boolean { + return isLegacyPiCompatibleTitle(title) && !containsBrailleSpinner(title) +} + +export function isPiAgentTitle(title: string): boolean { + return isLegacyPiCompatibleTitle(title) +} + +/** + * Returns true when the terminal title matches Claude Code's title conventions. + * Used to scope prompt-cache-timer behavior to Claude sessions only — other + * agents have different (or no) caching semantics. + */ +export function isClaudeAgent(title: string): boolean { + if (!title || isClaudeManagementTitle(title)) { + return false + } + const lower = title.toLowerCase() + + // Why: Claude Code titles are prefixed with status indicators (✳, ". ", "* ", + // braille spinners) followed by the task description. The task text can + // legitimately mention other agents, so Claude-specific prefixes must win. + if (title.startsWith(`${CLAUDE_IDLE} `) || title === CLAUDE_IDLE) { + return true + } + // Why: ". " (working) and "* " (idle) are Claude Code title conventions. + // Other supported agents do not use them, and rejecting titles that mention + // another agent in the task text caused false negatives for real Claude tabs. + if (title.startsWith('. ') || title.startsWith('* ')) { + return true + } + if (containsBrailleSpinner(title)) { + // Why: named non-Claude agents can carry braille spinners too; Claude-only + // prompt-cache paths must not fire for those explicit agent titles. + return !lower.includes('cursor') && !lower.includes('openclaude') + } + // Why: permission/action-required Claude titles can omit the usual prefixes. + // Token-match so cwd/worktree titles like "claude-scratch" do not become + // Claude tabs, while task text that merely mentions Claude still stays out. + const trimmedTitle = title.trimStart() + if ( + trimmedTitle.toLowerCase().startsWith('claude') && + titleHasAgentName(trimmedTitle, 'claude') + ) { + return true + } + + return false +} + +export function isClaudeManagementTitle(title: string): boolean { + return CLAUDE_MANAGEMENT_TITLE_RE.test(title) +} + +export function getAgentLabel(title: string): string | null { + if (isClaudeManagementTitle(title)) { + return null + } + // Why: Claude Code title text is often the task title. If that task mentions + // another CLI, the Claude-specific prefix is the identity signal, not the words. + if ( + title.startsWith(`${CLAUDE_IDLE} `) || + title === CLAUDE_IDLE || + title.startsWith('. ') || + title.startsWith('* ') + ) { + return 'Claude Code' + } + if (isGeminiTerminalTitle(title)) { + return 'Gemini CLI' + } + // Why: Pi-compatible synthetic titles can carry braille spinners, which the + // generic agent-title heuristics would otherwise claim first. + const piCompatibleSyntheticAgentLabel = getPiCompatibleSyntheticAgentLabel(title) + if (piCompatibleSyntheticAgentLabel) { + return piCompatibleSyntheticAgentLabel + } + // Why: Pi working titles include a braille spinner prefix, which would be + // mistaken for Claude Code if we checked `isClaudeAgent` first. + if (isPiAgentTitle(title)) { + return 'Pi' + } + // Why: Codex/OpenCode/Aider can also use braille spinner prefixes while + // working. Prefer explicit name matches before Claude's generic spinner + // heuristic so mixed-agent hovercards stay truthful. Token-match (not + // substring) so cwd/worktree titles like "opencode-blinker" don't mint a + // false agent identity. + if (titleHasAgentName(title, 'codex')) { + return 'Codex' + } + if (titleHasAgentName(title, 'openclaude')) { + return 'OpenClaude' + } + if (titleHasAgentName(title, 'copilot')) { + return 'GitHub Copilot' + } + if (titleHasAgentName(title, 'grok')) { + return 'Grok' + } + if (titleHasAgentName(title, 'devin')) { + return 'Devin' + } + if (titleHasAgentName(title, 'antigravity') || AGY_AGENT_NAME_RE.test(title)) { + return 'Antigravity' + } + if (titleHasAgentName(title, 'opencode')) { + return 'OpenCode' + } + if (titleHasAgentName(title, 'mimo')) { + return 'MiMo Code' + } + if (titleHasAgentName(title, 'aider')) { + return 'Aider' + } + // Why: the cursor-agent native title is the literal string "Cursor Agent" + // (verified against the 2026.04.17 release) — Orca synthesizes the same + // label from hook events so the braille-spinner + agent-name path lights + // up working/permission/idle transitions in the renderer. Match before + // `isClaudeAgent` because Claude's generic braille heuristic would + // otherwise claim every "⠋ Cursor Agent" frame as Claude. Token-match so a + // cwd like "~/cursor-rules" can't masquerade as a Cursor agent. + if (titleHasAgentName(title, 'cursor')) { + return 'Cursor' + } + // Why: synthesized "⠋ Droid" working title needs to be matched before Claude's braille heuristic. + // Token matching avoids labeling ordinary Android terminal titles as Droid. + if (DROID_AGENT_NAME_RE.test(title)) { + return 'Droid' + } + // Why: synthesized "⠋ Hermes" working titles need to be matched before + // Claude's generic braille-spinner heuristic. + if (HERMES_AGENT_NAME_RE.test(title)) { + return 'Hermes' + } + if (isClaudeAgent(title)) { + return 'Claude Code' + } + + return null +} + // Maps getAgentLabel()'s product labels to TuiAgent ids — the fallback for // agents whose foreground PROCESS name isn't self-identifying (Claude Code runs // as `node`, but its "✳ Claude Code" title resolves here). Agents whose process @@ -24,16 +211,6 @@ const TITLE_LABEL_TO_AGENT: Partial> = { OMP: 'omp' } -function containsBrailleSpinner(title: string): boolean { - for (const char of title) { - const codePoint = char.codePointAt(0) - if (codePoint !== undefined && codePoint >= 0x2800 && codePoint <= 0x28ff) { - return true - } - } - return false -} - function hasGenericClaudeStatusPrefix(title: string): boolean { return ( containsBrailleSpinner(title) || diff --git a/src/shared/terminal-title-display.ts b/src/shared/terminal-title-display.ts new file mode 100644 index 000000000..a74678e34 --- /dev/null +++ b/src/shared/terminal-title-display.ts @@ -0,0 +1,99 @@ +import { + AGY_AGENT_NAME_RE, + DROID_AGENT_NAME_RE, + HERMES_AGENT_NAME_RE, + titleHasAnyLegacyAgentName +} from './agent-name-token-match' +import { + GEMINI_IDLE, + GEMINI_PERMISSION, + GEMINI_SILENT_WORKING, + GEMINI_WORKING, + isGeminiTerminalTitle, + isPiAgentTitle +} from './terminal-title-agent-type' +import { + detectAgentStatusFromTitle, + STRONG_WORKING_KEYWORDS_RE_GLOBAL +} from './terminal-title-status' + +function containsAgentName(title: string): boolean { + return ( + titleHasAnyLegacyAgentName(title) || + AGY_AGENT_NAME_RE.test(title) || + DROID_AGENT_NAME_RE.test(title) || + HERMES_AGENT_NAME_RE.test(title) + ) +} + +/** + * Strip working-status indicators from a title so that + * `detectAgentStatusFromTitle` will no longer return 'working'. + * Used to clear stale titles when an agent exits without resetting its title. + */ +export function clearWorkingIndicators(title: string): string { + let cleaned = title + + // Gemini working symbols + cleaned = cleaned.replace(GEMINI_WORKING, '') + cleaned = cleaned.replace(GEMINI_SILENT_WORKING, '') + + // Braille spinner characters (U+2800–U+28FF) + // eslint-disable-next-line no-control-regex -- intentional unicode range + cleaned = cleaned.replace(/[\u2800-\u28FF]/g, '') + + // Claude Code ". " working prefix + if (cleaned.startsWith('. ')) { + cleaned = cleaned.slice(2) + } + + // Strip working keywords that detectAgentStatusFromTitle would pick up + // when the title also contains an agent name. + if (containsAgentName(cleaned)) { + cleaned = cleaned.replace(STRONG_WORKING_KEYWORDS_RE_GLOBAL, '') + } + + // Collapse whitespace after removals + cleaned = cleaned.replace(/\s{2,}/g, ' ').trim() + + return cleaned || title +} + +/** + * Normalize high-churn agent titles into stable display labels before storing + * them in app state. Gemini CLI can emit per-keystroke title updates, which + * otherwise causes broad rerenders and visible flashing. + */ +export function normalizeTerminalTitle(title: string): string { + if (!title) { + return title + } + + if (isGeminiTerminalTitle(title)) { + const status = detectAgentStatusFromTitle(title) + if (status === 'permission') { + return `${GEMINI_PERMISSION} Gemini CLI` + } + if (status === 'working') { + return `${GEMINI_WORKING} Gemini CLI` + } + if (status === 'idle') { + return `${GEMINI_IDLE} Gemini CLI` + } + } + + // Why: Pi's titlebar extension animates every 80ms with different braille + // frames. Collapsing those frames into one stable label avoids renderer + // churn while preserving the working/idle transition Orca keys off. + if (isPiAgentTitle(title)) { + const status = detectAgentStatusFromTitle(title) + if (status === 'working') { + return '\u280b Pi' + } + if (status === 'idle') { + return 'Pi' + } + } + + return title +} diff --git a/src/shared/terminal-title-status.ts b/src/shared/terminal-title-status.ts new file mode 100644 index 000000000..5d8cd0a45 --- /dev/null +++ b/src/shared/terminal-title-status.ts @@ -0,0 +1,230 @@ +import { + AGY_AGENT_NAME_RE, + DROID_AGENT_NAME_RE, + HERMES_AGENT_NAME_RE, + titleHasAnyLegacyAgentName +} from './agent-name-token-match' +import { getPiCompatibleSyntheticAgentStatus } from './pi-compatible-synthetic-title' +import { + CLAUDE_IDLE, + containsBrailleSpinner, + GEMINI_IDLE, + GEMINI_PERMISSION, + GEMINI_SILENT_WORKING, + GEMINI_WORKING, + isClaudeManagementTitle, + isPiTerminalTitle +} from './terminal-title-agent-type' + +export type AgentStatus = 'working' | 'permission' | 'idle' + +// Why: idle keywords used inside `detectAgentStatusFromTitle` to map titles +// like "Codex done", "OpenCode ready", "Aider idle" to AgentStatus 'idle'. +// `as const` so consumers receive literal-union types. +const STRONG_IDLE_KEYWORDS = ['ready', 'idle', 'done'] as const + +// Why: working keywords used inside `detectAgentStatusFromTitle` to map +// titles like "Codex working", "Aider thinking", "OpenCode running" to +// AgentStatus 'working'. Shared with `clearWorkingIndicators` so both stay +// in lock-step when stripping working indicators from stale titles. +const STRONG_WORKING_KEYWORDS = ['working', 'thinking', 'running'] as const + +// Why: match STRONG_IDLE_KEYWORDS only when not adjacent to characters that +// would make the "keyword" part of a larger token. Plain `\b` alone is +// insufficient because `-` is a non-word character in JS regex, so `\bready\b` +// still matches inside "is-ready-cap" (a `\b` boundary falls between `-` and +// `r`). +// +// Lookarounds are intentionally ASYMMETRIC: +// - LEFT: reject `[\w./\\-]` so path fragments like `~/codex/ready`, +// Windows `C:\codex\ready`, and `codex.ready` cannot mint a strong idle +// signal by having the agent name sit earlier in the same path and the +// keyword land right after a path separator. Orca is a cross-platform +// Electron app, so Windows path separators must be handled too. +// - RIGHT: reject only `[\w\-]` so legitimate sentence-style titles like +// "Codex done." / "Aider idle." / "OpenCode ready!" still match — path +// separators after the keyword are not a false-positive vector in +// practice and blocking them would regress trailing-punctuation titles. +// +// Also rejects hyphenated compounds ("is-ready-cap", "re-done") and plain +// substring false positives ("already"/"redone"/"idleness"). +export const STRONG_IDLE_KEYWORDS_RE = new RegExp( + `(? lower.includes(word)) +} + +/** + * Tracks agent status transitions from terminal title changes. + * Fires `onBecameIdle` when an agent transitions from working to idle/permission, + * like haunt's attention flag — the key trigger for unread notifications. + */ +export function createAgentStatusTracker( + onBecameIdle: (title: string) => void, + onBecameWorking?: () => void, + onAgentExited?: () => void +): { + handleTitle: (title: string) => void + /** Clear accumulated status so a stale working→idle transition cannot fire + * after the owning transport is torn down. */ + reset: () => void +} { + let lastStatus: AgentStatus | null = null + + return { + handleTitle(title: string): void { + const newStatus = detectAgentStatusFromTitle(title) + if (lastStatus === 'working' && newStatus !== null && newStatus !== 'working') { + onBecameIdle(title) + } + if (lastStatus !== 'working' && newStatus === 'working') { + onBecameWorking?.() + } + // Why: when the title reverts to a plain shell prompt (e.g., "bash", "zsh"), + // detectAgentStatusFromTitle returns null. If we were idle or in a permission + // prompt, this means the user exited the agent — clear session-tied state + // (like the prompt-cache countdown). We intentionally do NOT fire this when + // lastStatus is 'working', because active agents can briefly flash shell + // titles during internal operations without actually exiting. + if (lastStatus !== null && lastStatus !== 'working' && newStatus === null) { + lastStatus = null + onAgentExited?.() + } + if (newStatus !== null) { + lastStatus = newStatus + } + }, + reset(): void { + lastStatus = null + } + } +} + +// Why: cursor-agent's native OSC title is the literal string "Cursor Agent" +// across the entire turn — it carries zero working/idle information. Orca +// synthesizes its own titles ("⠋ Cursor Agent" for working, "Cursor - +// action required" for permission) from cursor's hook events; the bare +// native title must be a no-op so cursor's per-turn re-emissions cannot +// stomp the synthesized state back to idle. +const CURSOR_NATIVE_TITLE_LOWER = 'cursor agent' + +export function detectAgentStatusFromTitle(title: string): AgentStatus | null { + if (!title) { + return null + } + if (isClaudeManagementTitle(title)) { + return null + } + // Why: "Cursor Agent" exactly (case-insensitive, no prefix/suffix) is cursor's + // native title. Anything with additional tokens ("⠋ Cursor Agent", "Cursor - + // action required") is either an Orca-synthesized working/permission title + // or a tighter match worth classifying. + if (title.trim().toLowerCase() === CURSOR_NATIVE_TITLE_LOWER) { + return null + } + + // Gemini CLI symbols are the most specific and should take precedence. + if (title.includes(GEMINI_PERMISSION)) { + return 'permission' + } + if (title.includes(GEMINI_WORKING) || title.includes(GEMINI_SILENT_WORKING)) { + return 'working' + } + if (title.includes(GEMINI_IDLE)) { + return 'idle' + } + + // Why: resolve synthetic Pi/OMP permission/idle labels before the broader + // Pi and braille-spinner checks below. + const piCompatibleSyntheticAgentStatus = getPiCompatibleSyntheticAgentStatus(title) + if (piCompatibleSyntheticAgentStatus) { + return piCompatibleSyntheticAgentStatus + } + + // Claude Code uses ✳ prefix for idle — must check before braille/agent-name + // because the title text is the task description, not "Claude Code". + if (title.startsWith(`${CLAUDE_IDLE} `) || title === CLAUDE_IDLE) { + return 'idle' + } + + if (isPiTerminalTitle(title)) { + return 'idle' + } + + if (containsBrailleSpinner(title)) { + return 'working' + } + + const hasDroidAgentName = DROID_AGENT_NAME_RE.test(title) + const hasHermesAgentName = HERMES_AGENT_NAME_RE.test(title) + const hasAgyAgentName = AGY_AGENT_NAME_RE.test(title) + const hasLegacyAgentName = titleHasAnyLegacyAgentName(title) + if (hasLegacyAgentName || hasDroidAgentName || hasHermesAgentName || hasAgyAgentName) { + if (containsAny(title, ['action required', 'permission', 'waiting'])) { + return 'permission' + } + // Why: hyphen/word-char-aware boundary match (not plain substring, and + // stricter than `\b` — which treats `-` as a boundary) so titles like + // "~/codex already built" do not classify as idle via the substring + // "already" ⊃ "ready". See STRONG_IDLE_KEYWORDS_RE comment. + if (STRONG_IDLE_KEYWORDS_RE.test(title)) { + return 'idle' + } + // Why: hyphen/word-char-aware boundary match (not plain substring, and + // stricter than `\b`) so titles like "~/codex reworking diff" or + // "is-thinking-cap" do not classify as working via the substrings + // "reworking" ⊃ "working" or the `-`-adjacent "thinking" in + // "is-thinking-cap". Mirrors STRONG_IDLE_KEYWORDS_RE for symmetry; a + // false 'working' is worse than a false 'idle' because it drives + // active-agent UI (spinners, counts). + if (STRONG_WORKING_KEYWORDS_RE.test(title)) { + return 'working' + } + + // Claude Code title prefixes: ". " = working, "* " = idle + if (title.startsWith('. ')) { + return 'working' + } + if (title.startsWith('* ')) { + return 'idle' + } + + // Why: Factory Droid can publish native titles like "Factory Droid needs + // input" while an Execute tool is still sleeping. Droid's hook events are + // authoritative; don't turn a name-only native title into a completion. + if (hasDroidAgentName && !hasLegacyAgentName) { + return null + } + + return 'idle' + } + + return null +} diff --git a/src/shared/types.ts b/src/shared/types.ts index cfbdd8f50..0d181358a 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1,6 +1,6 @@ /* eslint-disable max-lines */ import type { ExecutionHostId } from './execution-host' -import type { SshRemotePtyLease, SshTarget } from './ssh-types' +import type { RemovedSshTargetTombstone, SshRemotePtyLease, SshTarget } from './ssh-types' import type { Automation, AutomationExecutionTargetType, AutomationRun } from './automations-types' import type { WorkspaceSource } from './workspace-source' import type { GitHubProjectSettings } from './github-project-types' @@ -1022,6 +1022,9 @@ export type PersistedOpenFile = { runtimeEnvironmentId?: string | null /** Unsaved editor buffer captured for hot exit; presence restores the tab dirty. */ dirtyDraftContent?: string + /** Signature of the disk content the dirty draft is based on; lets restore + * re-derive a changed-on-disk conflict from ground truth. */ + lastKnownDiskSignature?: string } export type WorkspaceSessionState = { @@ -3534,6 +3537,9 @@ export type PersistedState = { * matching ~/.ssh/config host on the next sync so a deleted host does not * reappear. Cleared for an alias when the user re-adds it or re-adopts config. */ deletedSshConfigAliases: string[] + /** Identity records for removed SSH targets. Lets a re-added host re-adopt + * workspaces that were orphaned on the old target id. Pruned by age/count. */ + removedSshTargetTombstones?: RemovedSshTargetTombstone[] sshRemotePtyLeases: SshRemotePtyLease[] /** Daemon session ids of live local Claude launches. Seeds the Claude * live-PTY gate on startup so an early OAuth refresh cannot rotate the diff --git a/src/shared/workspace-session-schema.ts b/src/shared/workspace-session-schema.ts index 07e98996e..22657617c 100644 --- a/src/shared/workspace-session-schema.ts +++ b/src/shared/workspace-session-schema.ts @@ -161,7 +161,8 @@ const persistedOpenFileSchema = z.object({ language: z.string(), isPreview: z.boolean().optional(), runtimeEnvironmentId: z.string().nullable().optional(), - dirtyDraftContent: z.string().optional() + dirtyDraftContent: z.string().optional(), + lastKnownDiskSignature: z.string().optional() }) // ─── Browser ──────────────────────────────────────────────────────── diff --git a/src/shared/wsl-login-shell-command.test.ts b/src/shared/wsl-login-shell-command.test.ts index 925937c88..7cc304771 100644 --- a/src/shared/wsl-login-shell-command.test.ts +++ b/src/shared/wsl-login-shell-command.test.ts @@ -117,6 +117,14 @@ describe('wsl login shell command helpers', () => { expect(command).toContain('getent passwd') expect(command).toContain('if [ -z "$_orca_wsl_shell" ] || [ ! -x "$_orca_wsl_shell" ]; then') + expect(command).toContain('_orca_shell_ready_root=""') + expect(command).toContain('if [ -n "${ORCA_USER_DATA_PATH:-}" ]; then') + expect(command).toContain('_orca_wsl_shell_name=$(basename "$_orca_wsl_shell"') + expect(command).toContain('bash)') + expect(command).toContain('--rcfile "${_orca_shell_ready_root}/bash/rcfile"') + expect(command).toContain('zsh)') + expect(command).toContain('export ZDOTDIR="${_orca_shell_ready_root}/zsh"') expect(command).toContain('exec "$_orca_wsl_shell" -l') + expectValidShSyntax(command) }) }) diff --git a/src/shared/wsl-login-shell-command.ts b/src/shared/wsl-login-shell-command.ts index 45356f402..d95939eaa 100644 --- a/src/shared/wsl-login-shell-command.ts +++ b/src/shared/wsl-login-shell-command.ts @@ -45,6 +45,23 @@ export function buildWslInteractiveLoginShellCommand(): string { 'if [ -z "$_orca_wsl_shell" ] || [ ! -x "$_orca_wsl_shell" ]; then', ' _orca_wsl_shell=/bin/sh', 'fi', + '_orca_shell_ready_root=""', + 'if [ -n "${ORCA_USER_DATA_PATH:-}" ]; then', + ' _orca_shell_ready_root="${ORCA_USER_DATA_PATH%/}/shell-ready"', + 'fi', + '_orca_wsl_shell_name=$(basename "$_orca_wsl_shell" | tr "[:upper:]" "[:lower:]")', + 'case "$_orca_wsl_shell_name" in', + ' bash)', + ' if [ -n "${_orca_shell_ready_root:-}" ] && [ -f "${_orca_shell_ready_root}/bash/rcfile" ]; then', + ' exec "$_orca_wsl_shell" --rcfile "${_orca_shell_ready_root}/bash/rcfile"', + ' fi', + ' ;;', + ' zsh)', + ' if [ -n "${_orca_shell_ready_root:-}" ] && [ -d "${_orca_shell_ready_root}/zsh" ]; then', + ' export ZDOTDIR="${_orca_shell_ready_root}/zsh"', + ' fi', + ' ;;', + 'esac', 'exec "$_orca_wsl_shell" -l' ].join('\n') } diff --git a/tools/daemon-relocation-spike/README.md b/tools/daemon-relocation-spike/README.md new file mode 100644 index 000000000..d7edd313a --- /dev/null +++ b/tools/daemon-relocation-spike/README.md @@ -0,0 +1,160 @@ +# daemon-relocation-spike + +A throwaway probe that answers one empirical question for Phase 1 of the +Windows update-survival work: + +> What is the **minimal set of files** that must be copied out of a packaged +> `win-unpacked` build so that a **copied `Orca.exe`** — run with +> `ELECTRON_RUN_AS_NODE=1` from a directory **outside** the install dir — can: +> (a) start the terminal daemon and signal ready over IPC, +> (b) spawn a real ConPTY `node-pty` session, write input, and read output back, +> (c) do all of that while holding **no open file handles into the app/install +> dir**, so an NSIS update could delete the original install. + +## Why this matters + +The daemon is `fork()`ed from the app's own Electron binary (`Orca.exe`) with +`ELECTRON_RUN_AS_NODE=1`, from the **install** directory. On a Windows update, +electron-builder's NSIS installer (a) runs `uninstallOldVersion` (deletes the +registered install's files) and (b) `CHECK_APP_RUNNING` force-closes every +process whose image path is under `$INSTDIR`. So the daemon dies and its held +file locks can break the update. + +The Phase 1 fix copies the daemon's whole file closure **out** of the install +dir (into `%LOCALAPPDATA%`/userData) and forks the daemon from the **copy**, so +its image + all loaded modules live outside `$INSTDIR`. This spike measures how +small that copy can be while still working. + +We keep the **Electron binary run as node** (not a stock `node.exe`): a prior +attempt (#7473, reverted) switched to stock node and caused Windows-console +flashing (stock node lacks Electron's `kHideConsoleWindows`) plus asar breakage. +This spike does **not** reintroduce stock node. + +## Usage + +``` +# Real run (Windows, needs a packaged win-unpacked build): +node tools/daemon-relocation-spike/spike.mjs \ + --app-dir \ + --work-dir \ + [--tier full|no-gpu|minimal] \ + [--keep-work-dir] + +# Offline logic validation (any OS, no build, no launch): +node tools/daemon-relocation-spike/spike.mjs --selftest +``` + +Exit code is `0` only when the run **PASSES**: daemon ready, PTY echo +round-trips the nonce, the daemon's main module is the copied `Orca.exe`, and +**no** loaded module resolves under `--app-dir`. + +## Tiers (defined as data in `tier-file-set.mjs`) + +Every tier includes the irreducible core: `Orca.exe`, `icudtl.dat`, both V8 +snapshot blobs (`snapshot_blob.bin`, `v8_context_snapshot.bin`), the daemon +bundle (`out/main/daemon-entry.js` + `chunks/` + `out/package.json`), and the +whole `node-pty` package (native `conpty.node` + the sibling `conpty/` runtime +dir holding `conpty.dll` + `OpenConsole.exe`). + +Tiers differ only in which top-level `*.dll` files they carry: + +| Tier | Top-level DLLs | +| --------- | ---------------------------------------------------------------- | +| `full` | **all** top-level `*.dll` | +| `no-gpu` | all **except** GPU/render DLLs (`libEGL`, `libGLESv2`, `vk_swiftshader`, `vulkan-1`, `d3dcompiler_47`); **keeps** `ffmpeg.dll` | +| `minimal` | **none** (exe + data blobs + daemon bundle + node-pty only) | + +Trimming further is a config change (edit `TIER_DEFINITIONS` / `GPU_DLLS`), not +a code change. + +## How node-pty's native + ConPTY runtime is handled + +The whole `node-pty` package tree is copied, and **the entire win-unpacked +layout is mirrored verbatim** (every copy destination is relative to the +win-unpacked root, not the asar-unpacked root). This matters because node-pty is +packaged at `resources/node_modules/node-pty` — a **sibling** of +`app.asar.unpacked`, not under it (see +`config/packaged-runtime-node-modules.cjs`). Mirroring the full layout preserves +two resolutions from the relocated path: + +1. **The daemon require-closure** resolves `require('node-pty')` by walking + parent dirs up from the mirrored + `resources/app.asar.unpacked/out/main/daemon-entry.js`, which passes through + `resources/` and finds `resources/node_modules/node-pty` — exactly as in the + packaged app. +2. **node-pty's own native loader** resolves `conpty.node` from `build/Release` + (or `prebuilds/win32-`) relative to node-pty's own `__dirname`, and + node-pty's Windows addon loads `conpty.dll` from `/conpty/` + and spawns `OpenConsole.exe` from beside it. Copying the tree verbatim keeps + all three side-by-side. + +### `ORCA_NODE_PTY_NATIVE_DIR` + +The reverted #7421 added a `node-pty` patch that reads +`ORCA_NODE_PTY_NATIVE_DIR` to override the native dir. **The current branch's +`config/patches/node-pty@1.1.0.patch` does NOT contain that override** — it was +reverted. The spike therefore relies on **layout preservation** (copying the +node-pty tree at its default relative path) rather than the env override. The +spike still *sets* `ORCA_NODE_PTY_NATIVE_DIR` to the relocated native dir so it +keeps working if pointed at a build that carries the patch, but on this branch +the var is inert. + +**Implication for the real Phase 1 implementation:** if the production copy does +NOT preserve node-pty at the path its loader resolves by default (e.g. if the +daemon-entry is relocated without the sibling `node_modules/node-pty`), the impl +will need to **re-add the `ORCA_NODE_PTY_NATIVE_DIR` patch** from #7421. If it +mirrors the layout as this spike does, the patch is not strictly required — +though re-adding it is the more robust choice. + +## The handshake / client + +`ndjson-client.mjs` is a small standalone NDJSON client (no electron/src +imports) that mirrors `src/main/daemon/daemon-server.ts`: + +1. Read the token the server writes to the token file after it begins listening. +2. Open a **control** socket, send `hello {role:'control'}`, await + `{type:'hello', ok:true}`. +3. Open a **stream** socket with the **same** `clientId`, send + `hello {role:'stream'}`. +4. `createOrAttach` on control, then `write` `echo SPIKE-OK-\r\n`, and + read `data` events on the stream socket until the nonce appears **alone at + line start** (executed output, distinct from the echoed input line). + +`PROTOCOL_VERSION` is read at runtime from `src/main/daemon/types.ts` so the +client never drifts from the daemon. + +## The handle probe + +`loaded-modules.ps1` (via `loaded-module-probe.mjs`) runs +`Get-Process -Id ` and enumerates `.Modules[].FileName`. Any module path +under `--app-dir` is a **lock risk** (the installer cannot replace a file a live +process maps), so a passing relocation must show **zero**. It also asserts the +process's **main module** is the copied `Orca.exe`, not the install-dir one. + +Loaded DLLs are the lock-critical set. Data files (`icudtl.dat`, asar) are not +memory-mapped as modules, so this probe does not enumerate them — the copy plan +handles those by construction (they are copied, so nothing opens the originals). + +## What remains unverified until CI runs it + +This session has **no build**, so the launch path is unproven. Verified here: +`node --check` on every `.mjs`, a green `--selftest`, and clean +`pnpm exec oxlint`. Open questions the real CI run must answer: + +- Whether `TIER_MINIMAL` (no top-level DLLs) boots `Orca.exe` as node at all, or + whether run-as-node still needs `ffmpeg.dll` / others — this is the core + empirical result. +- Whether the daemon bundle require-closure needs any **other** unpacked + `node_modules` beyond `node-pty` (surfaces as a ready-timeout if so). +- Whether any loaded module still resolves under `--app-dir` (the handle probe + will name it). + +## Recommendation for the likely-minimal tier + +`no-gpu` is the safe minimal target to ship: run-as-node Electron does not +initialize the GPU/render stack, so `libEGL` / `libGLESv2` / `vk_swiftshader` / +`vulkan-1` / `d3dcompiler_47` are very unlikely to load, while `ffmpeg.dll` and +the ICU/snapshot data are retained because the Electron bootstrap references +them regardless of run-as-node. Run `--tier minimal` on CI first: if it PASSES, +ship minimal; if `Orca.exe` fails to boot without the non-GPU DLLs, fall back to +`no-gpu`. `full` is the always-works upper bound for comparison. diff --git a/tools/daemon-relocation-spike/app-inventory.mjs b/tools/daemon-relocation-spike/app-inventory.mjs new file mode 100644 index 000000000..0460d1d4c --- /dev/null +++ b/tools/daemon-relocation-spike/app-inventory.mjs @@ -0,0 +1,146 @@ +// Locates the daemon-host inputs inside a packaged win-unpacked build. +// +// Layout the packager produces (see config/electron-builder.config.cjs and +// config/packaged-runtime-node-modules.cjs): +// /Orca.exe electron binary (run as node) +// /icudtl.dat ICU data (needed even as node) +// /snapshot_blob.bin V8 snapshot +// /v8_context_snapshot.bin V8 context snapshot +// /*.dll electron/GPU runtime DLLs +// /resources/app.asar.unpacked/out/main/daemon-entry.js (+ chunks/) +// /resources/app.asar.unpacked/node_modules/node-pty/** native + conpty + +import { existsSync, readdirSync, statSync } from 'node:fs' +import { basename, join } from 'node:path' + +export const RUNTIME_DATA_FILES = ['icudtl.dat', 'snapshot_blob.bin', 'v8_context_snapshot.bin'] +export const HOST_EXE = 'Orca.exe' + +// Windows arch dir names node-pty prebuilds ship under; build/Release is the +// packaged rebuild location and takes precedence. +const NODE_PTY_NATIVE_CANDIDATES = ['build/Release', 'prebuilds/win32-x64', 'prebuilds/win32-arm64'] + +function fileEntry(dir, name) { + const path = join(dir, name) + if (!existsSync(path)) { + return { name, path, exists: false, size: 0 } + } + return { name, path, exists: true, size: statSync(path).size } +} + +function listTopLevelDlls(appDir) { + const dlls = [] + for (const name of readdirSync(appDir)) { + if (name.toLowerCase().endsWith('.dll')) { + dlls.push(fileEntry(appDir, name)) + } + } + return dlls.sort((a, b) => a.name.localeCompare(b.name)) +} + +// Resolve the app.asar.unpacked root: everything the forked daemon-entry +// require-closure resolves (chunks, node-pty) lives under it, so the copied +// host must mirror it verbatim. +function resolveUnpackedRoot(appDir) { + const candidate = join(appDir, 'resources', 'app.asar.unpacked') + return existsSync(candidate) ? candidate : null +} + +// getDaemonEntryPath() in daemon-init.ts probes daemon-entry.js at the unpacked +// root first, then out/main — mirror that resolution order here. +function resolveDaemonEntry(unpackedRoot) { + if (!unpackedRoot) { + return { name: 'daemon-entry.js', path: '', exists: false, size: 0, relFromUnpacked: '' } + } + const direct = join(unpackedRoot, 'daemon-entry.js') + if (existsSync(direct)) { + return { ...fileEntry(unpackedRoot, 'daemon-entry.js'), relFromUnpacked: 'daemon-entry.js' } + } + const nested = join('out', 'main', 'daemon-entry.js') + const nestedPath = join(unpackedRoot, nested) + return { + name: 'daemon-entry.js', + path: nestedPath, + exists: existsSync(nestedPath), + size: existsSync(nestedPath) ? statSync(nestedPath).size : 0, + relFromUnpacked: nested.split('\\').join('/') + } +} + +function resolveNodePty(unpackedRoot, appDir) { + // Prefer the unpacked-root copy (what the daemon require-closure resolves); + // fall back to a resources-level copy some builds also stage. + const roots = [] + if (unpackedRoot) { + roots.push(join(unpackedRoot, 'node_modules', 'node-pty')) + } + roots.push(join(appDir, 'resources', 'node_modules', 'node-pty')) + + for (const dir of roots) { + if (!existsSync(dir)) { + continue + } + for (const rel of NODE_PTY_NATIVE_CANDIDATES) { + const nativeDir = join(dir, ...rel.split('/')) + if (existsSync(join(nativeDir, 'conpty.node'))) { + return { + exists: true, + packageDir: dir, + nativeDir, + nativeRel: rel, + conptyNode: fileEntry(nativeDir, 'conpty.node'), + // node-pty's Windows addon loads conpty.dll from /conpty/. + conptyDll: fileEntry(join(nativeDir, 'conpty'), 'conpty.dll'), + openConsole: fileEntry(join(nativeDir, 'conpty'), 'OpenConsole.exe') + } + } + } + // node-pty present but no ConPTY native found under known dirs. + return { exists: true, packageDir: dir, nativeDir: '', nativeRel: '', conptyNode: null } + } + return { exists: false, packageDir: '', nativeDir: '', nativeRel: '', conptyNode: null } +} + +/** + * Discover every daemon-host input in `appDir`. Never throws for missing files; + * each entry carries an `exists` flag so the caller can print a full report and + * decide whether the chosen tier is buildable. + */ +export function inventoryAppDir(appDir) { + const unpackedRoot = resolveUnpackedRoot(appDir) + return { + appDir, + unpackedRoot, + hostExe: fileEntry(appDir, HOST_EXE), + runtimeData: RUNTIME_DATA_FILES.map((name) => fileEntry(appDir, name)), + topLevelDlls: listTopLevelDlls(appDir), + daemonEntry: resolveDaemonEntry(unpackedRoot), + nodePty: resolveNodePty(unpackedRoot, appDir) + } +} + +/** Human-readable inventory dump for the run report. */ +export function formatInventory(inv) { + const lines = [] + const kib = (n) => `${(n / 1024).toFixed(1)} KiB` + const mark = (e) => (e.exists ? 'OK ' : 'MISS') + lines.push(`app-dir: ${inv.appDir}`) + lines.push(` ${mark(inv.hostExe)} ${inv.hostExe.name} (${kib(inv.hostExe.size)})`) + for (const e of inv.runtimeData) { + lines.push(` ${mark(e)} ${e.name} (${kib(e.size)})`) + } + lines.push(` top-level DLLs: ${inv.topLevelDlls.length}`) + for (const e of inv.topLevelDlls) { + lines.push(` - ${basename(e.name)} (${kib(e.size)})`) + } + lines.push( + ` ${mark(inv.daemonEntry)} daemon-entry: ${inv.daemonEntry.relFromUnpacked || '(none)'}` + ) + const np = inv.nodePty + lines.push(` node-pty: ${np.exists ? np.packageDir : '(none)'}`) + if (np.conptyNode) { + lines.push(` native: ${np.nativeRel} conpty.node (${kib(np.conptyNode.size)})`) + lines.push(` conpty.dll: ${mark(np.conptyDll)} OpenConsole.exe: ${mark(np.openConsole)}`) + } + return lines.join('\n') +} diff --git a/tools/daemon-relocation-spike/cli.mjs b/tools/daemon-relocation-spike/cli.mjs new file mode 100644 index 000000000..227580d5e --- /dev/null +++ b/tools/daemon-relocation-spike/cli.mjs @@ -0,0 +1,88 @@ +// Argument parsing + usage for the daemon-relocation spike. +// +// The spike answers an empirical question (see README): what is the MINIMAL +// set of files that must be copied out of a packaged win-unpacked build so a +// COPIED Orca.exe (ELECTRON_RUN_AS_NODE=1) can host the terminal daemon and a +// real ConPTY session while holding no open handles into the install dir. + +export const TIERS = ['full', 'no-gpu', 'minimal'] + +const USAGE = ` +daemon-relocation-spike — minimal relocated daemon-host file-set probe (Windows) + +Usage: + node tools/daemon-relocation-spike/spike.mjs --app-dir --work-dir [--tier ] + node tools/daemon-relocation-spike/spike.mjs --selftest + +Required (launch mode): + --app-dir Path to a packaged win-unpacked build (contains Orca.exe) + --work-dir Scratch dir for the copied host + logs (created, then removed) + +Options: + --tier File-set tier to copy: "full" (default), "no-gpu", "minimal" + full = Orca.exe + icudtl.dat + both snapshot blobs + + ALL top-level *.dll + daemon bundle + node-pty + no-gpu = full minus GPU/render DLLs (libEGL, libGLESv2, + vk_swiftshader, vulkan-1, d3dcompiler_47); + ffmpeg.dll kept + minimal = Orca.exe + icudtl.dat + both snapshots + + daemon bundle + node-pty only (no top-level DLLs) + --keep-work-dir Leave --work-dir on disk after the run (for inspection) + --selftest Validate arg parsing, tier defs, and the module-path filter + against synthetic inputs. No real build or launch. Exits + 0 on pass, non-zero on failure. + -h, --help Show this help + +Exit code is 0 only when the run PASSES: daemon ready, PTY echo round-trips the +nonce, and NO loaded module resolves under --app-dir. +` + +export function getUsage() { + return USAGE +} + +/** + * Parse argv (already sliced past `node script`). Returns a discriminated + * result: { help }, { selftest }, or { launch: {...} }. On a usage error + * returns { error } so the caller can print USAGE and exit non-zero. + */ +export function parseArgs(argv) { + if (argv.includes('-h') || argv.includes('--help')) { + return { help: true } + } + if (argv.includes('--selftest')) { + return { selftest: true } + } + + let appDir = '' + let workDir = '' + let tier = 'full' + let keepWorkDir = false + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] + if (arg === '--app-dir' && argv[i + 1]) { + appDir = argv[i + 1] + i++ + } else if (arg === '--work-dir' && argv[i + 1]) { + workDir = argv[i + 1] + i++ + } else if (arg === '--tier' && argv[i + 1]) { + tier = argv[i + 1] + i++ + } else if (arg === '--keep-work-dir') { + keepWorkDir = true + } else { + return { error: `Unknown or incomplete argument: ${arg}` } + } + } + + if (!appDir || !workDir) { + return { error: 'Both --app-dir and --work-dir are required' } + } + if (!TIERS.includes(tier)) { + return { error: `Invalid --tier "${tier}" (expected one of: ${TIERS.join(', ')})` } + } + + return { launch: { appDir, workDir, tier, keepWorkDir } } +} diff --git a/tools/daemon-relocation-spike/daemon-launch.mjs b/tools/daemon-relocation-spike/daemon-launch.mjs new file mode 100644 index 000000000..74784db9f --- /dev/null +++ b/tools/daemon-relocation-spike/daemon-launch.mjs @@ -0,0 +1,99 @@ +// Launches the copied Orca.exe as the daemon host (ELECTRON_RUN_AS_NODE=1) and +// waits for its {type:'ready'} IPC signal. Mirrors the real fork() options in +// src/main/daemon/daemon-init.ts (detached, ipc channel, ORCA_USER_DATA_PATH). + +import { spawn } from 'node:child_process' +import { createWriteStream } from 'node:fs' +import { join } from 'node:path' + +/** + * Spawn the daemon host. Resolves { child, pid } once the daemon signals ready, + * or rejects on early exit / timeout. stdout+stderr are teed to files under + * workDir. The caller owns shutdown (SIGTERM `child`). + */ +export function launchDaemonHost(options) { + const { + hostExePath, + daemonEntryPath, + socketPath, + tokenPath, + workDir, + nodePtyNativeDir, + logFilePath, + readyTimeoutMs = 30000 + } = options + + const stdoutLog = createWriteStream(join(workDir, 'daemon-stdout.log')) + const stderrLog = createWriteStream(join(workDir, 'daemon-stderr.log')) + + const env = { + ...process.env, + ELECTRON_RUN_AS_NODE: '1', + ORCA_USER_DATA_PATH: workDir + } + // The current branch's node-pty patch resolves natives relative to its own + // dir, so this env var is inert there; set it anyway so the spike still works + // if run against a build that carries the ORCA_NODE_PTY_NATIVE_DIR patch. + if (nodePtyNativeDir) { + env.ORCA_NODE_PTY_NATIVE_DIR = nodePtyNativeDir + } + + // Why: --log-file makes the daemon write its session lifecycle events + // (session-created / session-exited / uncaught-exception-suppressed) to a + // file, which is the only window into ConPTY spawn failures that don't reach + // stdout/stderr. daemon-entry parses it as an optional Phase 0 flag. + const daemonArgs = [daemonEntryPath, '--socket', socketPath, '--token', tokenPath] + if (logFilePath) { + daemonArgs.push('--log-file', logFilePath) + } + + const child = spawn(hostExePath, daemonArgs, { + cwd: workDir, + detached: true, + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + env + }) + child.stdout.pipe(stdoutLog) + child.stderr.pipe(stderrLog) + + return new Promise((resolve, reject) => { + let settled = false + const timer = setTimeout(() => { + finish(new Error(`daemon did not signal ready within ${readyTimeoutMs}ms`)) + }, readyTimeoutMs) + + function finish(err) { + if (settled) { + return + } + settled = true + clearTimeout(timer) + child.off('message', onMessage) + child.off('error', onError) + child.off('exit', onExit) + if (err) { + // Expose the still-running detached child so the caller can stop it; + // otherwise a ready-timeout leaks the daemon with no handle to kill it. + err.child = child + reject(err) + } else { + resolve({ child, pid: child.pid }) + } + } + function onMessage(msg) { + if (msg && typeof msg === 'object' && msg.type === 'ready') { + finish(null) + } + } + function onError(err) { + finish(err) + } + function onExit(code, signal) { + finish(new Error(`daemon exited before ready (code=${code}, signal=${signal})`)) + } + + child.on('message', onMessage) + child.on('error', onError) + child.on('exit', onExit) + }) +} diff --git a/tools/daemon-relocation-spike/host-copy.mjs b/tools/daemon-relocation-spike/host-copy.mjs new file mode 100644 index 000000000..f95541a91 --- /dev/null +++ b/tools/daemon-relocation-spike/host-copy.mjs @@ -0,0 +1,62 @@ +// Materializes a tier's copy plan into /daemon-host/, preserving the +// relative layout the daemon require-closure and node-pty native resolution +// expect. Returns the paths the launcher needs. + +import { cpSync, existsSync, mkdirSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { HOST_EXE } from './app-inventory.mjs' +import { toPosixRelative } from './tier-file-set.mjs' + +export const HOST_SUBDIR = 'daemon-host' + +function destPath(hostRoot, destRel) { + return join(hostRoot, ...destRel.split('/')) +} + +/** + * Execute the copy plan. Returns { hostRoot, hostExePath, daemonEntryPath, + * nodePtyNativeDir, skipped } — nodePtyNativeDir is the / dir under the + * copied node-pty, offered to callers that want to set ORCA_NODE_PTY_NATIVE_DIR + * (see README: the current branch's node-pty patch does NOT read it, so it is + * belt-and-suspenders here). + */ +export function copyHost(inv, plan, workDir) { + const hostRoot = join(workDir, HOST_SUBDIR) + mkdirSync(hostRoot, { recursive: true }) + + const skipped = [] + for (const op of plan.ops) { + const dest = destPath(hostRoot, op.destRel) + if (!existsSync(op.sourcePath)) { + if (!op.optional) { + skipped.push(op.destRel) + } + continue + } + mkdirSync(dirname(dest), { recursive: true }) + // cpSync mirrors both files and directory trees; dereference symlinks so + // the copy holds no link back into the app dir. + cpSync(op.sourcePath, dest, { + recursive: op.kind === 'dir', + dereference: true, + force: true + }) + } + + const hostExePath = join(hostRoot, HOST_EXE) + // Both paths mirror the win-unpacked layout under hostRoot, so they resolve + // exactly as they do in the packaged app (relative to appDir). + const daemonEntryPath = inv.daemonEntry.exists + ? destPath(hostRoot, toPosixRelative(inv.appDir, inv.daemonEntry.path)) + : '' + + // The relocated node-pty native dir (build/Release or prebuilds/...), mirrored + // under the host root at node-pty's real win-unpacked-relative path. + let nodePtyNativeDir = '' + if (inv.nodePty.exists && inv.nodePty.nativeRel) { + const pkgRel = toPosixRelative(inv.appDir, inv.nodePty.packageDir) + nodePtyNativeDir = destPath(hostRoot, `${pkgRel}/${inv.nodePty.nativeRel}`) + } + + return { hostRoot, hostExePath, daemonEntryPath, nodePtyNativeDir, skipped } +} diff --git a/tools/daemon-relocation-spike/loaded-module-probe.mjs b/tools/daemon-relocation-spike/loaded-module-probe.mjs new file mode 100644 index 000000000..07170a508 --- /dev/null +++ b/tools/daemon-relocation-spike/loaded-module-probe.mjs @@ -0,0 +1,85 @@ +// Probes a running daemon's loaded modules (via loaded-modules.ps1) and flags +// any that resolve under the original app dir — those would be locked during an +// NSIS update and defeat the relocation. + +import { spawnSync } from 'node:child_process' +import { join, win32 } from 'node:path' + +const HERE = import.meta.dirname +const POWERSHELL = 'powershell.exe' +const PS_ARGS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass'] + +// Case-insensitive, separator-normalized containment test. The inputs are always +// Windows module paths, so use win32 semantics explicitly — otherwise --selftest +// on a non-Windows host would treat `\` as a literal and every check would fail. +function normalizeForCompare(p) { + return win32 + .normalize(p) + .replace(/[\\/]+$/, '') + .toLowerCase() +} + +/** + * Pure filter: which of `modulePaths` live under `appDir`. Exported so selftest + * can validate the containment logic against synthetic inputs without a launch. + * Matches on a path-segment boundary so `C:\App` does not match `C:\Application`. + */ +export function findAppDirResidentModules(modulePaths, appDir) { + const needle = normalizeForCompare(appDir) + const prefix = `${needle}${win32.sep}` + return modulePaths.filter((raw) => { + const candidate = normalizeForCompare(raw) + return candidate === needle || candidate.startsWith(prefix) + }) +} + +/** + * Run the PowerShell probe for `pid`. Returns + * { found, mainModule, modules } or throws if PowerShell itself fails. + */ +export function probeLoadedModules(pid) { + const script = join(HERE, 'loaded-modules.ps1') + const result = spawnSync(POWERSHELL, [...PS_ARGS, '-File', script, '-ProcessId', String(pid)], { + encoding: 'utf8', + maxBuffer: 32 * 1024 * 1024 + }) + if (result.error) { + throw new Error(`failed to spawn PowerShell probe: ${result.error.message}`) + } + // Check exit status before parsing: a non-zero exit that still wrote to stdout + // would otherwise surface as a bare JSON SyntaxError instead of the real error. + if (result.status !== 0) { + throw new Error(`loaded-modules.ps1 exited with status ${result.status}: ${result.stderr}`) + } + const trimmed = (result.stdout ?? '').trim() + if (!trimmed) { + throw new Error( + `loaded-modules.ps1 produced no output (exit ${result.status}): ${result.stderr}` + ) + } + return JSON.parse(trimmed) +} + +/** + * Full handle assessment for a running daemon: whether its main module is the + * copied host exe, and which loaded modules (if any) still live in the app dir. + * Returns a structured verdict; never throws for a clean/empty module list. + */ +export function assessDaemonHandles(pid, appDir, expectedHostExePath) { + const probe = probeLoadedModules(pid) + if (!probe.found) { + return { found: false, mainModuleOk: false, appDirModules: [], mainModule: null } + } + const modules = Array.isArray(probe.modules) ? probe.modules : [] + const appDirModules = findAppDirResidentModules(modules, appDir) + const mainModuleOk = + typeof probe.mainModule === 'string' && + normalizeForCompare(probe.mainModule) === normalizeForCompare(expectedHostExePath) + return { + found: true, + mainModule: probe.mainModule, + mainModuleOk, + moduleCount: modules.length, + appDirModules + } +} diff --git a/tools/daemon-relocation-spike/loaded-modules.ps1 b/tools/daemon-relocation-spike/loaded-modules.ps1 new file mode 100644 index 000000000..98568134e --- /dev/null +++ b/tools/daemon-relocation-spike/loaded-modules.ps1 @@ -0,0 +1,44 @@ +# Emits the main-module path and every loaded module (DLL) path for a process, +# as a single JSON document, for the daemon-relocation spike's handle probe. +# +# Loaded DLLs are the update-time lock risk: the NSIS installer's CHECK_APP_RUNNING +# sweep force-closes processes whose image is under $INSTDIR, and files a live +# process maps cannot be replaced. A relocated host must load ZERO modules from +# the app dir. Data files (icudtl.dat, asar) are not memory-mapped as modules, so +# this probe covers the lock-critical set, not the entire open-handle set. +# +# PS 5.1 guard: $proc.Modules can be a single object (no .Count); @(...) forces +# an array so the enumeration and count are correct for one-module processes. + +param( + [Parameter(Mandatory = $true)] + [int]$ProcessId +) + +$ErrorActionPreference = 'Stop' + +try { + $proc = Get-Process -Id $ProcessId -ErrorAction Stop +} catch { + Write-Output (@{ found = $false; mainModule = $null; modules = @() } | ConvertTo-Json -Compress) + exit 0 +} + +$modulePaths = @() +foreach ($m in @($proc.Modules)) { + if ($m -and $m.FileName) { + $modulePaths += $m.FileName + } +} + +$mainModule = $null +if ($proc.MainModule -and $proc.MainModule.FileName) { + $mainModule = $proc.MainModule.FileName +} + +$result = @{ + found = $true + mainModule = $mainModule + modules = $modulePaths +} +Write-Output ($result | ConvertTo-Json -Compress -Depth 4) diff --git a/tools/daemon-relocation-spike/ndjson-client.mjs b/tools/daemon-relocation-spike/ndjson-client.mjs new file mode 100644 index 000000000..8919823e5 --- /dev/null +++ b/tools/daemon-relocation-spike/ndjson-client.mjs @@ -0,0 +1,262 @@ +// Minimal purpose-built NDJSON client for the daemon wire protocol. +// +// Deliberately standalone (no electron / src imports) so the spike runs under +// plain node. Mirrors the handshake in src/main/daemon/daemon-server.ts: +// 1. read the token the server wrote to after it began listening +// 2. control socket: send hello {role:'control'}, await {type:'hello',ok:true} +// 3. stream socket: send hello {role:'stream'} with the SAME clientId +// 4. createOrAttach on control, then write() input, read 'data' events on stream + +import { connect } from 'node:net' +import { readFileSync } from 'node:fs' +import { randomUUID } from 'node:crypto' + +function encodeNdjson(msg) { + return `${JSON.stringify(msg)}\n` +} + +// Split incoming bytes on newlines and dispatch each complete JSON line. +function makeLineReader(onMessage) { + let buffer = '' + return (chunk) => { + buffer += chunk.toString('utf8') + let idx = buffer.indexOf('\n') + while (idx !== -1) { + const line = buffer.slice(0, idx) + buffer = buffer.slice(idx + 1) + if (line.length > 0) { + onMessage(JSON.parse(line)) + } + idx = buffer.indexOf('\n') + } + } +} + +function connectSocket(socketPath, timeoutMs) { + return new Promise((resolve, reject) => { + const socket = connect(socketPath) + const timer = setTimeout(() => { + socket.destroy() + reject(new Error(`connect timeout after ${timeoutMs}ms: ${socketPath}`)) + }, timeoutMs) + socket.once('connect', () => { + clearTimeout(timer) + resolve(socket) + }) + socket.once('error', (err) => { + clearTimeout(timer) + reject(err) + }) + }) +} + +// Send a hello and resolve once the server accepts (or reject on rejection). +function handshake(socket, hello) { + return new Promise((resolve, reject) => { + const read = makeLineReader((msg) => { + if (msg.type === 'hello') { + if (msg.ok) { + resolve(read) + } else { + reject(new Error(`hello rejected: ${msg.error}`)) + } + } + }) + socket.on('data', read) + socket.write(encodeNdjson(hello)) + }) +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +// Strip CSI / OSC / two-char VT escapes so the marker regex can match executed +// PTY output that ConPTY interleaves with cursor-move and SGR color codes. +// eslint-disable-next-line no-control-regex -- ANSI escapes are control chars by definition +const ANSI_ESCAPE = /\[[0-9;?]*[ -/]*[@-~]|\][^]*?|[@-Z\\-_]/g + +function stripAnsi(text) { + return text.replace(ANSI_ESCAPE, '') +} + +// Race a promise against a timeout so a dead daemon can't wedge the failure +// path (an unanswered RPC would otherwise hang until the CI job limit). +function withTimeout(promise, ms, label) { + let timer + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms) + }) + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)) +} + +/** + * Connect a control+stream client, create a session, submit `command` + CR, and + * resolve once `expectRe` matches the accumulated PTY output (or reject on + * timeout). Returns { output, diagnostics } on success. On timeout/error the + * rejected Error carries `.diagnostics` and `.output` so the caller can tell + * "no session created" vs "session created but no output" vs "output arrived + * but the regex did not match". Always tears down its sockets. + */ +export async function runPtyEcho(options) { + const { + socketPath, + tokenPath, + protocolVersion, + command, + expectRe, + shellOverride, + connectTimeoutMs = 5000, + ioTimeoutMs = 20000, + // Why: PowerShell/PSReadLine needs a beat to initialize before it echoes + // typed input; writing the command the instant createOrAttach returns can + // race the shell's own startup so the keystrokes land before the prompt. + writeDelayMs = 400 + } = options + + const token = readFileSync(tokenPath, 'utf8').trim() + const clientId = randomUUID() + const sessionId = `spike-${randomUUID()}` + + // Everything we learn on the failure path, so the CI log can pinpoint where + // the ConPTY round-trip broke. + const diagnostics = { + createResponse: null, + ourDataFrames: 0, + otherDataFrames: 0, + exitEvents: [], + rawSample: '', + sessionsAtTimeout: null + } + + const control = await connectSocket(socketPath, connectTimeoutMs) + const stream = await connectSocket(socketPath, connectTimeoutMs) + const teardown = () => { + control.destroy() + stream.destroy() + } + + try { + const controlRead = await handshake(control, { + type: 'hello', + version: protocolVersion, + token, + clientId, + role: 'control' + }) + await handshake(stream, { + type: 'hello', + version: protocolVersion, + token, + clientId, + role: 'stream' + }) + + // Route control RPC responses by id. + const pending = new Map() + control.removeAllListeners('data') + control.on( + 'data', + makeLineReader((msg) => { + if (msg.id && pending.has(msg.id)) { + const { resolve, reject } = pending.get(msg.id) + pending.delete(msg.id) + if (msg.ok) { + resolve(msg.payload) + } else { + reject(new Error(msg.error)) + } + } + }) + ) + // The initial controlRead consumed only the hello; discard it now. + void controlRead + + const rpc = (type, payload) => { + const id = randomUUID() + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }) + control.write(encodeNdjson({ id, type, payload })) + }) + } + + return await new Promise((resolve, reject) => { + let output = '' + let settled = false + + const rejectWith = (err) => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + err.diagnostics = diagnostics + err.output = output + reject(err) + } + + const timer = setTimeout(() => { + // On timeout, ask the daemon what sessions it thinks exist — this + // distinguishes "session never created / already exited" from "session + // alive but silent". + withTimeout(rpc('listSessions'), 2000, 'listSessions') + .then((payload) => { + diagnostics.sessionsAtTimeout = payload?.sessions ?? payload + }) + .catch((err) => { + diagnostics.sessionsAtTimeout = `listSessions error: ${err.message}` + }) + .finally(() => { + rejectWith(new Error(`pty echo timeout after ${ioTimeoutMs}ms`)) + }) + }, ioTimeoutMs) + + stream.removeAllListeners('data') + stream.on( + 'data', + makeLineReader((msg) => { + if (msg.type === 'event' && msg.event === 'data') { + const data = msg.payload?.data ?? '' + if (diagnostics.rawSample.length < 500) { + diagnostics.rawSample = (diagnostics.rawSample + data).slice(0, 500) + } + if (msg.sessionId === sessionId) { + diagnostics.ourDataFrames++ + output += data + // Test against the ANSI-stripped stream: ConPTY interleaves the + // executed marker with cursor-move / SGR codes. + if (expectRe.test(stripAnsi(output)) && !settled) { + settled = true + clearTimeout(timer) + resolve({ output, diagnostics }) + } + } else { + diagnostics.otherDataFrames++ + } + } else if (msg.type === 'event' && msg.event === 'exit') { + diagnostics.exitEvents.push({ sessionId: msg.sessionId, code: msg.payload?.code }) + } + }) + ) + + const createPayload = { sessionId, cols: 120, rows: 30 } + if (shellOverride) { + createPayload.shellOverride = shellOverride + } + rpc('createOrAttach', createPayload) + .then((payload) => { + diagnostics.createResponse = payload + return delay(writeDelayMs) + }) + // Submit with a lone CR: PSReadLine treats CRLF as a soft newline + // (multiline continuation) and leaves the command typed but unexecuted; + // a bare CR is Enter. + .then(() => rpc('write', { sessionId, data: `${command}\r` })) + .catch((err) => { + rejectWith(err instanceof Error ? err : new Error(String(err))) + }) + }) + } finally { + teardown() + } +} diff --git a/tools/daemon-relocation-spike/selftest.mjs b/tools/daemon-relocation-spike/selftest.mjs new file mode 100644 index 000000000..520126716 --- /dev/null +++ b/tools/daemon-relocation-spike/selftest.mjs @@ -0,0 +1,166 @@ +// Offline validation of the spike's pure logic: argument parsing, tier +// definitions, the tier -> copy-plan resolver, and the app-dir module filter. +// No real build, copy, or launch. `runSelftest()` returns true on all-pass. + +import { parseArgs, TIERS } from './cli.mjs' +import { TIER_DEFINITIONS, selectTierDlls, resolveTierFileSet, GPU_DLLS } from './tier-file-set.mjs' +import { findAppDirResidentModules } from './loaded-module-probe.mjs' + +function makeSyntheticInventory() { + const unpackedRoot = 'C:\\App\\resources\\app.asar.unpacked' + const f = (path) => ({ path, exists: true, size: 1 }) + return { + appDir: 'C:\\App', + unpackedRoot, + hostExe: { name: 'Orca.exe', ...f('C:\\App\\Orca.exe') }, + runtimeData: [ + { name: 'icudtl.dat', ...f('C:\\App\\icudtl.dat') }, + { name: 'snapshot_blob.bin', ...f('C:\\App\\snapshot_blob.bin') }, + { name: 'v8_context_snapshot.bin', ...f('C:\\App\\v8_context_snapshot.bin') } + ], + topLevelDlls: [ + { name: 'ffmpeg.dll', ...f('C:\\App\\ffmpeg.dll') }, + { name: 'libEGL.dll', ...f('C:\\App\\libEGL.dll') }, + { name: 'libGLESv2.dll', ...f('C:\\App\\libGLESv2.dll') }, + { name: 'vk_swiftshader.dll', ...f('C:\\App\\vk_swiftshader.dll') }, + { name: 'vulkan-1.dll', ...f('C:\\App\\vulkan-1.dll') }, + { name: 'd3dcompiler_47.dll', ...f('C:\\App\\d3dcompiler_47.dll') } + ], + daemonEntry: { + name: 'daemon-entry.js', + path: `${unpackedRoot}\\out\\main\\daemon-entry.js`, + exists: true, + size: 1, + relFromUnpacked: 'out/main/daemon-entry.js' + }, + // node-pty is packaged at resources/node_modules/node-pty — a SIBLING of + // app.asar.unpacked, NOT under it (see packaged-runtime-node-modules.cjs). + // The synthetic inventory reflects that so the copy-plan test catches any + // regression that mislocates it. + nodePty: { + exists: true, + packageDir: 'C:\\App\\resources\\node_modules\\node-pty', + nativeDir: 'C:\\App\\resources\\node_modules\\node-pty\\build\\Release', + nativeRel: 'build/Release', + conptyNode: { name: 'conpty.node', path: 'x', exists: true, size: 1 } + } + } +} + +function run() { + const failures = [] + const check = (name, cond) => { + if (!cond) { + failures.push(name) + } + } + + // ── Argument parsing ──────────────────────────────────────────────── + check('help flag', parseArgs(['--help']).help === true) + check('selftest flag', parseArgs(['--selftest']).selftest === true) + check('missing app-dir errors', Boolean(parseArgs(['--work-dir', 'w']).error)) + check('missing work-dir errors', Boolean(parseArgs(['--app-dir', 'a']).error)) + check( + 'bad tier errors', + Boolean(parseArgs(['--app-dir', 'a', '--work-dir', 'w', '--tier', 'x']).error) + ) + check('unknown arg errors', Boolean(parseArgs(['--nope']).error)) + const ok = parseArgs(['--app-dir', 'a', '--work-dir', 'w', '--tier', 'no-gpu', '--keep-work-dir']) + check('valid parse launch', Boolean(ok.launch)) + check('valid parse tier', ok.launch?.tier === 'no-gpu') + check('valid parse keep', ok.launch?.keepWorkDir === true) + check( + 'default tier full', + parseArgs(['--app-dir', 'a', '--work-dir', 'w']).launch?.tier === 'full' + ) + + // ── Tier definitions ──────────────────────────────────────────────── + check( + 'all tiers defined', + TIERS.every((t) => Boolean(TIER_DEFINITIONS[t])) + ) + const dlls = makeSyntheticInventory().topLevelDlls + check('full keeps all dlls', selectTierDlls(dlls, 'full').length === 6) + check('minimal keeps no dlls', selectTierDlls(dlls, 'minimal').length === 0) + const noGpu = selectTierDlls(dlls, 'no-gpu').map((d) => d.name) + check('no-gpu keeps ffmpeg', noGpu.includes('ffmpeg.dll')) + check('no-gpu drops libEGL', !noGpu.includes('libEGL.dll')) + check( + 'no-gpu drops all gpu dlls', + noGpu.every((n) => !GPU_DLLS.has(n.toLowerCase())) + ) + check('no-gpu count is 1', noGpu.length === 1) + + // ── Copy-plan resolution ──────────────────────────────────────────── + const inv = makeSyntheticInventory() + for (const tier of TIERS) { + const plan = resolveTierFileSet(inv, tier) + check(`${tier}: no warnings`, plan.warnings.length === 0) + const dests = plan.ops.map((o) => o.destRel) + check(`${tier}: has exe`, dests.includes('Orca.exe')) + check(`${tier}: has icu`, dests.includes('icudtl.dat')) + // destRel mirrors the full win-unpacked layout so the require-closure and + // node-pty native resolution work verbatim from the copy. + check( + `${tier}: has daemon entry`, + dests.includes('resources/app.asar.unpacked/out/main/daemon-entry.js') + ) + check(`${tier}: has node-pty dir`, dests.includes('resources/node_modules/node-pty')) + check( + `${tier}: node-pty op is a dir`, + plan.ops.find((o) => o.destRel === 'resources/node_modules/node-pty')?.kind === 'dir' + ) + } + const fullDests = resolveTierFileSet(inv, 'full').ops.map((o) => o.destRel) + check('full plan includes gpu dll', fullDests.includes('vulkan-1.dll')) + const minimalDests = resolveTierFileSet(inv, 'minimal').ops.map((o) => o.destRel) + check('minimal plan excludes ffmpeg', !minimalDests.includes('ffmpeg.dll')) + check('minimal plan excludes gpu dll', !minimalDests.includes('vulkan-1.dll')) + + // Missing required input surfaces a warning rather than throwing. + const brokenInv = { ...inv, nodePty: { exists: false, conptyNode: null } } + check('missing node-pty warns', resolveTierFileSet(brokenInv, 'full').warnings.length > 0) + + // ── Module-path filter ────────────────────────────────────────────── + const appDir = 'C:\\Users\\me\\AppData\\Local\\Programs\\orca' + const modules = [ + 'C:\\Users\\me\\AppData\\Local\\Programs\\orca\\Orca.exe', + 'C:\\Windows\\System32\\kernel32.dll', + 'C:\\Users\\me\\AppData\\Local\\orca-daemon-host\\Orca.exe' + ] + const resident = findAppDirResidentModules(modules, appDir) + check('detects app-dir module', resident.length === 1) + check('detects the right module', resident[0].toLowerCase().includes('programs\\orca\\orca.exe')) + // Sibling-prefix must NOT match (C:\...\orca vs C:\...\orca-daemon-host). + check( + 'sibling prefix not matched', + findAppDirResidentModules(['C:\\a\\orca-daemon-host\\x.dll'], 'C:\\a\\orca').length === 0 + ) + // Forward/back-slash + case normalization. + check( + 'slash + case normalized', + findAppDirResidentModules(['c:/a/ORCA/x.dll'], 'C:\\A\\orca').length === 1 + ) + check( + 'relocated host has zero app-dir modules', + findAppDirResidentModules( + ['C:\\work\\daemon-host\\Orca.exe', 'C:\\Windows\\System32\\ntdll.dll'], + appDir + ).length === 0 + ) + + return failures +} + +export function runSelftest() { + const failures = run() + if (failures.length === 0) { + console.log('selftest: PASS (all checks green)') + return true + } + console.error(`selftest: FAIL (${failures.length} check(s))`) + for (const name of failures) { + console.error(` - ${name}`) + } + return false +} diff --git a/tools/daemon-relocation-spike/spike.mjs b/tools/daemon-relocation-spike/spike.mjs new file mode 100644 index 000000000..5ce1c9eac --- /dev/null +++ b/tools/daemon-relocation-spike/spike.mjs @@ -0,0 +1,313 @@ +// daemon-relocation-spike — empirically finds the minimal file set that lets a +// COPIED Orca.exe (ELECTRON_RUN_AS_NODE=1), launched from outside the install +// dir, host the terminal daemon + a real ConPTY session while holding no open +// handles into the app dir. See README.md. +// +// Requires a packaged win-unpacked build (runs on Windows CI). Use --selftest to +// validate the pure logic anywhere without a build. + +import { randomUUID } from 'node:crypto' +import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { join, relative } from 'node:path' +import { parseArgs, getUsage } from './cli.mjs' +import { inventoryAppDir, formatInventory } from './app-inventory.mjs' +import { resolveTierFileSet } from './tier-file-set.mjs' +import { copyHost } from './host-copy.mjs' +import { launchDaemonHost } from './daemon-launch.mjs' +import { runPtyEcho } from './ndjson-client.mjs' +import { assessDaemonHandles } from './loaded-module-probe.mjs' +import { runSelftest } from './selftest.mjs' + +const HERE = import.meta.dirname +const FALLBACK_PROTOCOL_VERSION = 18 + +// Read PROTOCOL_VERSION from the daemon source so the spike client never drifts +// out of sync with the running daemon's handshake. +function resolveProtocolVersion() { + try { + const typesPath = join(HERE, '..', '..', 'src', 'main', 'daemon', 'types.ts') + const match = readFileSync(typesPath, 'utf8').match(/PROTOCOL_VERSION\s*=\s*(\d+)/) + if (match) { + return Number(match[1]) + } + } catch { + // Fall through to the pinned default. + } + return FALLBACK_PROTOCOL_VERSION +} + +function makeSocketPath() { + if (process.platform === 'win32') { + return `\\\\?\\pipe\\orca-daemon-spike-${randomUUID().slice(0, 12)}` + } + return join(process.env.TMPDIR ?? '/tmp', `orca-daemon-spike-${randomUUID().slice(0, 12)}.sock`) +} + +/** Print a recursive listing of the copied daemon-host tree so the mirrored + * layout (daemon-entry + node-pty at their require-resolvable paths) is + * verifiable from the CI log. Depth-limited to keep output readable. */ +function printHostTree(hostRoot, maxDepth = 6) { + console.log(`\n--- copied daemon-host tree: ${hostRoot} ---`) + if (!existsSync(hostRoot)) { + console.log(' (missing)') + return + } + const walk = (dir, depth) => { + let entries = [] + try { + entries = readdirSync(dir, { withFileTypes: true }) + } catch { + return + } + for (const e of entries) { + const full = join(dir, e.name) + const rel = relative(hostRoot, full).split('\\').join('/') + if (e.isDirectory()) { + console.log(` ${rel}/`) + if (depth < maxDepth) { + walk(full, depth + 1) + } + } else { + console.log(` ${rel}`) + } + } + } + walk(hostRoot, 0) +} + +/** Dump the tail of the daemon's captured stdout/stderr — the actual crash + * reason when it exits before ready. */ +function printDaemonLogs(workDir, tailLines = 60) { + for (const name of ['daemon.log', 'daemon-stdout.log', 'daemon-stderr.log']) { + const p = join(workDir, name) + console.log(`\n--- ${name} ---`) + try { + const text = readFileSync(p, 'utf8').trimEnd() + const lines = text.split('\n') + console.log(lines.slice(-tailLines).join('\n') || '(empty)') + } catch { + console.log('(unavailable)') + } + } +} + +/** Print the raw-frame diagnostics the client collects so a failed ConPTY + * round-trip is classifiable from the CI log alone. */ +function printEchoDiagnostics(d) { + if (!d) { + console.log(' (no diagnostics captured)') + return + } + console.log(` createOrAttach response: ${JSON.stringify(d.createResponse)}`) + console.log(` data frames (our session): ${d.ourDataFrames}`) + console.log(` data frames (other sessions): ${d.otherDataFrames}`) + console.log(` exit events: ${JSON.stringify(d.exitEvents)}`) + if (d.sessionsAtTimeout !== null) { + console.log(` listSessions at timeout: ${JSON.stringify(d.sessionsAtTimeout)}`) + } + const sample = d.rawSample || '' + console.log(` raw stream sample (${sample.length} chars): ${JSON.stringify(sample)}`) +} + +async function shutdownDaemon(child) { + if (!child || child.exitCode !== null) { + return + } + await new Promise((resolve) => { + const timer = setTimeout(resolve, 5000) + child.once('exit', () => { + clearTimeout(timer) + resolve() + }) + try { + child.kill('SIGTERM') + } catch { + clearTimeout(timer) + resolve() + } + }) +} + +async function runLaunch(opts) { + const { appDir, workDir, tier, keepWorkDir } = opts + const report = { + tier, + ready: false, + ptyEchoOk: false, + mainModuleOk: false, + appDirModules: [], + warnings: [], + error: null + } + + console.log(`\n=== daemon-relocation-spike (tier=${tier}) ===\n`) + + const inv = inventoryAppDir(appDir) + console.log(formatInventory(inv)) + console.log('') + + const plan = resolveTierFileSet(inv, tier) + report.warnings = plan.warnings + console.log(`tier: ${plan.label} (${plan.ops.length} copy ops)`) + if (plan.warnings.length > 0) { + for (const w of plan.warnings) { + console.error(` WARNING: ${w}`) + } + report.error = 'incomplete file set for chosen tier' + return report + } + + const { hostRoot, hostExePath, daemonEntryPath, nodePtyNativeDir, skipped } = copyHost( + inv, + plan, + workDir + ) + if (skipped.length > 0) { + console.error(` copy skipped (missing sources): ${skipped.join(', ')}`) + report.error = `required sources missing: ${skipped.join(', ')}` + return report + } + console.log(`copied host: ${hostExePath}`) + console.log(`daemon entry: ${daemonEntryPath}`) + console.log(`node-pty native dir: ${nodePtyNativeDir || '(none)'}`) + printHostTree(hostRoot) + console.log('') + + const socketPath = makeSocketPath() + const tokenPath = join(workDir, 'daemon.token') + const logFilePath = join(workDir, 'daemon.log') + const protocolVersion = resolveProtocolVersion() + + let child = null + try { + const launched = await launchDaemonHost({ + hostExePath, + daemonEntryPath, + socketPath, + tokenPath, + workDir, + nodePtyNativeDir, + logFilePath + }) + child = launched.child + report.ready = true + console.log(`daemon ready (pid=${launched.pid})`) + + // Probe loaded modules BEFORE shutdown — the daemon and its node-pty native + // are mapped at this point. + const handles = assessDaemonHandles(launched.pid, appDir, hostExePath) + report.mainModuleOk = handles.mainModuleOk + report.appDirModules = handles.appDirModules + console.log( + `handle probe: mainModuleOk=${handles.mainModuleOk} ` + + `modules=${handles.moduleCount ?? 0} appDirResident=${handles.appDirModules.length}` + ) + for (const m of handles.appDirModules) { + console.error(` APP-DIR MODULE (would lock during update): ${m}`) + } + + const nonce = randomUUID().slice(0, 8) + const marker = `SPIKE-OK-${nonce}` + // Match the marker only when it appears alone at line start (executed + // output), not inside the echoed `echo ` input line. + const expectRe = new RegExp(`(?:^|\\r?\\n)${marker}(?:\\r|\\n)`) + // `echo ` is shell-agnostic (cmd / powershell / pwsh / bash); force + // powershell.exe so the CI runner's ambient COMSPEC can't pick a shell that + // behaves differently under ConPTY. + const echo = await runPtyEcho({ + socketPath, + tokenPath, + protocolVersion, + command: `echo ${marker}`, + expectRe, + shellOverride: process.platform === 'win32' ? 'powershell.exe' : undefined + }) + report.ptyEchoOk = true + console.log(`pty echo: nonce round-tripped (${echo.output.length} bytes of output)`) + console.log('pty echo diagnostics:') + printEchoDiagnostics(echo.diagnostics) + } catch (err) { + // Recover the handle from a pre-ready rejection so `finally` can stop a + // daemon that started but never signaled ready. + child = child ?? err?.child ?? null + report.error = err instanceof Error ? err.message : String(err) + console.error(`\nFAILURE: ${report.error}`) + if (err && err.diagnostics) { + console.error('pty echo diagnostics:') + printEchoDiagnostics(err.diagnostics) + } + printDaemonLogs(workDir) + } finally { + await shutdownDaemon(child) + if (!keepWorkDir) { + try { + rmSync(workDir, { recursive: true, force: true }) + } catch { + // Best-effort cleanup; a locked file just means the relocation is + // incomplete, which the handle probe already reports. + } + } + } + + return report +} + +function printFinalReport(report) { + const pass = + report.ready && + report.ptyEchoOk && + report.appDirModules.length === 0 && + report.mainModuleOk && + !report.error + + console.log('\n=== FINAL REPORT ===') + console.log(` tier: ${report.tier}`) + console.log(` daemon ready: ${report.ready}`) + console.log(` pty echo ok: ${report.ptyEchoOk}`) + console.log(` main module = copy: ${report.mainModuleOk}`) + console.log(` app-dir modules: ${report.appDirModules.length}`) + for (const m of report.appDirModules) { + console.log(` - ${m}`) + } + if (report.error) { + console.log(` error: ${report.error}`) + } + console.log(` VERDICT: ${pass ? 'PASS' : 'FAIL'}\n`) + return pass +} + +async function main() { + const parsed = parseArgs(process.argv.slice(2)) + + if (parsed.help) { + console.log(getUsage()) + return 0 + } + if (parsed.error) { + console.error(`error: ${parsed.error}`) + console.error(getUsage()) + return 2 + } + if (parsed.selftest) { + return runSelftest() ? 0 : 1 + } + + if (process.platform !== 'win32') { + console.error( + 'launch mode requires Windows (ConPTY + loaded-module probe). Use --selftest elsewhere.' + ) + return 2 + } + + const report = await runLaunch(parsed.launch) + return printFinalReport(report) ? 0 : 1 +} + +main() + .then((code) => { + process.exitCode = code + }) + .catch((err) => { + console.error('unexpected error:', err) + process.exitCode = 1 + }) diff --git a/tools/daemon-relocation-spike/tier-file-set.mjs b/tools/daemon-relocation-spike/tier-file-set.mjs new file mode 100644 index 000000000..312d9a6c8 --- /dev/null +++ b/tools/daemon-relocation-spike/tier-file-set.mjs @@ -0,0 +1,135 @@ +// Tier definitions as DATA, so trimming the copied file set is a config change +// rather than a code change. A tier resolves (given a discovered inventory) to a +// flat list of copy operations { sourcePath, destRel, kind }. + +import { dirname, join, relative, sep } from 'node:path' + +// GPU/render DLLs that a run-as-node Electron host plausibly never loads. The +// spike measures whether dropping them still yields a working ConPTY host. +// ffmpeg.dll is deliberately NOT here — it is kept in the no-gpu tier. +export const GPU_DLLS = new Set([ + 'libegl.dll', + 'libglesv2.dll', + 'vk_swiftshader.dll', + 'vulkan-1.dll', + 'd3dcompiler_47.dll' +]) + +// Each tier declares which top-level DLLs to include. The exe, runtime data +// blobs, daemon bundle, and node-pty are in every tier — they are the +// irreducible core (Orca.exe needs icu + snapshots even as node; the daemon +// needs its bundle; node-pty needs its native + conpty runtime). +export const TIER_DEFINITIONS = { + full: { label: 'TIER_FULL_RUNTIME', dlls: 'all' }, + 'no-gpu': { label: 'TIER_NO_GPU_DLLS', dlls: 'non-gpu' }, + minimal: { label: 'TIER_MINIMAL', dlls: 'none' } +} + +function isGpuDll(name) { + return GPU_DLLS.has(name.toLowerCase()) +} + +/** + * Which top-level DLL entries a tier keeps. Pure over the inventory's DLL list + * so selftest can exercise it without a real build. + */ +export function selectTierDlls(topLevelDlls, tier) { + const def = TIER_DEFINITIONS[tier] + if (!def || def.dlls === 'none') { + return [] + } + if (def.dlls === 'all') { + return topLevelDlls + } + return topLevelDlls.filter((e) => !isGpuDll(e.name)) +} + +/** + * A source file/dir's path relative to the win-unpacked root, normalized to '/'. + * + * Why relative to the APP DIR (not the app.asar.unpacked root): node-pty is + * packaged at resources/node_modules/node-pty (see + * config/packaged-runtime-node-modules.cjs), a SIBLING of app.asar.unpacked. + * The daemon resolves `require('node-pty')` by walking parent dirs up from + * resources/app.asar.unpacked/out/main/daemon-entry.js, which passes through + * resources/ and finds resources/node_modules/node-pty. Mirroring the full + * win-unpacked layout verbatim is the only copy that preserves that walk. + */ +export function toPosixRelative(appDir, absPath) { + return relative(appDir, absPath).split(sep).join('/') +} + +/** + * Build the ordered copy plan for a tier. Returns { ops, warnings } where each + * op is { sourcePath, destRel, kind: 'file' | 'dir' }. Every destRel mirrors the + * source's win-unpacked-relative path. Missing required inputs are surfaced as + * warnings rather than thrown, so the report stays complete. + */ +export function resolveTierFileSet(inv, tier) { + const ops = [] + const warnings = [] + const appDir = inv.appDir + + const addFile = (entry, requiredLabel, optional = false) => { + if (!entry || !entry.exists) { + if (requiredLabel) { + warnings.push(`missing required input: ${requiredLabel}`) + } + return + } + ops.push({ + sourcePath: entry.path, + destRel: toPosixRelative(appDir, entry.path), + kind: 'file', + optional + }) + } + + // Core: exe + runtime data blobs live next to Orca.exe in win-unpacked. + addFile(inv.hostExe, 'Orca.exe') + for (const entry of inv.runtimeData) { + addFile(entry, entry.name) + } + + // Top-level DLLs per tier. + for (const dll of selectTierDlls(inv.topLevelDlls, tier)) { + addFile(dll) + } + + // Daemon bundle: the entry, its sibling chunks/, and the unpacked + // out/package.json (CJS/ESM loader resolution). Mirror the layout verbatim. + if (inv.daemonEntry.exists && inv.unpackedRoot) { + addFile(inv.daemonEntry, 'daemon-entry.js') + const entryDir = dirname(inv.daemonEntry.path) + const chunksDir = join(entryDir, 'chunks') + ops.push({ + sourcePath: chunksDir, + destRel: toPosixRelative(appDir, chunksDir), + kind: 'dir', + optional: true + }) + const pkgJson = join(inv.unpackedRoot, 'out', 'package.json') + ops.push({ + sourcePath: pkgJson, + destRel: toPosixRelative(appDir, pkgJson), + kind: 'file', + optional: true + }) + } else { + warnings.push('missing required input: daemon-entry.js (+ chunks)') + } + + // node-pty package tree (native binding + conpty runtime), mirrored at its + // real win-unpacked path (resources/node_modules/node-pty). + if (inv.nodePty.exists && inv.nodePty.conptyNode) { + ops.push({ + sourcePath: inv.nodePty.packageDir, + destRel: toPosixRelative(appDir, inv.nodePty.packageDir), + kind: 'dir' + }) + } else { + warnings.push('missing required input: node-pty (with conpty.node)') + } + + return { ops, warnings, label: TIER_DEFINITIONS[tier].label } +} diff --git a/tools/repro-orchestration-long-prompt.mjs b/tools/repro-orchestration-long-prompt.mjs new file mode 100644 index 000000000..6951e29d1 --- /dev/null +++ b/tools/repro-orchestration-long-prompt.mjs @@ -0,0 +1,504 @@ +#!/usr/bin/env node +import { spawn } from 'node:child_process' +import { createHash, randomUUID } from 'node:crypto' +import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' + +const SCRIPT_PATH = import.meta.filename +const BEGIN = '\x1b[200~' +const END = '\x1b[201~' + +const DEFAULT_SIZE_KB = 80 +const DEFAULT_TIMEOUT_MS = 20_000 +const DEFAULT_MODE = 'codex-like' + +function argValue(name, fallback = undefined) { + const prefix = `--${name}=` + const inline = process.argv.find((arg) => arg.startsWith(prefix)) + if (inline) { + return inline.slice(prefix.length) + } + const index = process.argv.indexOf(`--${name}`) + if (index !== -1) { + return process.argv[index + 1] ?? fallback + } + return fallback +} + +function hasFlag(name) { + return process.argv.includes(`--${name}`) +} + +function parsePositiveInteger(name, fallback) { + const raw = argValue(name) + if (raw === undefined) { + return fallback + } + const value = Number(raw) + if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) { + throw new Error(`--${name} must be a positive integer`) + } + return value +} + +function shellQuote(value) { + if (process.platform === 'win32') { + return `"${String(value).replace(/"/g, '\\"')}"` + } + return `'${String(value).replace(/'/g, "'\\''")}'` +} + +function runCommand(command, args, options = {}) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + cwd: options.cwd, + env: options.env, + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true + }) + let stdout = '' + let stderr = '' + child.stdout.setEncoding('utf8') + child.stderr.setEncoding('utf8') + child.stdout.on('data', (chunk) => { + stdout += chunk + }) + child.stderr.on('data', (chunk) => { + stderr += chunk + }) + child.on('error', reject) + child.on('close', (code) => { + if (code === 0) { + resolve({ stdout, stderr }) + return + } + const error = new Error(`${command} ${args.join(' ')} exited ${code}`) + error.stdout = stdout + error.stderr = stderr + error.code = code + reject(error) + }) + }) +} + +function parseCliJson(output) { + const text = output.trim() + if (!text) { + throw new Error('CLI returned empty JSON output') + } + return JSON.parse(text) +} + +async function callOrca(cli, args, options = {}) { + const result = await runCommand(cli, [...args, '--json'], options) + const parsed = parseCliJson(result.stdout) + if (parsed.ok === false) { + throw new Error(parsed.error?.message ?? JSON.stringify(parsed.error)) + } + return parsed.result ?? parsed +} + +function buildLongSpec(sizeKb, marker) { + const targetBytes = sizeKb * 1024 + const header = [ + `ORCA_LONG_PROMPT_REPRO_START ${marker}`, + 'This task is intentionally long so orchestration dispatch crosses terminal input chunks.', + 'The receiver expects the end marker to arrive before the submit byte.' + ].join('\n') + const lines = [header] + let index = 0 + while ( + Buffer.byteLength(`${lines.join('\n')}\nORCA_LONG_PROMPT_REPRO_END ${marker}`, 'utf8') < + targetBytes + ) { + lines.push( + `line ${String(index).padStart(5, '0')} ${marker} ${'abcdefghijklmnopqrstuvwxyz 0123456789 '.repeat(3)}` + ) + index += 1 + } + lines.push(`ORCA_LONG_PROMPT_REPRO_END ${marker}`) + return lines.join('\n') +} + +function readNested(result, pathParts) { + let current = result + for (const part of pathParts) { + current = current?.[part] + } + return current +} + +async function waitForReport(reportPath, timeoutMs) { + const startedAt = Date.now() + let lastError = null + while (Date.now() - startedAt < timeoutMs) { + try { + return JSON.parse(await readFile(reportPath, 'utf8')) + } catch (error) { + lastError = error + await new Promise((resolve) => setTimeout(resolve, 200)) + } + } + const error = new Error(`Timed out waiting for report: ${reportPath}`) + error.cause = lastError + throw error +} + +async function tryCloseTerminal(cli, handle, cwd) { + if (!handle) { + return + } + try { + await callOrca(cli, ['terminal', 'close', '--terminal', handle], { cwd }) + } catch { + // Best-effort cleanup; the report is more useful than a close failure. + } +} + +async function parentMain() { + const cli = argValue('cli', process.env.ORCA_REPRO_CLI ?? 'orca') + const mode = argValue('mode', DEFAULT_MODE) + if (!new Set(['wire', 'codex-like']).has(mode)) { + throw new Error('--mode must be wire or codex-like') + } + const sizeKb = parsePositiveInteger('size-kb', DEFAULT_SIZE_KB) + const timeoutMs = parsePositiveInteger('timeout-ms', DEFAULT_TIMEOUT_MS) + const cwd = path.resolve(argValue('worktree', process.cwd())) + const keepTerminals = hasFlag('keep-terminals') + const discardReport = hasFlag('discard-report') + const marker = `marker_${randomUUID().replace(/-/g, '')}` + const spec = buildLongSpec(sizeKb, marker) + const tempDir = path.join(tmpdir(), `orca-orchestration-long-prompt-${process.pid}-${Date.now()}`) + await mkdir(tempDir, { recursive: true }) + const workerReportPath = path.join(tempDir, 'worker-report.json') + + console.log(`runtime: ${cli} status`) + await callOrca(cli, ['status'], { cwd }) + + const coordinator = await callOrca( + cli, + [ + 'terminal', + 'create', + '--worktree', + `path:${cwd}`, + '--title', + 'orchestration repro coordinator', + '--command', + `${shellQuote(process.execPath)} ${shellQuote(SCRIPT_PATH)} --fake-coordinator` + ], + { cwd } + ) + const coordinatorHandle = readNested(coordinator, ['terminal', 'handle']) + if (!coordinatorHandle) { + throw new Error('Could not create coordinator terminal') + } + + const workerCommand = [ + shellQuote(process.execPath), + shellQuote(SCRIPT_PATH), + '--fake-worker', + '--cli', + shellQuote(cli), + '--mode', + shellQuote(mode), + '--report', + shellQuote(workerReportPath), + '--marker', + shellQuote(marker), + '--timeout-ms', + String(timeoutMs) + ].join(' ') + const worker = await callOrca( + cli, + [ + 'terminal', + 'create', + '--worktree', + `path:${cwd}`, + '--title', + 'orchestration repro fake codex', + '--command', + workerCommand + ], + { cwd } + ) + const workerHandle = readNested(worker, ['terminal', 'handle']) + if (!workerHandle) { + throw new Error('Could not create worker terminal') + } + + let taskId = null + try { + await callOrca( + cli, + [ + 'terminal', + 'wait', + '--terminal', + workerHandle, + '--for', + 'tui-idle', + '--timeout-ms', + '10000' + ], + { cwd } + ) + const task = await callOrca( + cli, + [ + 'orchestration', + 'task-create', + '--spec', + spec, + '--task-title', + 'Long prompt repro', + '--display-name', + 'Long prompt repro' + ], + { cwd } + ) + taskId = readNested(task, ['task', 'id']) + if (!taskId) { + throw new Error('Could not create orchestration task') + } + + const dispatch = await callOrca( + cli, + [ + 'orchestration', + 'dispatch', + '--task', + taskId, + '--to', + workerHandle, + '--from', + coordinatorHandle, + '--inject' + ], + { cwd } + ) + const dispatchId = readNested(dispatch, ['dispatch', 'id']) + const report = await waitForReport(workerReportPath, timeoutMs) + const summary = { + mode, + sizeKb, + taskId, + dispatchId, + coordinatorHandle, + workerHandle, + reportPath: workerReportPath, + expectedMarker: marker, + expectedSpecBytes: Buffer.byteLength(spec, 'utf8'), + ...report + } + console.log(JSON.stringify(summary, null, 2)) + if (report.contractOk !== true) { + process.exitCode = 1 + } + } finally { + if (!keepTerminals) { + await tryCloseTerminal(cli, workerHandle, cwd) + await tryCloseTerminal(cli, coordinatorHandle, cwd) + } + if (discardReport) { + await rm(tempDir, { recursive: true, force: true }) + } + } +} + +function countUnframedLineBreaks(text) { + let inPaste = false + let count = 0 + for (let index = 0; index < text.length; index += 1) { + if (text.startsWith(BEGIN, index)) { + inPaste = true + index += BEGIN.length - 1 + continue + } + if (text.startsWith(END, index)) { + inPaste = false + index += END.length - 1 + continue + } + const char = text[index] + if (!inPaste && (char === '\n' || char === '\r')) { + count += 1 + } + } + return count +} + +function buildReport(payload, mode, marker) { + const firstSubmit = payload.indexOf(0x0d) + const body = firstSubmit === -1 ? payload : payload.subarray(0, firstSubmit) + const text = body.toString('utf8') + const hasBracketedPasteFrame = text.includes(BEGIN) && text.includes(END) + const hasSubmit = firstSubmit !== -1 + const rawContainsMarker = text.includes(marker) + const unframedLineBreaks = countUnframedLineBreaks(text) + const base = { + mode, + receivedBytesBeforeSubmit: body.length, + receivedSha256BeforeSubmit: createHash('sha256').update(body).digest('hex'), + hasSubmit, + rawContainsMarker, + hasBracketedPasteFrame, + unframedLineBreaks, + previewStart: text.slice(0, 120), + previewEnd: text.slice(-120) + } + if (mode === 'wire') { + return { + ...base, + contractOk: hasSubmit && rawContainsMarker + } + } + return { + ...base, + // Codex/Claude-like TUIs need generated multi-line prompts to arrive as + // one paste frame; unframed newlines are treated as live editor keys. + contractOk: hasSubmit && rawContainsMarker && hasBracketedPasteFrame && unframedLineBreaks === 0 + } +} + +function parseInjectedIds(text) { + return { + taskId: /Your task ID is:\s*(task_[A-Za-z0-9_]+)/.exec(text)?.[1] ?? null, + dispatchId: /--dispatch-id\s+(ctx_[A-Za-z0-9_]+)/.exec(text)?.[1] ?? null, + coordinatorHandle: /Your coordinator's terminal handle is:\s*([^\s]+)/.exec(text)?.[1] ?? null + } +} + +async function fakeWorkerMain() { + const cli = argValue('cli', process.env.ORCA_REPRO_CLI ?? 'orca') + const mode = argValue('mode', DEFAULT_MODE) + const reportPath = argValue('report') + const marker = argValue('marker') + const timeoutMs = parsePositiveInteger('timeout-ms', DEFAULT_TIMEOUT_MS) + if (!reportPath || !marker) { + throw new Error('--fake-worker requires --report and --marker') + } + + process.stdout.write('\x1b]0;codex ready\x07') + process.stdout.write('fake codex ready\n> ') + if (process.stdin.isTTY) { + process.stdin.setRawMode(true) + } + process.stdin.resume() + + const chunks = [] + let finished = false + async function sendWorkerDone(ids, report) { + if (!ids.taskId || !ids.dispatchId || !ids.coordinatorHandle) { + return { attempted: false, reason: 'missing-dispatch-identifiers' } + } + try { + await callOrca(cli, [ + 'orchestration', + 'send', + '--to', + ids.coordinatorHandle, + '--type', + 'worker_done', + '--subject', + report.contractOk + ? 'Harness observed safe prompt delivery' + : 'Harness reproduced unsafe prompt delivery', + '--body', + [ + `The fake worker received ${report.receivedBytesBeforeSubmit} bytes before submit.`, + `Bracketed paste frame present: ${String(report.hasBracketedPasteFrame)}.`, + `Unframed line breaks: ${String(report.unframedLineBreaks)}.` + ].join(' '), + '--task-id', + ids.taskId, + '--dispatch-id', + ids.dispatchId, + '--report-path', + reportPath + ]) + return { attempted: true, ok: true } + } catch (error) { + return { + attempted: true, + ok: false, + error: error instanceof Error ? error.message : String(error) + } + } + } + + const finish = async (reason) => { + if (finished) { + return + } + finished = true + const payload = Buffer.concat(chunks) + const report = { + reason, + ...buildReport(payload, mode, marker) + } + const ids = parseInjectedIds(payload.toString('utf8')) + report.parsedTaskId = ids.taskId + report.parsedDispatchId = ids.dispatchId + report.parsedCoordinatorHandle = ids.coordinatorHandle + report.workerDone = await sendWorkerDone(ids, report) + await writeFile(reportPath, JSON.stringify(report, null, 2)) + process.stdout.write( + `\nORCA_REPRO_REPORT ${report.contractOk ? 'ok' : 'failed'} ${reportPath}\n` + ) + process.exit(report.contractOk ? 0 : 7) + } + + const timer = setTimeout(() => { + finish('timeout').catch(() => process.exit(8)) + }, timeoutMs) + process.stdin.on('data', (chunk) => { + chunks.push(Buffer.from(chunk)) + if (Buffer.concat(chunks).includes(0x0d)) { + clearTimeout(timer) + finish('submit').catch(() => process.exit(8)) + } + }) +} + +function fakeCoordinatorMain() { + process.stdout.write('\x1b]0;orchestration repro coordinator\x07') + process.stdout.write('orchestration repro coordinator ready\n') + setInterval(() => {}, 60_000) +} + +async function main() { + if (hasFlag('help')) { + console.log(`Usage: + node tools/repro-orchestration-long-prompt.mjs [--mode codex-like|wire] [--size-kb 80] + +The parent mode requires a running Orca runtime and creates temporary Orca +terminals. The fake worker records whether orchestration dispatch delivered a +long prompt in a safe agent-input contract. + +Options: + --cli Orca CLI command (default: ORCA_REPRO_CLI or orca) + --worktree Worktree path for temporary terminals (default: cwd) + --timeout-ms Wait budget for terminal/report operations + --keep-terminals Leave temporary terminals open for inspection + --discard-report Delete the temporary JSON report after printing summary +`) + return + } + if (hasFlag('fake-worker')) { + await fakeWorkerMain() + return + } + if (hasFlag('fake-coordinator')) { + fakeCoordinatorMain() + return + } + await parentMain() +} + +main().catch((error) => { + console.error(error instanceof Error ? (error.stack ?? error.message) : error) + process.exit(1) +}) diff --git a/tools/repro-watcher-crash-7547/.gitignore b/tools/repro-watcher-crash-7547/.gitignore new file mode 100644 index 000000000..fd936c821 --- /dev/null +++ b/tools/repro-watcher-crash-7547/.gitignore @@ -0,0 +1 @@ +parcel-watcher-process.bundle.cjs diff --git a/tools/repro-watcher-crash-7547/README.md b/tools/repro-watcher-crash-7547/README.md new file mode 100644 index 000000000..8f8261995 --- /dev/null +++ b/tools/repro-watcher-crash-7547/README.md @@ -0,0 +1,50 @@ +# Repro harness: watcher.node main-process crash (issue #7547) + +Manual, Windows-focused harness for the `@parcel/watcher` native crash class +(`0xc0000409` fail-fast / `0xc0000005` AV in `watcher.node`; same family as +macOS #5377 and Linux #6635). Not run in CI — it deliberately crashes +processes and hammers the filesystem. + +All watched/churned directories live under `os.tmpdir()`, never the repo. + +## Reproduce the bug (in-process watcher, pre-fix architecture) + +``` +node tools/repro-watcher-crash-7547/run.cjs delete-root 3 15000 +``` + +Spawns `child.cjs`, which uses `@parcel/watcher` **in-process** the way +`filesystem-watcher.ts` did before the fix. Scenarios (arg 1): + +- `delete-root` — subscribe to worktree-like dirs, churn files, delete the + watched root mid-churn, unsubscribe (worktree deletion during agent writes). + Crashes in seconds on Windows. +- `unsub-churn` — rapid subscribe/unsubscribe cycles against live churn. + Also crashes: the trigger is `unsubscribe()` racing active event delivery + (`CancelIo` from the wrong thread leaves a pending `ReadDirectoryChangesW` + completion pointing at a freed `Subscription`). +- `worker-mix` — worker_threads sharing the process-global native `Watcher`. +- `del-nounsub` / `del-nochurn` / `del-1lane` — minimisation variants + (deletion without unsubscribe does NOT crash; unsubscribe is the trigger). +- `overflow`, `mixed`. + +A native crash surfaces as the child's exit code (`0xC0000409` = 3221226505, +`0xC0000005` = 3221225477) and the runner stops. + +## Verify the fix (out-of-process watcher) + +Build first so the forked entry exists, then run from the repo root: + +``` +npx electron-vite build +node tools/repro-watcher-crash-7547/fixed-child.cjs 15000 +``` + +`fixed-child.cjs` esbuild-bundles the real `src/main/ipc/parcel-watcher-process.ts` +client and runs the same `delete-root` + `unsub-churn` load through the forked +`out/main/parcel-watcher-process-entry.js`. Expected output: contained watcher +process crashes (counted, recovered by respawn+resubscribe, surfaced through +`onInterruption`), a final health check that sees live events, and exit 0. + +Exit codes: 0 pass · 5 watcher not functional at end · 6 in-process fallback +used (isolation not exercised) · 7 watchdog · 8 premature exit. diff --git a/tools/repro-watcher-crash-7547/child.cjs b/tools/repro-watcher-crash-7547/child.cjs new file mode 100644 index 000000000..d5a522c0b --- /dev/null +++ b/tools/repro-watcher-crash-7547/child.cjs @@ -0,0 +1,470 @@ +// Throwaway repro harness for issue #7547 — Windows main-process crash in +// @parcel/watcher (watcher.node, 0xc0000409 fail-fast). +// +// Runs ONE scenario in THIS process (the parent runner spawns us in a loop and +// watches our exit code). Each scenario mimics a real Orca usage pattern: +// +// delete-root — subscribe to worktree-like dirs, churn files, delete the +// watched root mid-churn (worktree deletion during agent +// writes). Exercises the WindowsBackend error path +// (handleWatcherError -> Watcher::notifyError on the backend +// thread). +// unsub-churn — rapid subscribe/unsubscribe cycles on dirs with live churn +// (worktree switching + 30s-grace teardown compressed). +// Exercises pending-ReadDirectoryChangesW teardown. +// worker-mix — worker_threads subscribe to the SAME dirs as the main env +// (desktop explorer watch + runtime file-watcher worker on one +// worktree). Workers exit cleanly, exit without unsubscribing, +// or are terminate()d — then new workers subscribe again so +// std::thread::id values recycle against the process-global +// shared native Watcher. +// overflow — one watched dir, massive delete/rename bursts with long +// file names to force ERROR_NOTIFY_ENUM_DIR ("Buffer +// overflow") on the backend thread. +// mixed — all of the above concurrently. +// +// Exit code 0 = survived the scenario. A native crash surfaces as the child's +// exit code (0xC0000409 = 3221226505) in the parent. +'use strict' + +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') +const { Worker, isMainThread, workerData } = require('node:worker_threads') + +const REPO_ROOT = path.resolve(__dirname, '..', '..') +// The exact bundled native module (@parcel/watcher 2.5.6 + watcher-win32-x64). +const watcherPath = path.join(REPO_ROOT, 'node_modules', '@parcel', 'watcher') + +// Mirrors buildParcelWatcherIgnoreOption(WATCHER_IGNORE_DIRS) on win32 — +// identical ignore set => identical native Watcher key => cross-env sharing. +const IGNORE_DIRS = [ + '.git', + 'node_modules', + 'dist', + 'build', + '.next', + '.cache', + 'target', + '.venv', + '__pycache__' +] +const IGNORE = IGNORE_DIRS.flatMap((dir) => [`**/${dir}`, `**/${dir}/**`]) +const OPTS = { ignore: IGNORE, backend: 'windows' } + +const stats = { + eventBatches: 0, + events: 0, + errors: 0, + errorMessages: new Map(), + subscribes: 0, + unsubscribes: 0, + workersSpawned: 0, + workersTerminated: 0 +} + +function log(msg) { + process.stderr.write(`[child ${process.pid}] ${msg}\n`) +} + +function recordError(err) { + stats.errors++ + const msg = String((err && err.message) || err) + stats.errorMessages.set(msg, (stats.errorMessages.get(msg) || 0) + 1) +} + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const rand = (n) => Math.floor(Math.random() * n) + +function makeTree(dir, files, subdirs, nameLen) { + fs.mkdirSync(dir, { recursive: true }) + const dirs = [dir] + for (let d = 0; d < subdirs; d++) { + const sub = path.join(dir, `sub-${d}`) + fs.mkdirSync(sub, { recursive: true }) + dirs.push(sub) + } + let made = 0 + for (const d of dirs) { + for (let f = 0; f < Math.ceil(files / dirs.length); f++) { + const pad = 'x'.repeat(Math.max(0, nameLen - 12)) + fs.writeFileSync(path.join(d, `f${f}-${pad}.txt`), 'seed') + made++ + } + } + return made +} + +function rmrf(dir) { + try { + fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 10 }) + } catch { + // Watched dirs can be locked mid-delete on Windows; partial deletes still + // generate the event storm we want. + } +} + +// ── Churn worker (same file, worker_threads entry) ─────────────────── + +if (!isMainThread && workerData && workerData.role === 'churn') { + // Tight synchronous churn: create/write/rename/delete inside dir until told + // to stop (dir disappearing is fine — keep going, that's the scenario). + const { dir, durationMs } = workerData + const end = Date.now() + durationMs + let i = 0 + while (Date.now() < end) { + const a = path.join(dir, `churn-${i % 200}.txt`) + const b = path.join(dir, `churn-${i % 200}.renamed.txt`) + try { + fs.writeFileSync(a, `payload-${i}`) + fs.renameSync(a, b) + fs.rmSync(b, { force: true }) + } catch { + // Root may be mid-delete; recreate it occasionally to keep churn alive. + if (i % 500 === 0) { + try { + fs.mkdirSync(dir, { recursive: true }) + } catch {} + } + } + i++ + } + process.exit(0) +} + +if (!isMainThread && workerData && workerData.role === 'subscriber') { + // Mimics file-watcher-worker.ts: subscribe in a worker env to the SAME dir + // the main env watches, then tear down per `mode`. + const { dir, mode, holdMs } = workerData + const watcher = require(watcherPath) + ;(async () => { + let sub + try { + sub = await watcher.subscribe(dir, () => {}, OPTS) + } catch { + process.exit(0) + } + await sleep(holdMs) + if (mode === 'clean') { + try { + await sub.unsubscribe() + } catch {} + process.exit(0) + } + if (mode === 'dirty-exit') { + // Exit the worker env WITHOUT unsubscribing — leaves the callback ref + // registered in the process-global shared native Watcher. + process.exit(0) + } + // mode === 'wait-terminate': linger; the main thread terminate()s us, + // possibly while the subscription (or its unsubscribe) is in flight. + await sleep(60_000) + })() +} + +// ── Scenarios (main thread) ────────────────────────────────────────── + +async function scenarioDeleteRoot(watcher, baseDir, durationMs, lane) { + const end = Date.now() + durationMs + let round = 0 + while (Date.now() < end) { + const dir = path.join(baseDir, `wt-${lane}-${round}`) + makeTree(dir, 120, 4, 20) + let sub = null + let errored = false + try { + stats.subscribes++ + sub = await watcher.subscribe( + dir, + (err, events) => { + if (err) { + recordError(err) + errored = true + // Orca's createWatcher error path: unsubscribe from inside the + // error callback. + if (sub) { + stats.unsubscribes++ + sub.unsubscribe().catch(() => {}) + } + return + } + stats.eventBatches++ + stats.events += events.length + }, + OPTS + ) + } catch (err) { + recordError(err) + rmrf(dir) + round++ + continue + } + // Churn briefly, then delete the watched root while events are flowing. + const churn = new Worker(__filename, { + workerData: { role: 'churn', dir, durationMs: 300 } + }) + await sleep(50 + rand(100)) + rmrf(dir) + await sleep(rand(60)) + if (!errored && sub) { + stats.unsubscribes++ + await sub.unsubscribe().catch(() => {}) + } + await new Promise((r) => churn.once('exit', r)) + rmrf(dir) + round++ + } +} + +async function scenarioUnsubChurn(watcher, baseDir, durationMs, lane) { + const dir = path.join(baseDir, `unsub-${lane}`) + makeTree(dir, 150, 3, 20) + const churn = new Worker(__filename, { + workerData: { role: 'churn', dir, durationMs } + }) + const end = Date.now() + durationMs + while (Date.now() < end) { + let sub + try { + stats.subscribes++ + sub = await watcher.subscribe( + dir, + (err, events) => { + if (err) { + recordError(err) + return + } + stats.eventBatches++ + stats.events += events.length + }, + OPTS + ) + } catch (err) { + recordError(err) + continue + } + await sleep(rand(50)) + stats.unsubscribes++ + // Half the time don't await — overlapping unsubscribe with the next + // subscribe on the same dir, like racing grace-teardown vs re-watch. + if (rand(2) === 0) { + await sub.unsubscribe().catch(() => {}) + } else { + sub.unsubscribe().catch(() => {}) + } + } + await new Promise((r) => churn.once('exit', r)) + rmrf(dir) +} + +async function scenarioWorkerMix(watcher, baseDir, durationMs, lane) { + const dir = path.join(baseDir, `wmix-${lane}`) + makeTree(dir, 100, 3, 20) + // Main env holds a long-lived subscription (desktop explorer watch). + let mainSub = null + try { + stats.subscribes++ + mainSub = await watcher.subscribe( + dir, + (err, events) => { + if (err) { + recordError(err) + return + } + stats.eventBatches++ + stats.events += events.length + }, + OPTS + ) + } catch (err) { + recordError(err) + } + const churn = new Worker(__filename, { + workerData: { role: 'churn', dir, durationMs } + }) + const end = Date.now() + durationMs + while (Date.now() < end) { + const mode = ['clean', 'dirty-exit', 'wait-terminate'][rand(3)] + const worker = new Worker(__filename, { + workerData: { role: 'subscriber', dir, mode, holdMs: rand(150) } + }) + stats.workersSpawned++ + const exited = new Promise((r) => worker.once('exit', r)) + worker.once('error', () => {}) + if (mode === 'wait-terminate') { + await sleep(rand(100)) + stats.workersTerminated++ + await worker.terminate().catch(() => {}) + } + await Promise.race([exited, sleep(1000)]) + } + await new Promise((r) => churn.once('exit', r)) + if (mainSub) { + stats.unsubscribes++ + await mainSub.unsubscribe().catch(() => {}) + } + rmrf(dir) +} + +async function scenarioOverflow(watcher, baseDir, durationMs, lane) { + const end = Date.now() + durationMs + let round = 0 + while (Date.now() < end) { + const dir = path.join(baseDir, `ovf-${lane}-${round}`) + // Long names fill the 1MB ReadDirectoryChangesW buffer faster. + makeTree(dir, 4000, 8, 180) + let sub = null + try { + stats.subscribes++ + sub = await watcher.subscribe( + dir, + (err, events) => { + if (err) { + recordError(err) + if (sub) { + stats.unsubscribes++ + sub.unsubscribe().catch(() => {}) + } + return + } + stats.eventBatches++ + stats.events += events.length + }, + OPTS + ) + } catch (err) { + recordError(err) + rmrf(dir) + round++ + continue + } + // Parallel delete storm: multiple churn workers + recursive delete produce + // a dense event burst while the backend thread stats each event. + const churners = Array.from( + { length: 3 }, + () => new Worker(__filename, { workerData: { role: 'churn', dir, durationMs: 500 } }) + ) + rmrf(dir) + await Promise.all(churners.map((w) => new Promise((r) => w.once('exit', r)))) + if (sub) { + stats.unsubscribes++ + await sub.unsubscribe().catch(() => {}) + } + rmrf(dir) + round++ + } +} + +// Minimisation variants of delete-root, to isolate which ingredient crashes: +// del-nounsub — subscribe, churn, delete root; NEVER call unsubscribe. +// del-nochurn — subscribe, delete root; no churn worker at all. +// del-1lane — the full delete-root pattern but a single sequential lane. +async function scenarioDeleteMinimal(watcher, baseDir, durationMs, lane, { churn, unsub }) { + const end = Date.now() + durationMs + let round = 0 + while (Date.now() < end) { + const dir = path.join(baseDir, `min-${lane}-${round}`) + makeTree(dir, 120, 4, 20) + let sub = null + try { + stats.subscribes++ + sub = await watcher.subscribe( + dir, + (err, events) => { + if (err) { + recordError(err) + return + } + stats.eventBatches++ + stats.events += events.length + }, + OPTS + ) + } catch (err) { + recordError(err) + rmrf(dir) + round++ + continue + } + let churnWorker = null + if (churn) { + churnWorker = new Worker(__filename, { + workerData: { role: 'churn', dir, durationMs: 300 } + }) + await sleep(50 + rand(100)) + } + rmrf(dir) + await sleep(100) + if (unsub && sub) { + stats.unsubscribes++ + await sub.unsubscribe().catch(() => {}) + } + if (churnWorker) { + await new Promise((r) => churnWorker.once('exit', r)) + } + rmrf(dir) + round++ + } +} + +const SCENARIOS = { + 'delete-root': { fn: scenarioDeleteRoot, lanes: 6 }, + 'del-nounsub': { + fn: (w, b, d, l) => scenarioDeleteMinimal(w, b, d, l, { churn: true, unsub: false }), + lanes: 6 + }, + 'del-nochurn': { + fn: (w, b, d, l) => scenarioDeleteMinimal(w, b, d, l, { churn: false, unsub: false }), + lanes: 6 + }, + 'del-1lane': { + fn: (w, b, d, l) => scenarioDeleteMinimal(w, b, d, l, { churn: true, unsub: true }), + lanes: 1 + }, + 'unsub-churn': { fn: scenarioUnsubChurn, lanes: 6 }, + 'worker-mix': { fn: scenarioWorkerMix, lanes: 4 }, + overflow: { fn: scenarioOverflow, lanes: 2 } +} + +async function main() { + const scenarioName = process.argv[2] || 'mixed' + const durationMs = Number(process.argv[3] || 15000) + // Outside the repo worktree: a live Orca instance may be watching the repo, + // and this churn must not feed the production watcher. + const baseDir = path.join(os.tmpdir(), 'orca-7547-harness', `run-${process.pid}`) + fs.mkdirSync(baseDir, { recursive: true }) + + const watcher = require(watcherPath) + const jobs = [] + const names = scenarioName === 'mixed' ? Object.keys(SCENARIOS) : [scenarioName] + for (const name of names) { + const s = SCENARIOS[name] + if (!s) { + log(`unknown scenario: ${name}`) + process.exit(2) + } + const lanes = scenarioName === 'mixed' ? Math.max(1, Math.floor(s.lanes / 2)) : s.lanes + for (let lane = 0; lane < lanes; lane++) { + jobs.push(s.fn(watcher, baseDir, durationMs, lane)) + } + } + await Promise.all(jobs) + + const errs = Array.from(stats.errorMessages.entries()) + .map(([m, n]) => `${n}x "${m}"`) + .join(', ') + log( + `done: subs=${stats.subscribes} unsubs=${stats.unsubscribes} batches=${stats.eventBatches} ` + + `events=${stats.events} errors=${stats.errors} workers=${stats.workersSpawned} ` + + `terminated=${stats.workersTerminated}${errs ? ` errMsgs: ${errs}` : ''}` + ) + rmrf(baseDir) + process.exit(0) +} + +if (isMainThread) { + main().catch((err) => { + log(`harness error: ${err && err.stack}`) + process.exit(3) + }) +} diff --git a/tools/repro-watcher-crash-7547/fixed-child.cjs b/tools/repro-watcher-crash-7547/fixed-child.cjs new file mode 100644 index 000000000..f45d65bc7 --- /dev/null +++ b/tools/repro-watcher-crash-7547/fixed-child.cjs @@ -0,0 +1,334 @@ +// Fixed-architecture harness for issue #7547: runs the SAME scenarios that +// crash the in-process watcher (see child.cjs), but through the real +// parcel-watcher-process client (esbuild-bundled from src/main/ipc) which +// forks the real out/main/parcel-watcher-process-entry.js. +// +// Success = this process exits 0 (the app-process stand-in survived), the +// watcher stayed functional (final health check receives a live event), and +// no in-process fallback was used. Contained watcher-child crashes are +// EXPECTED and counted — they prove the native bug still fires but no longer +// reaches the host. +// +// Must be run with cwd = repo root (entry path resolves against cwd). +'use strict' + +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') +const { Worker, isMainThread, workerData } = require('node:worker_threads') + +const REPO_ROOT = path.resolve(__dirname, '..', '..') + +// The real host client, bundled on demand so the harness always exercises the +// current src/main/ipc/parcel-watcher-process.ts. +const bundlePath = path.join(__dirname, 'parcel-watcher-process.bundle.cjs') +if (isMainThread) { + const clientSrc = path.join(REPO_ROOT, 'src', 'main', 'ipc', 'parcel-watcher-process.ts') + if ( + !fs.existsSync(bundlePath) || + fs.statSync(bundlePath).mtimeMs < fs.statSync(clientSrc).mtimeMs + ) { + require('node:child_process').execSync( + `npx esbuild ${JSON.stringify(clientSrc)} --bundle --platform=node --format=cjs ` + + `--external:electron --external:@parcel/watcher --outfile=${JSON.stringify(bundlePath)}`, + { cwd: REPO_ROOT, stdio: 'inherit' } + ) + } + const entry = path.join(process.cwd(), 'out', 'main', 'parcel-watcher-process-entry.js') + if (!fs.existsSync(entry)) { + process.stderr.write( + `[fixed-harness] missing ${entry}\nRun from the repo root after building (npx electron-vite build).\n` + ) + process.exit(2) + } +} +const client = require(bundlePath) + +const IGNORE_DIRS = [ + '.git', + 'node_modules', + 'dist', + 'build', + '.next', + '.cache', + 'target', + '.venv', + '__pycache__' +] +const OPTS = { + ignore: IGNORE_DIRS.flatMap((dir) => [`**/${dir}`, `**/${dir}/**`]), + backend: 'windows' +} + +const stats = { + subscribes: 0, + unsubscribes: 0, + events: 0, + watchErrors: 0, + interruptions: 0, + containedCrashes: 0, + fallbackDetected: false +} + +// The client reports child crashes / fallback via console.error|warn — hook +// them to count contained crashes and detect a broken (in-process) setup. +const realError = console.error.bind(console) +console.error = (...args) => { + const line = args.map(String).join(' ') + if (line.includes('[parcel-watcher-process] watcher process exited')) { + stats.containedCrashes++ + } + realError(...args) +} +const realWarn = console.warn.bind(console) +console.warn = (...args) => { + const line = args.map(String).join(' ') + if (line.includes('using in-process watcher')) { + stats.fallbackDetected = true + } + realWarn(...args) +} + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const rand = (n) => Math.floor(Math.random() * n) + +function makeTree(dir, files, subdirs) { + fs.mkdirSync(dir, { recursive: true }) + const dirs = [dir] + for (let d = 0; d < subdirs; d++) { + const sub = path.join(dir, `sub-${d}`) + fs.mkdirSync(sub, { recursive: true }) + dirs.push(sub) + } + for (const d of dirs) { + for (let f = 0; f < Math.ceil(files / dirs.length); f++) { + fs.writeFileSync(path.join(d, `f${f}.txt`), 'seed') + } + } +} + +function rmrf(dir) { + try { + fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 10 }) + } catch {} +} + +if (!isMainThread && workerData && workerData.role === 'churn') { + const { dir, durationMs } = workerData + const end = Date.now() + durationMs + let i = 0 + while (Date.now() < end) { + const a = path.join(dir, `churn-${i % 200}.txt`) + const b = path.join(dir, `churn-${i % 200}.renamed.txt`) + try { + fs.writeFileSync(a, `payload-${i}`) + fs.renameSync(a, b) + fs.rmSync(b, { force: true }) + } catch { + if (i % 500 === 0) { + try { + fs.mkdirSync(dir, { recursive: true }) + } catch {} + } + } + i++ + } + process.exit(0) +} + +function subscribeLikeOrca(dir) { + let subRef = { current: null } + stats.subscribes++ + return client + .subscribeViaWatcherProcess( + dir, + (err, events) => { + if (err) { + stats.watchErrors++ + // Orca's error path: unsubscribe from inside the error callback. + if (subRef.current) { + stats.unsubscribes++ + subRef.current.unsubscribe().catch(() => {}) + subRef.current = null + } + return + } + stats.events += events.length + }, + OPTS, + () => { + stats.interruptions++ + } + ) + .then((sub) => { + subRef.current = sub + return subRef + }) +} + +async function deleteRootLane(baseDir, durationMs, lane) { + const end = Date.now() + durationMs + let round = 0 + while (Date.now() < end) { + const dir = path.join(baseDir, `wt-${lane}-${round}`) + makeTree(dir, 120, 4) + let subRef + try { + subRef = await subscribeLikeOrca(dir) + } catch { + rmrf(dir) + round++ + continue + } + const churn = new Worker(__filename, { + workerData: { role: 'churn', dir, durationMs: 300 } + }) + // Attach at spawn: a listener added after the worker already exited never + // fires, which hangs the lane (or lets the process exit 0 mid-run). + const churnDone = new Promise((r) => churn.once('exit', r)) + await sleep(50 + rand(100)) + rmrf(dir) + await sleep(rand(60)) + if (subRef.current) { + stats.unsubscribes++ + await subRef.current.unsubscribe().catch(() => {}) + subRef.current = null + } + await churnDone + rmrf(dir) + round++ + } +} + +async function unsubChurnLane(baseDir, durationMs, lane) { + const dir = path.join(baseDir, `unsub-${lane}`) + makeTree(dir, 150, 3) + const churn = new Worker(__filename, { + workerData: { role: 'churn', dir, durationMs } + }) + const churnDone = new Promise((r) => churn.once('exit', r)) + const end = Date.now() + durationMs + while (Date.now() < end) { + let subRef + try { + subRef = await subscribeLikeOrca(dir) + } catch { + await sleep(20) + continue + } + await sleep(rand(50)) + if (subRef.current) { + stats.unsubscribes++ + const p = subRef.current.unsubscribe().catch(() => {}) + subRef.current = null + if (rand(2) === 0) { + await p + } + } + } + await churnDone + rmrf(dir) +} + +// Health check must outlast the client's 30s crash-loop cooldown: if the +// breaker tripped during the scenarios, watching is expected to recover on a +// later subscribe, and THAT is what we verify. +async function finalHealthCheck(baseDir) { + const deadline = Date.now() + 45_000 + let attempt = 0 + while (Date.now() < deadline) { + attempt++ + const dir = path.join(baseDir, `health-${attempt}`) + makeTree(dir, 5, 0) + let gotEvent = false + let sub = null + try { + sub = await client.subscribeViaWatcherProcess(dir, (err, events) => { + if (!err && events.length > 0) { + gotEvent = true + } + }, OPTS) + } catch (err) { + process.stderr.write(`[fixed-harness] health subscribe attempt ${attempt} failed: ${err.message}\n`) + rmrf(dir) + await sleep(5000) + continue + } + const probeDeadline = Date.now() + 8000 + while (!gotEvent && Date.now() < probeDeadline) { + fs.writeFileSync(path.join(dir, 'probe.txt'), `probe-${Date.now()}`) + await sleep(200) + } + await sub.unsubscribe().catch(() => {}) + rmrf(dir) + if (gotEvent) { + return true + } + process.stderr.write(`[fixed-harness] health attempt ${attempt}: no events in 8s; retrying\n`) + await sleep(3000) + } + return false +} + +let completed = false + +async function main() { + const durationMs = Number(process.argv[2] || 15000) + const baseDir = path.join(os.tmpdir(), 'orca-7547-harness-fixed', `run-${process.pid}`) + fs.mkdirSync(baseDir, { recursive: true }) + + // Watchdog: a stuck lane must fail loudly, and a premature natural exit + // (empty event loop) must not read as success. + const watchdog = setTimeout(() => { + process.stderr.write('[fixed-harness] FAIL: watchdog — scenarios did not complete\n') + process.exit(7) + }, durationMs * 4 + 60_000) + process.on('exit', (code) => { + if (!completed && code === 0) { + process.exitCode = 8 + process.stderr.write('[fixed-harness] FAIL: premature exit before completion\n') + } + }) + + const lanes = [] + for (let lane = 0; lane < 6; lane++) { + lanes.push(deleteRootLane(baseDir, durationMs, lane)) + } + for (let lane = 0; lane < 6; lane++) { + lanes.push(unsubChurnLane(baseDir, durationMs, lane)) + } + await Promise.all(lanes) + + const healthy = await finalHealthCheck(baseDir) + client.disposeWatcherProcess() + rmrf(baseDir) + completed = true + clearTimeout(watchdog) + + // Summary via stderr + exitCode (not process.exit): stdout writes to a pipe + // are async on Windows and process.exit() drops them. + process.stderr.write( + `[fixed-harness] subs=${stats.subscribes} unsubs=${stats.unsubscribes} events=${stats.events} ` + + `watchErrors=${stats.watchErrors} containedCrashes=${stats.containedCrashes} ` + + `interruptions=${stats.interruptions} healthy=${healthy} fallback=${stats.fallbackDetected}\n` + ) + if (stats.fallbackDetected) { + process.stderr.write('[fixed-harness] FAIL: in-process fallback used — isolation not exercised\n') + process.exitCode = 6 + return + } + if (!healthy) { + process.stderr.write('[fixed-harness] FAIL: watcher not functional after scenarios\n') + process.exitCode = 5 + return + } + process.stderr.write('[fixed-harness] PASS: host survived; watcher functional\n') + process.exitCode = 0 +} + +if (isMainThread) { + main().catch((err) => { + console.error('[fixed-harness] harness error:', err) + process.exit(3) + }) +} diff --git a/tools/repro-watcher-crash-7547/run.cjs b/tools/repro-watcher-crash-7547/run.cjs new file mode 100644 index 000000000..0d10b56a2 --- /dev/null +++ b/tools/repro-watcher-crash-7547/run.cjs @@ -0,0 +1,74 @@ +// Parent runner for the #7547 watcher.node crash harness. Spawns child.cjs in +// a loop and reports native crash exit codes (0xC0000409 fail-fast, 0xC0000005 +// AV, etc.). Usage: +// node run.cjs [iterations] [durationMs] +'use strict' + +const { spawn } = require('node:child_process') +const path = require('node:path') + +const CHILD = path.join(__dirname, 'child.cjs') +const KNOWN = { + 3221226505: 'STATUS_STACK_BUFFER_OVERRUN (0xC0000409) — fail-fast/abort << TARGET', + 3221225477: 'STATUS_ACCESS_VIOLATION (0xC0000005)', + 3221225725: 'STATUS_STACK_OVERFLOW (0xC00000FD)', + 3221226356: 'STATUS_HEAP_CORRUPTION (0xC0000374)', + 134: 'SIGABRT (128+6)' +} + +function hex(code) { + return code >= 0 ? `0x${code.toString(16).toUpperCase()}` : String(code) +} + +function runOnce(scenario, durationMs) { + return new Promise((resolve) => { + const child = spawn(process.execPath, [CHILD, scenario, String(durationMs)], { + stdio: ['ignore', 'inherit', 'pipe'] + }) + let stderr = '' + child.stderr.on('data', (d) => { + stderr += d + process.stderr.write(d) + }) + child.on('exit', (code, signal) => resolve({ code, signal, stderr })) + }) +} + +async function main() { + const scenario = process.argv[2] || 'mixed' + const iterations = Number(process.argv[3] || 10) + const durationMs = Number(process.argv[4] || 15000) + const scenarios = + scenario === 'all' + ? ['delete-root', 'unsub-churn', 'worker-mix', 'overflow', 'mixed'] + : [scenario] + + const results = [] + let crashed = false + outer: for (const s of scenarios) { + for (let i = 1; i <= iterations; i++) { + const started = Date.now() + console.log(`\n=== [${s}] iteration ${i}/${iterations} (${durationMs}ms) ===`) + const { code, signal } = await runOnce(s, durationMs) + const elapsed = Date.now() - started + const meaning = KNOWN[code] || (code === 0 ? 'clean exit' : 'unexpected') + console.log(`=== [${s}] iter ${i}: exit=${code} (${hex(code ?? -1)}) signal=${signal} ${meaning} after ${elapsed}ms`) + results.push({ scenario: s, iteration: i, code, signal, elapsed }) + if (code !== 0 && code !== null) { + crashed = true + console.log(`\n*** NATIVE CRASH REPRODUCED in scenario "${s}" (exit ${hex(code)}) ***`) + break outer + } + } + } + + console.log('\n──── summary ────') + for (const r of results) { + console.log( + `${r.scenario.padEnd(12)} #${r.iteration} exit=${hex(r.code ?? -1)} ${r.signal || ''} ${r.elapsed}ms` + ) + } + process.exit(crashed ? 1 : 0) +} + +main() diff --git a/tools/win-update-e2e/README.md b/tools/win-update-e2e/README.md new file mode 100644 index 000000000..973958a8b --- /dev/null +++ b/tools/win-update-e2e/README.md @@ -0,0 +1,215 @@ +# win-update-e2e — packaged NSIS update proof harness + +**Windows only.** Given two Orca Windows installers (version N and N+1), this +harness performs a real silent update and proves, with machine-checkable +assertions, what happens to the terminal **daemon** and its **sessions** across +the update — and whether any console/terminal window flashes. + +It is the Phase 0 "proof harness" deliverable from +[`docs/windows-terminal-update-survival-plan.md`](../../docs/windows-terminal-update-survival-plan.md). +It exists specifically because the July 2026 attempt shipped four broken RCs +without ever installing the packaged artifact (see +[`docs/windows-terminal-update-survival-postmortem.md`](../../docs/windows-terminal-update-survival-postmortem.md), +"Why verification missed every one of these"). Its design refuses to repeat +those verification failures: + +- **Window visibility is measured by window enumeration + owner/canary + attribution — never by conhost command-line heuristics.** The post-mortem + proved conhost flags invert with parent console state and `MainWindowHandle` + is `0` for Windows-Terminal-hosted consoles. See `window-enum.ps1`. +- **Interactivity is proven by execution, not by result-shape.** Typed commands + write sentinel **files**; the harness checks the files. A command that "runs + and returns correct output" but flashes a window is still caught, because the + window watch runs independently. +- **The daemon is identified by command-line marker, never by exe name.** With + `ELECTRON_RUN_AS_NODE` the daemon image is `Orca.exe`; a relocated Phase 1 + host may be a differently-named copied binary. See `daemon-processes.mjs`. +- **Each run uses an isolated userData dir** so its daemon's socket/token path + is unique and never collides with the many other daemons a dev box or CI + runner can host. + +## Usage + +``` +pnpm win-update-e2e --from --to --expect +# or download release assets via gh (one call each): +pnpm win-update-e2e --from-release v1.4.124-rc.9 --to-release v1.4.125-rc.1 --expect cold-restore +``` + +Or directly: `node tools/win-update-e2e/run.mjs --from ... --to ... --expect ...` + +### Flags + +| Flag | Meaning | +| --------------------------------------------- | ----------------------------------------------------------- | +| `--from ` / `--to ` | Local `orca-windows-setup.exe` for base (N) / update (N+1) | +| `--from-release ` / `--to-release ` | Download the setup asset from a GitHub release tag via `gh` | +| `--expect cold-restore \| survival` | Assertion profile (required) | +| `--install-dir ` | Isolated-install mode (see below) — install into `` | +| `--asset-pattern ` | gh asset glob (default `*windows-setup.exe`) | +| `--soak-seconds ` | Post-relaunch window-watch soak (default `180`) | +| `--keep-install` | Skip teardown/uninstall for debugging (ignored in isolated) | + +### Profiles + +- **`cold-restore`** — **today's** behavior and the baseline that must keep + passing against current `main`. The installer's path sweep kills the in-dir + daemon, so: old daemon PID is **dead**, a **fresh** daemon exists, scrollback + is cold-restored (best-effort), a new terminal is interactive, and **zero** + unexpected console/terminal windows appear. +- **`survival`** — the Phase 1 target. Daemon PID **unchanged** across the + update, marker process **still alive**, the pre-update session still + interactive (typed input echoes, Ctrl+C interrupts), and **zero** unexpected + windows. + +## Safety + +This harness installs, overwrites, and can uninstall a real app. Two guards +protect a developer's machine; a clean CI/VM is unaffected by either: + +- **Pre-existing app process → hard refusal.** If an Orca _app_ process (not a + daemon) is already running, the run aborts and prints the offending PIDs. The + harness never kills a process it did not start. +- **Pre-existing install → refusal unless `--allow-existing-install`.** If an + Orca install already exists under `%LOCALAPPDATA%\Programs`, the run refuses, + because installing N then N+1 would silently overwrite that build and leave + the `--to` version behind. Pass `--allow-existing-install` to proceed anyway. + +Uninstall behavior at teardown follows ownership: + +- **No pre-existing install** (harness fully owns it): teardown silently + uninstalls, unless `--keep-install`. +- **`--allow-existing-install` was used** (an install existed first): teardown + does **not** uninstall — removing a build the harness did not place would be + wrong. It prints a prominent note that the machine now has the `--to` version + and the prior build was not restored. + +## Isolated install mode (developer machines) + +On a clean CI/VM the harness installs into the default per-user location +(`%LOCALAPPDATA%\Programs\Orca`). A developer's box already has a real Orca there, +and the safety guards above would (correctly) refuse to run. **Isolated mode** +(`--install-dir `) lets the harness run on that box without disturbing the +real install. + +**The /D mechanism.** electron-builder's NSIS honors the standard NSIS `/D=` +override for the install *directory* (`node_modules/app-builder-lib/templates/nsis/multiUser.nsh`). +`/D` is special: it must be the **last** argument and **cannot be quoted**, so the +path must be absolute and **spaces-free** (validated by `validateInstallDir`). The +installer's kill-sweep only matches processes under its own `$INSTDIR`, so a +separate directory never touches the real install's app or daemon processes. + +**Why registry/shortcut backup-restore exists.** `/D` relocates *files only*. +Regardless of `/D`, the installer writes `InstallLocation` + the uninstall entry to +the **same per-user HKCU keys** as the real install +(`HKCU\Software\` and +`HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\`, +`node_modules/app-builder-lib/templates/nsis/include/installer.nsh`) and rewrites the +Start Menu / Desktop shortcuts. Left hijacked, the user's **next real update would +install into the test directory**. So isolated mode, before installing: + +1. **Snapshots** the shared state (`registry-shortcut-backup.mjs`): `reg export`s + each existing key to `.reg` files, copies the Orca `*.lnk` shortcuts, and records + a manifest (which keys/shortcuts existed, the pre-run `InstallLocation`). +2. Runs the full install → update → assert proof against the isolated directory. +3. **Always restores** at teardown (a `try/finally` wraps everything after the + snapshot): `reg import`s keys that pre-existed, `reg delete`s keys the test + created, copies shortcuts back / deletes test-created ones, then **re-reads + `InstallLocation` and verifies** it matches the snapshot. On mismatch it prints a + loud block with the exact manual `reg import` command to recover. Isolated + teardown **always** uninstalls the test install (the harness owns the directory) + and removes the directory if empty — `--keep-install` is ignored. + +**Residual risk.** The backup/restore covers `InstallLocation`, the uninstall entry, +and the Orca shortcuts — the state that steers a future update and the user-visible +launchers. It does **not** attempt to snapshot auto-update state files under the real +install's `userData` (the harness uses an isolated `userData` throughout, so it never +writes there), and it cannot restore state if the machine loses power mid-teardown +(re-run with a valid `--install-dir` to let restore complete, or run the printed +`reg import` by hand). The `.reg` backups live under the run's temp dir until a +successful teardown removes it. + +**Example.** + +``` +pnpm win-update-e2e \ + --from-release v1.4.124-rc.9 --to-release v1.4.125-rc.1 \ + --expect cold-restore --install-dir C:\OrcaE2E +``` + +Read-only, touches nothing — print what isolated mode would snapshot on this machine: + +``` +node tools/win-update-e2e/registry-shortcut-backup.mjs +``` + +## What it does + +1. **Preflight** — assert win32; warn if elevated; **refuse** to run if a + pre-existing Orca _app_ process (not a daemon) is running that the harness + did not start (it is printed and the run aborts — the harness never kills a + user's processes); snapshot the baseline set of visible top-level windows. +2. **Install N** silently (` /S`) and locate `Orca.exe`. +3. **Launch** the installed app (Playwright `_electron`, isolated userData), + create ≥2 terminals, start a **marker** in one: a `powershell` loop that sets + a unique window-title **canary**, records its PID, and heartbeats a file. +4. **Record** the daemon PID (scoped pid-file + live-process scan), marker PID, + and session tab ids. +5. **Close** the app normally; verify the detached daemon is still alive. +6. **Start the window watch** — a background PowerShell loop polling visible + top-level windows every 500ms, diffing against baseline, recording every new + window (and title change) to a JSONL log through the update and soak. +7. **Install N+1** silently (the update). +8. **Relaunch** the app. +9. **Assert** per profile, then print a PASS/FAIL/INFO evidence table. +10. **Teardown** (unless `--keep-install`) — close app, kill only harness-created + processes, silent-uninstall. + +Exit code is `0` when every non-informational assertion passes, else `1` +(`2` for a CLI usage error). + +## Standalone instrument self-tests (no installers needed) + +Each probe module runs on its own so the harness's own instruments are testable: + +``` +# Opens a real transient console window and asserts the watch catches it: +node tools/win-update-e2e/window-watch.mjs --selftest + +# Read-only: list daemon processes + PID files on this machine: +node tools/win-update-e2e/daemon-processes.mjs [--user-data ] [--scope ] + +# Emit the current visible-window snapshot as JSON: +powershell -File tools/win-update-e2e/window-enum.ps1 +``` + +## Files + +| File | Responsibility | +| -------------------------- | ----------------------------------------------------------------------------- | +| `run.mjs` | Orchestrator + CLI entry | +| `cli-args.mjs` | Argument parsing / validation | +| `preflight.mjs` | win32/elevation checks, pre-existing-app refusal, baseline snapshot | +| `installer-steps.mjs` | Silent install/update/uninstall, exe discovery, gh download | +| `registry-shortcut-backup.mjs` | Isolated mode: snapshot/restore the shared HKCU keys + Orca shortcuts | +| `app-driver.mjs` | Playwright Electron launch + terminal driving (production-safe DOM selectors) | +| `interactivity-probes.mjs` | Sentinel-file echo / heartbeat / Ctrl+C probes | +| `daemon-processes.mjs` | Daemon PID discovery (command-line marker + pid file), scoped | +| `window-enum.ps1` | Shared visible-top-level-window enumerator (P/Invoke `EnumWindows`) | +| `window-watch.ps1` | Background baseline-diff watch loop → JSONL | +| `window-watch.mjs` | Node wrapper: start/stop watch, `--selftest`, baseline capture | +| `assertions.mjs` | Window-event classification + profile PASS/FAIL table | +| `platform-guard.mjs` | `assertWin32`, elevation detection | +| `powershell-runner.mjs` | Windows PowerShell 5.1 spawn helpers | + +## Known limitations + +- **Scrollback fidelity is best-effort.** A production build renders the + terminal with WebGL, so xterm text is not reliably in the DOM and the e2e + `SerializeAddon` is not exposed. When text cannot be read the check reports + `INFO` (unknown), never a false `FAIL`. +- **Daemon file log** does not exist yet in packaged builds (the fork's stdio is + suppressed). The "daemon log free of ERROR lines" assertion is `INFO` until + Phase 0 daemon logging lands, then it reads `/logs/daemon.log`. +- The harness assumes the packaged main honors `ORCA_E2E_USER_DATA_DIR` to + relocate userData; verify this against a real packaged build. diff --git a/tools/win-update-e2e/app-driver.mjs b/tools/win-update-e2e/app-driver.mjs new file mode 100644 index 000000000..8f16a4464 --- /dev/null +++ b/tools/win-update-e2e/app-driver.mjs @@ -0,0 +1,357 @@ +// Drive the installed, packaged Orca app with Playwright's Electron driver. +// +// This targets a PRODUCTION build, so it must NOT depend on the e2e-only store +// exposure (window.__store / window.__paneManagers) — those exist only under a +// `--mode e2e` / VITE_EXPOSE_STORE build. Everything here uses ARIA/DOM +// selectors that ship in production (matching tests/e2e/helpers/terminal.ts and +// terminal-attention.spec.ts) and proves interactivity through filesystem +// sentinels rather than by reading the WebGL-rendered xterm buffer: +// - typed commands write a marker FILE; the harness checks the file. This +// proves keystrokes reached the shell AND executed — stronger, and robust, +// than scraping canvas-rendered terminal text. +// +// The long-running marker also sets a unique window-title canary and writes a +// heartbeat file every ~500ms: the canary lets the window watch attribute any +// real console flash to our child, and the heartbeat proves the session is +// live and streaming. + +import { _electron as electron } from '@stablyai/playwright-test' +import { execFileSync } from 'node:child_process' +import { mkdirSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { seedFreshProfile } from './onboarding-profile.mjs' + +const NEW_TAB_BUTTON = { role: 'button', name: 'New tab' } +const NEW_TERMINAL_ITEM = /New Terminal/i +const NEW_WORKSPACE_BUTTON = { role: 'button', name: 'New workspace' } +const SORTABLE_TAB = '[data-testid="sortable-tab"]' +// Why: the layout mounts hidden duplicate panes; only the visible one is the +// live terminal, so target `:visible` to avoid focusing/measuring a hidden copy. +const TERMINAL_SURFACE_VISIBLE = '[data-terminal-tab-id]:visible' +const XTERM_CONTAINER_VISIBLE = '.xterm:visible' +const XTERM_INPUT = '.xterm-helper-textarea' + +/** + * Launch the installed Orca.exe. Pointing userDataDir at a harness-owned temp + * dir isolates this run's daemon (its socket/token path becomes unique), so + * daemon lookups never collide with other Orca installs/daemons on the box. + * Pass `seedProfile` (a buildFreshProfile object) to write orca-data.json + * BEFORE this launch — do so only on the FIRST launch, never before the + * post-update relaunch, or the persisted session under test is destroyed. + */ +export async function launchInstalledApp({ + exePath, + userDataDir, + seedProfile = null, + extraEnv = {} +}) { + const { ELECTRON_RUN_AS_NODE: _drop, ...cleanEnv } = process.env + mkdirSync(userDataDir, { recursive: true }) + if (seedProfile) { + seedFreshProfile(userDataDir, seedProfile) + } + const app = await electron.launch({ + executablePath: exePath, + args: [], + env: { + ...cleanEnv, + // Packaged main honors ORCA_E2E_USER_DATA_DIR to relocate userData + // (logs/daemon/terminal-history) under a controlled dir. + ORCA_E2E_USER_DATA_DIR: userDataDir, + ...extraEnv + } + }) + const page = await app.firstWindow({ timeout: 120_000 }) + await page.waitForLoadState('domcontentloaded') + return { app, page } +} + +/** + * Best-effort diagnostics dump when driving fails: a screenshot, the visible + * body text, and whether the e2e store is exposed (it is not in production + * builds). Written under `dir` so CI can upload it and reveal the actual + * post-launch DOM state. Never throws. + */ +export async function captureFailureDiagnostics(page, dir, label) { + const out = {} + try { + mkdirSync(dir, { recursive: true }) + } catch { + return out + } + try { + await page.screenshot({ + path: path.join(dir, `${label}.png`), + fullPage: false, + timeout: 10_000 + }) + out.screenshot = `${label}.png` + } catch { + /* renderer may be unresponsive */ + } + try { + const info = await page.evaluate(() => ({ + hasStore: typeof window.__store, + title: document.title, + url: location.href, + bodyText: (document.body?.innerText ?? '').slice(0, 4000), + testIds: Array.from(document.querySelectorAll('[data-testid]')) + .map((el) => el.getAttribute('data-testid')) + .filter((v, i, a) => v && a.indexOf(v) === i) + .slice(0, 80), + buttons: Array.from(document.querySelectorAll('button,[role="button"]')) + .map((el) => (el.getAttribute('aria-label') || el.textContent || '').trim()) + .filter((v, i, a) => v && a.indexOf(v) === i) + .slice(0, 60) + })) + writeFileSync(path.join(dir, `${label}.json`), JSON.stringify(info, null, 2)) + out.info = info + } catch { + /* renderer may be unresponsive */ + } + return out +} + +/** Wait until the visible terminal surface and its xterm container are mounted. */ +export async function waitForTerminalReady(page, timeoutMs = 60_000) { + await page + .locator(TERMINAL_SURFACE_VISIBLE) + .first() + .waitFor({ state: 'visible', timeout: timeoutMs }) + await page + .locator(XTERM_CONTAINER_VISIBLE) + .first() + .waitFor({ state: 'visible', timeout: timeoutMs }) +} + +/** + * Get the app to an interactive terminal. + * - `allowCreate` true (first launch): if no terminal is visible, create a + * workspace from the seeded repo (or a new tab if a workspace already + * exists) — the drivable composer, not the native folder dialog. + * - `allowCreate` false (post-update relaunch): the session should be + * RESTORED, so only wait for the restored terminal — never create a second + * workspace (which would mask a broken restore). + */ +export async function ensureTerminal(page, { allowCreate = true, timeoutMs = 60_000 } = {}) { + const visibleTerminal = page.locator(TERMINAL_SURFACE_VISIBLE).first() + if (await visibleTerminal.isVisible().catch(() => false)) { + await waitForTerminalReady(page, timeoutMs) + return + } + if (!allowCreate) { + // Wait for the restored terminal to appear; a timeout here is a real + // (asserted) failure of session restore, not a driving gap. + await waitForTerminalReady(page, timeoutMs) + return + } + const newTab = page.getByRole(NEW_TAB_BUTTON.role, { name: NEW_TAB_BUTTON.name }).first() + if (await newTab.isVisible().catch(() => false)) { + await createTerminalTab(page) + return + } + await createWorkspaceFromSeededRepo(page, timeoutMs) + await waitForTerminalReady(page, timeoutMs) +} + +/** + * Drive the "New workspace" composer to create a worktree from the single + * seeded project. The composer is in-app DOM (unlike the native Add-Project + * dialog): open it, choose the "Blank Terminal" mode so the worktree opens a + * plain terminal (not an agent), then submit "Create worktree". + */ +async function createWorkspaceFromSeededRepo(page, timeoutMs) { + await page + .getByRole(NEW_WORKSPACE_BUTTON.role, { name: NEW_WORKSPACE_BUTTON.name }) + .first() + .click({ timeout: timeoutMs }) + // Choose the plain-terminal mode (best-effort — if it is already the default + // or the label differs, the create below still produces a worktree). + await page + .getByRole('button', { name: 'Blank Terminal' }) + .first() + .click({ timeout: 15_000 }) + .catch(() => {}) + // Submit. The create button's accessible name carries the shortcut hint + // ("Create worktreeCtrl"), so match by prefix; fall back to the documented + // Ctrl+Enter shortcut if the button is not directly clickable. + const created = await page + .getByRole('button', { name: /^Create worktree/ }) + .last() + .click({ timeout: 15_000 }) + .then(() => true) + .catch(() => false) + if (!created) { + await page.keyboard.press('Control+Enter') + } +} + +const OVERLAY_DISMISS_LABELS = ['Got it', 'Dismiss setup scripts', 'Dismiss tip', 'Dismiss update'] + +/** + * Best-effort dismissal of the modals/banners that appear after creating a + * worktree (a full-screen "Got it" feature-tip modal, the setup-script prompt, + * update banner) and intercept all input over the terminal. Loops because tips + * can appear in sequence. Never throws. + */ +export async function dismissOverlays(page, rounds = 3) { + for (let i = 0; i < rounds; i++) { + let acted = false + for (const name of OVERLAY_DISMISS_LABELS) { + const btn = page.getByRole('button', { name }).first() + if (await btn.isVisible().catch(() => false)) { + await btn.click({ timeout: 3_000 }).catch(() => {}) + acted = true + } + } + await page.keyboard.press('Escape').catch(() => {}) + if (!acted) { + return + } + await page.waitForTimeout(400) + } +} + +/** Create a new terminal tab via the New tab menu. Returns the count after. */ +export async function createTerminalTab(page) { + await dismissOverlays(page, 1) + const before = await page.locator(SORTABLE_TAB).count() + await page + .getByRole(NEW_TAB_BUTTON.role, { name: NEW_TAB_BUTTON.name }) + .first() + .click({ force: true }) + await page.getByRole('menuitem', { name: NEW_TERMINAL_ITEM }).first().click({ force: true }) + await page.waitForFunction( + ({ selector, prev }) => document.querySelectorAll(selector).length > prev, + { selector: SORTABLE_TAB, prev: before }, + { timeout: 10_000 } + ) + await waitForTerminalReady(page) + return page.locator(SORTABLE_TAB).count() +} + +/** Cheap session identifiers: the rendered tab ids. */ +export async function listTabIds(page) { + return page + .locator(SORTABLE_TAB) + .evaluateAll((tabs) => + tabs.map((t) => t.getAttribute('data-tab-id')).filter((id) => Boolean(id)) + ) +} + +/** + * Focus the live terminal so keystrokes reach the shell. Clicking the visible + * xterm surface is what actually gives xterm keyboard focus — focusing the + * off-screen helper textarea alone does not, which is why typed input was being + * dropped. Click the pane, then focus the helper textarea as a belt-and-braces. + */ +export async function focusActiveTerminal(page) { + // A feature-tip modal can appear late and swallow keystrokes; clear any before + // focusing so typed commands actually reach the shell. + for (const name of OVERLAY_DISMISS_LABELS) { + const btn = page.getByRole('button', { name }).first() + if (await btn.isVisible().catch(() => false)) { + await btn.click({ timeout: 2_000 }).catch(() => {}) + } + } + const surface = page.locator(TERMINAL_SURFACE_VISIBLE).first() + await surface.click({ position: { x: 24, y: 24 }, timeout: 15_000 }).catch(() => {}) + // Scope the helper textarea to the visible surface so focus can't land on a + // hidden duplicate pane's textarea (which would silently swallow keystrokes). + const input = surface.locator(XTERM_INPUT).last() + await input.focus().catch(() => {}) + return input +} + +/** Type a line and submit it (Enter → \r submits in the shell). */ +export async function typeLine(page, text) { + await focusActiveTerminal(page) + await page.keyboard.type(text) + await page.keyboard.press('Enter') +} + +/** Send Ctrl+C to the active terminal. */ +export async function sendCtrlC(page) { + await focusActiveTerminal(page) + await page.keyboard.press('Control+C') +} + +/** + * Run a PowerShell command inside the active terminal by invoking a nested + * powershell.exe. The command is wrapped in double quotes for the OUTER + * interactive shell (also pwsh), which would otherwise expand `$var`, `$(...)` + * and consume backticks before the nested shell sees them — so escape backticks, + * quotes, and `$`. Without the `$` escape, `while($true)` reaches the nested + * shell as `while(True)` and never runs (the bug that silently broke every + * loop/heartbeat probe while simple `$`-free commands worked). + */ +export async function runShellCommand(page, psCommand) { + const escaped = psCommand.replace(/`/g, '``').replace(/"/g, '`"').replace(/\$/g, '`$') + await typeLine(page, `powershell.exe -NoProfile -NonInteractive -Command "${escaped}"`) +} + +/** + * Start the long-running marker in the active terminal: sets the canary window + * title, records its own PID, and heartbeats a file every 500ms. Returns the + * command string (the caller reads the pid file to learn the marker PID). + */ +export async function startMarker(page, { canary, pidFile, heartbeatFile }) { + const script = [ + `$host.UI.RawUI.WindowTitle='${canary}'`, + `Set-Content -LiteralPath '${pidFile}' -Value $PID`, + `while($true){ [System.IO.File]::WriteAllText('${heartbeatFile}',(Get-Date).ToString('o')); Start-Sleep -Milliseconds 500 }` + ].join('; ') + await runShellCommand(page, script) + return script +} + +/** + * Best-effort read of the active terminal's visible text, for the cold-restore + * scrollback fidelity check. Prefers the SerializeAddon when the build happens + * to expose paneManagers; falls back to DOM rows (populated only under the DOM + * renderer, so this may be empty under WebGL — hence best-effort). + */ +export async function readTerminalTextBestEffort(page) { + return page.evaluate(() => { + const managers = window.__paneManagers + if (managers && typeof managers.forEach === 'function') { + let out = '' + managers.forEach((m) => { + const pane = m.getActivePane?.() ?? m.getPanes?.()[0] + const text = pane?.serializeAddon?.serialize?.() + if (text) { + out += text + } + }) + if (out) { + return out + } + } + return Array.from(document.querySelectorAll('.xterm-rows')) + .map((el) => el.textContent ?? '') + .join('\n') + }) +} + +/** + * Close the app gracefully; force-kill its process tree on timeout. Mirrors + * tests/e2e/helpers/electron-process-shutdown.ts so the daemon (detached) is + * left alive exactly as a normal quit would. + */ +export async function closeApp(app, timeoutMs = 10_000) { + const proc = app.process() + try { + await Promise.race([ + app.close(), + new Promise((_, reject) => setTimeout(() => reject(new Error('close timeout')), timeoutMs)) + ]) + } catch { + if (proc?.pid) { + try { + execFileSync('taskkill', ['/pid', String(proc.pid), '/T', '/F'], { stdio: 'ignore' }) + } catch { + /* already gone */ + } + } + } +} diff --git a/tools/win-update-e2e/assertions.mjs b/tools/win-update-e2e/assertions.mjs new file mode 100644 index 000000000..20db79e48 --- /dev/null +++ b/tools/win-update-e2e/assertions.mjs @@ -0,0 +1,186 @@ +// Profile assertions and the final PASS/FAIL evidence table. +// +// Two profiles: +// cold-restore — TODAY's behavior. The installer's path sweep kills the +// in-dir daemon, so the old daemon PID must be DEAD, a fresh daemon must +// exist, scrollback is cold-restored (best-effort), a new terminal is +// interactive, and NO unexpected console/terminal windows appear. +// survival — Phase 1 target. The daemon PID is UNCHANGED across the update, +// the marker process is still alive, the pre-update session is still +// interactive (echo + Ctrl+C), and NO unexpected windows appear. + +const CONSOLE_HOST_PROCESSES = new Set([ + 'powershell', + 'pwsh', + 'cmd', + 'conhost', + 'windowsterminal', + 'openconsole' +]) + +// The app's own windows are expected on relaunch and never count as a flash. +const APP_OWNER_PROCESSES = new Set(['orca', 'electron']) + +/** + * Split window-watch events into unexpected flashes vs benign. Unexpected = + * (a) any window whose title contains the run's canary — a real flash of our + * marker child, which must never get its own window — or (b) any new + * console/terminal-host window that is not the app itself. Attribution is by + * title + owner process only (never conhost command-line heuristics). + */ +export function classifyWindowEvents(events, { canary }) { + const unexpected = [] + for (const event of events) { + const title = typeof event.title === 'string' ? event.title : '' + const owner = (event.processName ?? '').toLowerCase() + const canaryHit = canary && title.includes(canary) + const consoleHit = CONSOLE_HOST_PROCESSES.has(owner) && !APP_OWNER_PROCESSES.has(owner) + if (canaryHit || consoleHit) { + unexpected.push({ ...event, reason: canaryHit ? 'canary-title' : 'console-host' }) + } + } + return { unexpected } +} + +function assertion(name, pass, expected, actual, detail = '') { + return { name, pass, expected, actual, detail } +} + +/** Build the ordered assertion list for the run's profile. */ +export function buildAssertions(ctx) { + const { unexpected } = classifyWindowEvents(ctx.watchEvents ?? [], { canary: ctx.canary }) + const windowAssertion = assertion( + 'zero unexpected console/terminal windows', + unexpected.length === 0, + '0 windows', + `${unexpected.length} windows`, + unexpected.map((u) => `${u.processName}:"${u.title}" (${u.reason})`).join('; ') + ) + + const common = [windowAssertion, daemonLogAssertion(ctx)] + + return ctx.profile === 'survival' + ? [...survivalAssertions(ctx), ...common] + : [...coldRestoreAssertions(ctx), ...common] +} + +function survivalAssertions(ctx) { + const samePid = + ctx.preDaemonPid != null && ctx.preDaemonPid === ctx.postDaemonPid && ctx.postDaemonAlive + return [ + assertion( + 'daemon PID unchanged across update', + samePid, + `pid ${ctx.preDaemonPid} still alive`, + `post pid ${ctx.postDaemonPid} (alive: ${ctx.postDaemonAlive})` + ), + assertion( + 'marker process still alive', + Boolean(ctx.markerAliveAfter), + `marker pid ${ctx.markerPid} alive`, + String(ctx.markerAliveAfter) + ), + assertion( + 'pre-update session streams (heartbeat advanced)', + Boolean(ctx.heartbeatAdvancedAfterUpdate), + 'heartbeat mtime advanced post-update', + String(ctx.heartbeatAdvancedAfterUpdate) + ), + assertion( + 'typed input echoes in pre-update session', + Boolean(ctx.echoObserved), + 'echo sentinel file written', + String(ctx.echoObserved) + ), + assertion( + 'Ctrl+C interrupts marker loop', + Boolean(ctx.ctrlCInterrupted), + 'heartbeat stopped + post-interrupt sentinel written', + String(ctx.ctrlCInterrupted) + ) + ] +} + +function coldRestoreAssertions(ctx) { + const freshDaemon = + ctx.postDaemonPid != null && ctx.postDaemonPid !== ctx.preDaemonPid && ctx.postDaemonAlive + return [ + assertion( + 'old daemon PID is dead after update', + ctx.preDaemonAliveAfter === false, + `pid ${ctx.preDaemonPid} dead`, + `alive: ${ctx.preDaemonAliveAfter}` + ), + assertion( + 'fresh daemon exists after relaunch', + freshDaemon, + 'new daemon pid, alive', + `post pid ${ctx.postDaemonPid} (alive: ${ctx.postDaemonAlive})` + ), + // Best-effort: WebGL renderer may hide buffer text from DOM scraping, so a + // null result is reported as informational (pass=null), not a failure. + assertion( + 'previous terminals show restored scrollback (best-effort)', + ctx.scrollbackRestored === null ? null : ctx.scrollbackRestored, + 'prior output text present after restore', + ctx.scrollbackRestored === null ? 'unknown (renderer opaque)' : String(ctx.scrollbackRestored) + ), + assertion( + 'new terminal is interactive (typed input echoes)', + Boolean(ctx.echoObserved), + 'echo sentinel file written', + String(ctx.echoObserved) + ), + assertion( + 'Ctrl+C kills a sleep loop in new terminal', + Boolean(ctx.ctrlCInterrupted), + 'loop interrupted + post-interrupt sentinel written', + String(ctx.ctrlCInterrupted) + ) + ] +} + +function daemonLogAssertion(ctx) { + // The daemon has no file log today (stdio is suppressed in packaged forks). + // Treat "no log present" as informational; when a log IS present (Phase 0 + // observability), assert it is free of ERROR lines. + if (!ctx.daemonLog) { + return assertion( + 'daemon log free of fatal records', + null, + 'no fatal/invalid-token records', + 'no daemon log present (informational)' + ) + } + // Only genuinely-bad records count (fatal uncaught exceptions, invalid-token + // hello rejections). Benign suppressed native-PTY exceptions are reported as + // context but never affect pass/fail. + const errorLines = ctx.daemonLog.errorLines ?? [] + const suppressed = ctx.daemonLog.suppressedCount ?? 0 + const suppressedNote = suppressed > 0 ? ` (${suppressed} benign suppressed, ignored)` : '' + return assertion( + 'daemon log free of fatal records', + errorLines.length === 0, + 'no fatal/invalid-token records', + `${errorLines.length} fatal record(s)${suppressedNote}`, + errorLines.slice(0, 3).join(' | ') + ) +} + +/** True only if every non-informational assertion passed. */ +export function allPassed(assertions) { + return assertions.every((a) => a.pass === true || a.pass === null) +} + +/** Render the assertion list as an aligned PASS/FAIL/INFO table. */ +export function renderTable(assertions) { + const symbol = (pass) => (pass === true ? 'PASS' : pass === false ? 'FAIL' : 'INFO') + const nameWidth = Math.max(...assertions.map((a) => a.name.length), 10) + const lines = assertions.map((a) => { + const detail = a.detail ? ` — ${a.detail}` : '' + return ` [${symbol(a.pass)}] ${a.name.padEnd(nameWidth)} expected: ${a.expected}; actual: ${a.actual}${detail}` + }) + const failed = assertions.filter((a) => a.pass === false).length + const header = `\n===== win-update-e2e assertions (${failed === 0 ? 'ALL PASS' : `${failed} FAILED`}) =====` + return [header, ...lines, ''].join('\n') +} diff --git a/tools/win-update-e2e/cli-args.mjs b/tools/win-update-e2e/cli-args.mjs new file mode 100644 index 000000000..ed5041231 --- /dev/null +++ b/tools/win-update-e2e/cli-args.mjs @@ -0,0 +1,201 @@ +// Argument parsing for `node run.mjs`. +// +// Two installer sources are accepted per side: a local path (--from/--to) or a +// GitHub release tag (--from-release/--to-release) that the harness downloads +// via `gh release download`. Exactly one profile (--expect) is required. + +import { existsSync, readdirSync } from 'node:fs' +import path from 'node:path' + +const VALID_PROFILES = new Set(['cold-restore', 'survival']) + +const USAGE = ` +win-update-e2e — packaged NSIS update proof harness (Windows only) + +Usage: + node tools/win-update-e2e/run.mjs --from --to --expect [options] + node tools/win-update-e2e/run.mjs --from-release --to-release --expect + +Installer source (version N, then N+1) — path or release tag on each side: + --from Local orca-windows-setup.exe for the base version (N) + --to Local orca-windows-setup.exe for the update (N+1) + --from-release Download N's setup asset via gh (e.g. v1.4.124-rc.9) + --to-release Download N+1's setup asset via gh + +Required: + --expect Assertion profile: "cold-restore" or "survival" + cold-restore = today's behavior (daemon killed by the + installer sweep, app cold-restores scrollback, no + flashing). survival = Phase 1 target (daemon PID + unchanged, sessions still interactive). + +Options: + --install-dir Isolated-install mode: install the test build into + instead of the default per-user location, + leaving a developer's REAL Orca install untouched. + The path must be absolute and contain NO SPACES (the + NSIS /D override cannot be quoted), must not be the + default install location, and must not point at a + non-empty directory that is not a prior harness + install. Isolated mode snapshots and restores the + shared per-user registry keys + shortcuts at teardown + so the real install's "next update" target is + preserved. See README "Isolated install mode". + --allow-existing-install Proceed even if an Orca install already exists. The + run overwrites it with the --from/--to versions and + leaves the --to version installed (your prior build + is NOT restored). Without this flag the harness + refuses to run when an install exists, to protect a + developer's real Orca. Clean machines (CI/VM) never + need it. Ignored in --install-dir mode, which never + touches the real install. + --keep-install Skip teardown/uninstall (leaves the app installed) + --asset-pattern gh release asset glob (default: *windows-setup.exe) + --soak-seconds Post-relaunch window watch duration (default: 180) + -h, --help Show this help +` + +export function parseArgs(argv) { + if (argv.includes('-h') || argv.includes('--help')) { + return { help: true, usage: USAGE } + } + + const opts = { + from: takeValue(argv, '--from'), + to: takeValue(argv, '--to'), + fromRelease: takeValue(argv, '--from-release'), + toRelease: takeValue(argv, '--to-release'), + expect: takeValue(argv, '--expect'), + assetPattern: takeValue(argv, '--asset-pattern') ?? '*windows-setup.exe', + soakSeconds: Number(takeValue(argv, '--soak-seconds') ?? '180'), + installDir: takeValue(argv, '--install-dir'), + keepInstall: argv.includes('--keep-install'), + allowExistingInstall: argv.includes('--allow-existing-install'), + usage: USAGE + } + + // Distinguish "--install-dir omitted" from "--install-dir with no value": the + // latter must fail rather than silently fall back to a non-isolated install. + const errors = validate(opts, argv.includes('--install-dir')) + return { ...opts, errors } +} + +/** Default per-user oneClick install location: %LOCALAPPDATA%\Programs\Orca. */ +function defaultInstallDir() { + const localAppData = + process.env.LOCALAPPDATA ?? path.join(process.env.USERPROFILE ?? '', 'AppData', 'Local') + return path.join(localAppData, 'Programs', 'Orca') +} + +/** True if `child` is equal to, inside, or an ancestor of `parent` (case-insensitive). */ +function pathsOverlap(a, b) { + const na = path + .resolve(a) + .replace(/[\\/]+$/, '') + .toLowerCase() + const nb = path + .resolve(b) + .replace(/[\\/]+$/, '') + .toLowerCase() + if (na === nb) { + return true + } + return na.startsWith(`${nb}\\`) || nb.startsWith(`${na}\\`) +} + +/** A prior harness install directory carries both the app exe and its uninstaller. */ +function looksLikeHarnessInstall(dir) { + return existsSync(path.join(dir, 'Orca.exe')) && existsSync(path.join(dir, 'Uninstall Orca.exe')) +} + +/** + * Validate --install-dir for isolated-install mode. The NSIS /D override must be + * the last, unquoted argument, so the path cannot contain spaces. It must also + * not overlap the default install location (that would defeat isolation) and + * must not clobber an unrelated non-empty directory. + */ +export function validateInstallDir(installDir) { + const errors = [] + if (!path.isAbsolute(installDir)) { + errors.push(`--install-dir must be an absolute path (got "${installDir}")`) + return errors + } + if (/\s/.test(installDir)) { + errors.push( + `--install-dir must not contain spaces (got "${installDir}"). The NSIS installer's ` + + `/D path override must be the last, UNQUOTED argument, so a path with spaces cannot ` + + `be passed. Choose a spaces-free location (e.g. C:\\OrcaE2E).` + ) + } + if (pathsOverlap(installDir, defaultInstallDir())) { + errors.push( + `--install-dir "${installDir}" overlaps the default install location ` + + `"${defaultInstallDir()}". Isolated mode must target a separate directory so the ` + + `real install is never touched.` + ) + } + if (existsSync(installDir)) { + let entries = [] + try { + entries = readdirSync(installDir) + } catch (err) { + // Fail closed: an unreadable existing directory must not be treated as + // empty/safe to overwrite. + errors.push( + `--install-dir "${installDir}" could not be read (${err.message}). ` + + `Refusing to treat an unreadable directory as safe to overwrite.` + ) + return errors + } + if (entries.length > 0 && !looksLikeHarnessInstall(installDir)) { + errors.push( + `--install-dir "${installDir}" is a non-empty directory that does not look like a ` + + `prior harness install (no Orca.exe + "Uninstall Orca.exe"). Refusing to overwrite ` + + `unrelated files. Point at an empty or non-existent directory.` + ) + } + } + return errors +} + +function validate(opts, installDirFlagPresent) { + const errors = [] + if (!opts.from && !opts.fromRelease) { + errors.push('Missing base installer: pass --from or --from-release ') + } + if (opts.from && opts.fromRelease) { + errors.push('Pass only one of --from / --from-release') + } + if (!opts.to && !opts.toRelease) { + errors.push('Missing update installer: pass --to or --to-release ') + } + if (opts.to && opts.toRelease) { + errors.push('Pass only one of --to / --to-release') + } + if (!opts.expect) { + errors.push('Missing --expect ') + } else if (!VALID_PROFILES.has(opts.expect)) { + errors.push(`Invalid --expect "${opts.expect}" (expected cold-restore or survival)`) + } + if (!Number.isFinite(opts.soakSeconds) || opts.soakSeconds < 0) { + errors.push('--soak-seconds must be a non-negative number') + } + if (installDirFlagPresent && opts.installDir === undefined) { + errors.push('--install-dir requires a path value') + } else if (opts.installDir !== undefined) { + errors.push(...validateInstallDir(opts.installDir)) + } + return errors +} + +function takeValue(argv, flag) { + const idx = argv.indexOf(flag) + if (idx < 0) { + return undefined + } + const value = argv[idx + 1] + if (value === undefined || value.startsWith('--')) { + return undefined + } + return value +} diff --git a/tools/win-update-e2e/daemon-processes.mjs b/tools/win-update-e2e/daemon-processes.mjs new file mode 100644 index 000000000..cfd9c5d41 --- /dev/null +++ b/tools/win-update-e2e/daemon-processes.mjs @@ -0,0 +1,173 @@ +// Identify and inspect the Orca terminal daemon on Windows. +// +// The daemon is forked with ELECTRON_RUN_AS_NODE=1, so on Windows its process +// image is Orca.exe (the Electron binary running as plain Node) — it CANNOT be +// matched by executable name. The only reliable discriminators are the +// command-line markers the fork always passes: the daemon entry script +// (daemon-entry.js) and its --socket / --token arguments. See +// src/main/daemon/daemon-init.ts (createOutOfProcessLauncher). +// +// The daemon also writes a PID file at /daemon/daemon-v.pid whose +// JSON carries { pid, startedAtMs, entryPath, appVersion } — the appVersion +// field lets the harness prove whether a post-update daemon was re-forked by +// the new build (cold-restore) or is the same process (survival). + +import { existsSync, readFileSync, readdirSync } from 'node:fs' +import path from 'node:path' +import { assertWin32 } from './platform-guard.mjs' +import { runCommandSync } from './powershell-runner.mjs' + +const DAEMON_ENTRY_MARKER = 'daemon-entry.js' + +/** Default packaged userData root on Windows: %APPDATA%\Orca. */ +export function defaultUserDataDir() { + const appData = + process.env.APPDATA ?? path.join(process.env.USERPROFILE ?? '', 'AppData', 'Roaming') + return path.join(appData, 'Orca') +} + +/** + * Find live daemon processes by scanning Win32_Process command lines for the + * daemon-entry.js marker. Returns [{ pid, ppid, name, commandLine }]. + * + * A developer box (and a busy CI runner) can host many unrelated daemons — one + * per worktree/profile, plus lingering hosts from reverted builds. Pass + * `scope` (a substring of the harness's own userData/token/socket path) to + * match ONLY the daemon this harness's app instance owns. Omit it for a + * machine-wide listing. + */ +export function findDaemonProcesses(scope = '') { + assertWin32('daemon-processes') + // Match by command-line marker only, never by exe name: with + // ELECTRON_RUN_AS_NODE the daemon's image is Orca.exe today but a relocated + // Phase 1 host may run from a differently-named copied binary. @() around the + // filtered result guards the PS 5.1 single-item unwrap — one match must still + // serialize as an array or the JS side sees an object and .length explodes. + // This exact class caused a production incident. + const command = [ + `$procs = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |`, + ` Where-Object { $_.CommandLine -and $_.CommandLine -match 'daemon-entry\\.js' })`, + `$out = @($procs | ForEach-Object {`, + ` [pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; name = $_.Name; commandLine = $_.CommandLine } })`, + `ConvertTo-Json -InputObject @{ processes = $out } -Depth 4 -Compress` + ].join('\n') + + const parsed = runJsonCommand(command) + const scopeNeedle = scope.toLowerCase() + return normalizeArray(parsed.processes).filter( + (p) => + typeof p.commandLine === 'string' && + p.commandLine.includes(DAEMON_ENTRY_MARKER) && + (scopeNeedle === '' || p.commandLine.toLowerCase().includes(scopeNeedle)) + ) +} + +/** + * Read all daemon PID files under /daemon (daemon-v*.pid). Globbing + * the protocol-versioned name keeps this correct across PROTOCOL_VERSION bumps. + * Returns [{ file, pid, startedAtMs, entryPath, appVersion }]. + */ +export function readDaemonPidFiles(userDataDir = defaultUserDataDir()) { + const daemonDir = path.join(userDataDir, 'daemon') + if (!existsSync(daemonDir)) { + return [] + } + const records = [] + for (const entry of readdirSync(daemonDir)) { + if (!entry.startsWith('daemon-v') || !entry.endsWith('.pid')) { + continue + } + const filePath = path.join(daemonDir, entry) + // Read once: a PID file can vanish between readdir and here, and re-reading + // it in the catch path would crash discovery on a single stale file. + let raw = '' + try { + raw = readFileSync(filePath, 'utf8').trim() + const parsed = JSON.parse(raw) + records.push({ file: filePath, ...parsed }) + } catch { + // Legacy/partial pid files may hold a bare integer. + const pid = Number(raw) + if (Number.isInteger(pid)) { + records.push({ file: filePath, pid }) + } + } + } + return records +} + +/** True if a PID currently maps to a live process. */ +export function isPidAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) { + return false + } + const { stdout } = runCommandSync( + `if (Get-Process -Id ${pid} -ErrorAction SilentlyContinue) { 'alive' } else { 'dead' }` + ) + return stdout.trim() === 'alive' +} + +function runJsonCommand(command) { + const { stdout, stderr, code, error } = runCommandSync(command) + if (error) { + throw new Error(`PowerShell spawn failed: ${error.message}`) + } + const trimmed = stdout.trim() + if (!trimmed) { + // No matches: ConvertTo-Json of an empty array can emit nothing. + return { processes: [] } + } + try { + return JSON.parse(trimmed) + } catch (parseError) { + throw new Error( + `daemon-processes query returned non-JSON (exit ${code}): ${parseError.message}\n` + + `stdout:\n${trimmed}\nstderr:\n${stderr}` + ) + } +} + +function normalizeArray(raw) { + if (!raw) { + return [] + } + return Array.isArray(raw) ? raw : [raw] +} + +function parseUserDataArg(argv) { + const idx = argv.indexOf('--user-data') + return idx >= 0 && argv[idx + 1] ? argv[idx + 1] : defaultUserDataDir() +} + +function runStandalone(argv) { + assertWin32('daemon-processes standalone') + const userDataDir = parseUserDataArg(argv) + console.log(`[daemon-processes] userData: ${userDataDir}`) + + const pidFiles = readDaemonPidFiles(userDataDir) + console.log(`[daemon-processes] PID files (${pidFiles.length}):`) + console.log(JSON.stringify(pidFiles, null, 2)) + + const scopeIdx = argv.indexOf('--scope') + const scope = scopeIdx >= 0 && argv[scopeIdx + 1] ? argv[scopeIdx + 1] : '' + const processes = findDaemonProcesses(scope) + console.log( + `[daemon-processes] live daemon processes${scope ? ` scoped to "${scope}"` : ''} (${processes.length}):` + ) + console.log(JSON.stringify(processes, null, 2)) + + for (const rec of pidFiles) { + if (typeof rec.pid === 'number') { + console.log(`[daemon-processes] pid ${rec.pid} alive: ${isPidAlive(rec.pid)}`) + } + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === import.meta.filename) { + try { + runStandalone(process.argv.slice(2)) + } catch (err) { + console.error(err.message) + process.exitCode = 1 + } +} diff --git a/tools/win-update-e2e/installer-steps.mjs b/tools/win-update-e2e/installer-steps.mjs new file mode 100644 index 000000000..18ba4ed09 --- /dev/null +++ b/tools/win-update-e2e/installer-steps.mjs @@ -0,0 +1,202 @@ +// Silent NSIS install / update / uninstall and installed-app discovery. +// +// Orca ships a per-user oneClick NSIS installer (electron-builder defaults: +// oneClick=true, perMachine=false) named orca-windows-setup.exe. One-click +// silent mode is ` /S`; the app installs under +// %LOCALAPPDATA%\Programs\ and the exe is Orca.exe. The install dir casing +// is not guaranteed (observed lowercase "orca" on a dev box), so the exe is +// located by search, never by a hard-coded path. + +import { existsSync, mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { spawnSync } from 'node:child_process' +import { assertWin32 } from './platform-guard.mjs' +import { runCommandSync } from './powershell-runner.mjs' + +const PRODUCT_NAME = 'Orca' +const EXE_NAME = 'Orca.exe' + +/** Programs root that per-user oneClick NSIS installs into. */ +function programsRoot() { + const localAppData = + process.env.LOCALAPPDATA ?? path.join(process.env.USERPROFILE ?? '', 'AppData', 'Local') + return path.join(localAppData, 'Programs') +} + +/** + * Resolve a base/update installer to a local .exe path, downloading from a + * GitHub release tag when requested. Keeps gh usage to a single `release + * download` call (AGENTS.md rate-limit guidance). + */ +export function resolveInstaller({ localPath, releaseTag, assetPattern }) { + if (localPath) { + if (!existsSync(localPath)) { + throw new Error(`Installer not found: ${localPath}`) + } + return path.resolve(localPath) + } + if (!releaseTag) { + throw new Error('resolveInstaller: neither localPath nor releaseTag provided') + } + const outDir = mkdtempSync(path.join(tmpdir(), 'orca-e2e-installer-')) + const result = spawnSync( + 'gh', + ['release', 'download', releaseTag, '--pattern', assetPattern, '--dir', outDir], + { encoding: 'utf8' } + ) + if (result.status !== 0) { + throw new Error( + `gh release download ${releaseTag} failed (exit ${result.status}): ${result.stderr || result.stdout}` + ) + } + const found = findSetupExe(outDir) + if (!found) { + throw new Error(`No installer matching "${assetPattern}" in downloaded release ${releaseTag}`) + } + return found +} + +function findSetupExe(dir) { + const { stdout } = runCommandSync( + `Get-ChildItem -Path '${dir}' -Filter '*.exe' -Recurse -ErrorAction SilentlyContinue | ` + + `Select-Object -First 1 -ExpandProperty FullName` + ) + const line = stdout.trim().split('\n')[0]?.trim() + return line && existsSync(line) ? line : null +} + +/** + * Run an NSIS installer in one-click silent mode and wait for the installed exe + * to appear. Returns { exePath, version }. The installer process returns before + * copying finishes, so completion is confirmed by polling for the exe. + * + * When `installDir` is set (isolated-install mode), `/D=` overrides the + * install location. `/D` is special in NSIS: it must be the LAST argument and + * cannot be quoted, so the path must be spaces-free (validated upstream) and is + * passed as a single unquoted argv entry. + */ +export function silentInstall(setupExe, { timeoutMs = 180_000, installDir = null } = {}) { + assertWin32('silentInstall') + if (!existsSync(setupExe)) { + throw new Error(`Installer not found: ${setupExe}`) + } + // /S is the NSIS silent switch; the electron-builder oneClick installer needs + // no other flags for a per-user install. /D, when present, MUST be last. + const args = ['/S'] + if (installDir) { + args.push(`/D=${installDir}`) + } + const proc = spawnSync(setupExe, args, { encoding: 'utf8' }) + if (proc.error) { + throw new Error(`Failed to launch installer ${setupExe}: ${proc.error.message}`) + } + + // On update runs the old Orca.exe already exists, so wait for the exe whose + // version matches this installer — not just any exe the installer hasn't yet + // overwritten — to avoid reading the pre-update binary mid-copy. + const targetVersion = getExeVersion(setupExe) + const exePath = waitForInstalledExe(timeoutMs, installDir, targetVersion) + if (!exePath) { + const where = installDir ?? programsRoot() + throw new Error(`Installed ${EXE_NAME} did not appear under ${where} within ${timeoutMs}ms`) + } + return { exePath, version: getExeVersion(exePath) } +} + +function waitForInstalledExe(timeoutMs, installDir = null, expectedVersion = null) { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + const exe = locateInstalledExe(installDir) + if (exe && (!expectedVersion || getExeVersion(exe) === expectedVersion)) { + return exe + } + sleepSync(1000) + } + return null +} + +/** + * Locate the installed Orca.exe. In isolated mode (`installDir` set), the exe is + * at a known fixed path (\Orca.exe). Otherwise it is discovered + * under %LOCALAPPDATA%\Programs (case-tolerant — casing is not guaranteed). + */ +export function locateInstalledExe(installDir = null) { + if (installDir) { + const exe = path.join(installDir, EXE_NAME) + return existsSync(exe) ? exe : null + } + const root = programsRoot() + if (!existsSync(root)) { + return null + } + const { stdout } = runCommandSync( + `Get-ChildItem -Path '${root}' -Directory -ErrorAction SilentlyContinue | ` + + `ForEach-Object { Join-Path $_.FullName '${EXE_NAME}' } | ` + + `Where-Object { Test-Path $_ } | Select-Object -First 1` + ) + const line = stdout.trim().split('\n')[0]?.trim() + return line && existsSync(line) ? line : null +} + +/** Read the ProductVersion string from an exe's version resource. */ +export function getExeVersion(exePath) { + const { stdout } = runCommandSync(`(Get-Item '${exePath}').VersionInfo.ProductVersion`) + return stdout.trim() || null +} + +/** + * Silently uninstall the test install at an EXPLICIT directory via its + * NSIS-generated uninstaller. Best-effort: returns false if no uninstaller is + * found rather than throwing, so teardown never masks the real assertion result. + * + * SAFETY: `installDir` is REQUIRED and must be the exact directory the harness + * installed into this run — there is deliberately no scan-and-discover fallback, + * because a `null` default once made this function locate and uninstall the + * developer's REAL Orca. It additionally refuses to run against the default + * per-user install location unless `allowDefaultLocation` is explicitly set (only + * the owns-the-install non-isolated teardown may do so). + */ +export function silentUninstall(installDir, { allowDefaultLocation = false } = {}) { + assertWin32('silentUninstall') + if (typeof installDir !== 'string' || installDir.trim() === '') { + throw new Error('silentUninstall requires an explicit install directory (no scan fallback)') + } + const resolved = path.resolve(installDir) + if (!allowDefaultLocation && pathsEqual(resolved, path.join(programsRoot(), PRODUCT_NAME))) { + throw new Error( + `Refusing to uninstall the default install location "${resolved}" — this is where a ` + + `developer's REAL Orca lives. Isolated mode must target a separate --install-dir.` + ) + } + const exe = path.join(resolved, EXE_NAME) + if (!existsSync(exe)) { + return false + } + const exeDir = resolved + const uninstaller = path.join(exeDir, `Uninstall ${PRODUCT_NAME}.exe`) + if (!existsSync(uninstaller)) { + return false + } + // NSIS uninstallers must be run from a copy (they relocate themselves); _?= + // forces synchronous, in-place uninstall so we can assert completion. + spawnSync(uninstaller, ['/S', `_?=${exeDir}`], { encoding: 'utf8' }) + sleepSync(2000) + return !existsSync(exe) +} + +/** Case-insensitive path equality after trailing-separator normalization. */ +function pathsEqual(a, b) { + const norm = (p) => + path + .resolve(p) + .replace(/[\\/]+$/, '') + .toLowerCase() + return norm(a) === norm(b) +} + +function sleepSync(ms) { + // Blocking sleep via Atomics keeps install polling simple and synchronous. + const sab = new Int32Array(new SharedArrayBuffer(4)) + Atomics.wait(sab, 0, 0, ms) +} diff --git a/tools/win-update-e2e/interactivity-probes.mjs b/tools/win-update-e2e/interactivity-probes.mjs new file mode 100644 index 000000000..fd58a3546 --- /dev/null +++ b/tools/win-update-e2e/interactivity-probes.mjs @@ -0,0 +1,99 @@ +// Filesystem-sentinel interactivity probes for a packaged terminal session. +// +// These prove a session is interactive without reading the (WebGL) xterm +// buffer: a typed command writes a marker FILE, and the harness checks the +// file. That verifies keystrokes reached the shell AND the shell executed them. + +import { existsSync, statSync, readFileSync, rmSync } from 'node:fs' +import path from 'node:path' +import { sendCtrlC, runShellCommand } from './app-driver.mjs' + +const POLL_MS = 500 + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +async function waitForFile(filePath, timeoutMs) { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + if (existsSync(filePath)) { + return true + } + await delay(POLL_MS) + } + return false +} + +/** + * Type a command that writes a unique token to a sentinel file, then confirm + * the file appears with that token. Proves typed input reaches and runs in the + * active terminal. Returns true on success. + */ +export async function probeEcho(page, runDir, label = 'echo') { + const token = `${label.toUpperCase()}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}` + const file = path.join(runDir, `${label}-${token}.txt`) + await runShellCommand(page, `Set-Content -LiteralPath '${file}' -Value '${token}'`) + const appeared = await waitForFile(file, 15_000) + if (!appeared) { + return false + } + return readFileSync(file, 'utf8').includes(token) +} + +/** Latest mtime (ms) of a file, or 0 if absent. */ +export function fileMtimeMs(filePath) { + try { + return statSync(filePath).mtimeMs + } catch { + return 0 + } +} + +/** + * Confirm a heartbeat file keeps advancing (session is live and streaming). + * Samples twice Poll apart; returns true if the second sample is newer. + */ +export async function probeHeartbeatAdvancing(heartbeatFile) { + const first = fileMtimeMs(heartbeatFile) + await delay(1500) + const second = fileMtimeMs(heartbeatFile) + return second > first && second > 0 +} + +/** + * Ctrl+C on a foreground marker loop: after interrupt the heartbeat must STOP + * advancing and the shell must return to a prompt (a follow-up sentinel command + * runs). Both conditions are required — output stopping alone could be a hang. + */ +export async function probeCtrlCInterruptsMarker(page, runDir, heartbeatFile) { + await sendCtrlC(page) + await delay(1500) + const afterCtrlC = fileMtimeMs(heartbeatFile) + await delay(1500) + const stillLater = fileMtimeMs(heartbeatFile) + const heartbeatStopped = stillLater === afterCtrlC + const promptReturned = await probeEcho(page, runDir, 'post-interrupt') + return heartbeatStopped && promptReturned +} + +/** + * cold-restore Ctrl+C: start a fresh foreground sleep loop in the active (new) + * terminal, interrupt it, then confirm the prompt returns via a sentinel. + */ +export async function probeCtrlCOnFreshLoop(page, runDir) { + const heartbeatFile = path.join(runDir, `fresh-loop-${Date.now()}.txt`) + if (existsSync(heartbeatFile)) { + rmSync(heartbeatFile) + } + await runShellCommand( + page, + `while($true){ [System.IO.File]::WriteAllText('${heartbeatFile}',(Get-Date).ToString('o')); Start-Sleep -Milliseconds 500 }` + ) + // Let the loop spin up and prove it is actually running before interrupting. + const running = await probeHeartbeatAdvancing(heartbeatFile) + if (!running) { + return false + } + return probeCtrlCInterruptsMarker(page, runDir, heartbeatFile) +} diff --git a/tools/win-update-e2e/onboarding-profile.mjs b/tools/win-update-e2e/onboarding-profile.mjs new file mode 100644 index 000000000..dd1d4771d --- /dev/null +++ b/tools/win-update-e2e/onboarding-profile.mjs @@ -0,0 +1,77 @@ +// Persistence seed for a fresh packaged Orca profile: dismisses onboarding and +// registers a throwaway git repo as a project so the harness can open a +// workspace + terminal without the native "Add Project" folder dialog (which +// Playwright cannot drive). +// +// A first-run profile renders a fullscreen onboarding overlay (`fixed inset-0 +// z-[100]`) that intercepts every pointer event; the renderer shows it only +// while `onboarding.closedAt === null` (src/renderer/src/components/onboarding/ +// should-show-onboarding.ts), so writing this object to `/ +// orca-data.json` BEFORE launch dismisses it. The app derives the Projects list +// from the persisted `repos` array (src/main/persistence.ts), so a single repo +// entry pointing at a real git checkout makes the project selectable. +// +// IMPORTANT: seed only BEFORE the first launch. The app rewrites orca-data.json +// on quit; overwriting it before the post-update relaunch would destroy the +// persisted session that the cold-restore/survival assertions depend on. +// +// Onboarding flow-version / final-step mirror src/shared/constants +// (ONBOARDING_FLOW_VERSION=4, ONBOARDING_FINAL_STEP=5); refresh if the app bumps +// the flow version, or a stale version re-arms onboarding. + +import { writeFileSync, mkdirSync } from 'node:fs' +import path from 'node:path' +import { execFileSync } from 'node:child_process' + +const ONBOARDING_FLOW_VERSION = 4 +const ONBOARDING_FINAL_STEP = 5 + +/** + * Create a throwaway git repo under `dir` and return a persisted `Repo` entry + * for it. A real checkout (init + one commit) is required — Orca treats a + * project as a git repository. + */ +export function createSeededRepo(dir) { + mkdirSync(dir, { recursive: true }) + const git = (...args) => execFileSync('git', args, { cwd: dir, stdio: 'ignore' }) + git('init', '-b', 'main') + git('config', 'user.email', 'win-update-e2e@orca.test') + git('config', 'user.name', 'win-update-e2e') + writeFileSync(path.join(dir, 'README.md'), '# win-update-e2e fixture repo\n') + git('add', '-A') + git('commit', '-m', 'seed') + return { + id: '00000000-0000-4000-8000-00000000e2e0', + path: dir, + displayName: 'e2e-fixture', + badgeColor: '#888888', + addedAt: 1 + } +} + +/** The persisted profile object: onboarding dismissed + telemetry opted in + + * an optional seeded repo. */ +export function buildFreshProfile({ repo = null } = {}) { + return { + settings: { + telemetry: { + optedIn: true, + installId: '00000000-0000-4000-8000-000000000000', + existedBeforeTelemetryRelease: false + } + }, + onboarding: { + flowVersion: ONBOARDING_FLOW_VERSION, + closedAt: 1, + outcome: 'completed', + lastCompletedStep: ONBOARDING_FINAL_STEP + }, + repos: repo ? [repo] : [] + } +} + +/** Write a fresh profile into a userData dir before the FIRST launch only. */ +export function seedFreshProfile(userDataDir, profile) { + mkdirSync(userDataDir, { recursive: true }) + writeFileSync(path.join(userDataDir, 'orca-data.json'), `${JSON.stringify(profile, null, 2)}\n`) +} diff --git a/tools/win-update-e2e/platform-guard.mjs b/tools/win-update-e2e/platform-guard.mjs new file mode 100644 index 000000000..faf9fc451 --- /dev/null +++ b/tools/win-update-e2e/platform-guard.mjs @@ -0,0 +1,38 @@ +// Windows-only guards for the packaged-update E2E harness. +// +// This tool drives real NSIS installers, named-pipe daemons, and Win32 window +// enumeration, none of which exist off Windows. Every entry point calls +// assertWin32() so a macOS/Linux invocation fails loudly with a useful message +// instead of throwing an opaque "powershell: command not found" later. + +import { runCommandSync } from './powershell-runner.mjs' + +/** Throw a clear error unless we are on win32. */ +export function assertWin32(context = 'win-update-e2e') { + if (process.platform !== 'win32') { + throw new Error( + `${context} is Windows-only (it drives NSIS installers, named-pipe ` + + `daemons, and Win32 window enumeration). Detected platform ` + + `"${process.platform}". Run it on a Windows machine or CI runner.` + ) + } +} + +/** + * True when this process is running elevated. Non-elevated is the expected, + * supported mode (per-user oneClick NSIS needs no elevation); this is only used + * to print an informational warning during preflight. + */ +export function isElevated() { + if (process.platform !== 'win32') { + return false + } + // Use the WindowsPrincipal role check via PowerShell rather than `whoami`, + // which under a Git Bash / MSYS PATH can resolve to a Unix whoami that + // rejects the /groups flag. + const { stdout } = runCommandSync( + `[bool]([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()` + + `).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)` + ) + return stdout.trim().toLowerCase() === 'true' +} diff --git a/tools/win-update-e2e/powershell-runner.mjs b/tools/win-update-e2e/powershell-runner.mjs new file mode 100644 index 000000000..68561b261 --- /dev/null +++ b/tools/win-update-e2e/powershell-runner.mjs @@ -0,0 +1,87 @@ +// Thin wrapper around Windows PowerShell 5.1 for the harness's Win32 probes. +// +// Everything that inspects windows or processes goes through Windows PowerShell +// (powershell.exe) rather than pwsh, because 5.1 is guaranteed present on every +// Windows box and the .ps1 probes are written for its quirks (notably the +// single-item .Count pitfall — see window-enum.ps1 / daemon-processes.mjs). + +import { spawn, spawnSync } from 'node:child_process' + +const POWERSHELL = 'powershell.exe' +const BASE_ARGS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass'] +// Cap sync probes so a wedged PowerShell call can't block the harness until the +// whole CI job times out. Callers can override via opts.timeout. +const DEFAULT_SYNC_TIMEOUT_MS = 60_000 + +/** + * Run a .ps1 file synchronously and return { code, stdout, stderr }. + * scriptArgs is an array of string arguments passed after -File. + */ +export function runScriptFileSync(scriptPath, scriptArgs = [], opts = {}) { + const result = spawnSync(POWERSHELL, [...BASE_ARGS, '-File', scriptPath, ...scriptArgs], { + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024, + timeout: DEFAULT_SYNC_TIMEOUT_MS, + ...opts + }) + return { + code: result.status ?? (result.error ? -1 : 0), + stdout: result.stdout ?? '', + stderr: result.stderr ?? '', + error: result.error ?? null + } +} + +/** + * Run a .ps1 file whose stdout is a single JSON document and return the parsed + * value. Throws with the raw stderr/stdout attached when parsing fails, so a + * malformed probe surfaces its actual PowerShell error instead of a bare + * SyntaxError. + */ +export function runScriptFileJson(scriptPath, scriptArgs = [], opts = {}) { + const { code, stdout, stderr, error } = runScriptFileSync(scriptPath, scriptArgs, opts) + if (error) { + throw new Error(`Failed to spawn PowerShell for ${scriptPath}: ${error.message}`) + } + const trimmed = stdout.trim() + if (!trimmed) { + throw new Error( + `PowerShell script ${scriptPath} produced no stdout (exit ${code}). stderr:\n${stderr}` + ) + } + try { + return JSON.parse(trimmed) + } catch (parseError) { + throw new Error( + `PowerShell script ${scriptPath} did not emit valid JSON (exit ${code}): ` + + `${parseError.message}\n--- stdout ---\n${trimmed}\n--- stderr ---\n${stderr}` + ) + } +} + +/** + * Spawn a .ps1 file as a long-running background child. Returns the ChildProcess + * so the caller can track/stop it. Used for the window watch loop. + */ +export function spawnScriptFile(scriptPath, scriptArgs = [], opts = {}) { + return spawn(POWERSHELL, [...BASE_ARGS, '-File', scriptPath, ...scriptArgs], { + stdio: ['ignore', 'pipe', 'pipe'], + ...opts + }) +} + +/** Run an inline command string synchronously and return { code, stdout, stderr }. */ +export function runCommandSync(command, opts = {}) { + const result = spawnSync(POWERSHELL, [...BASE_ARGS, '-Command', command], { + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024, + timeout: DEFAULT_SYNC_TIMEOUT_MS, + ...opts + }) + return { + code: result.status ?? (result.error ? -1 : 0), + stdout: result.stdout ?? '', + stderr: result.stderr ?? '', + error: result.error ?? null + } +} diff --git a/tools/win-update-e2e/preflight.mjs b/tools/win-update-e2e/preflight.mjs new file mode 100644 index 000000000..b5218ed01 --- /dev/null +++ b/tools/win-update-e2e/preflight.mjs @@ -0,0 +1,161 @@ +// Preflight safety checks and the baseline window snapshot. +// +// The harness installs, updates, and uninstalls a real app and kills processes +// it created. To avoid ever touching a user's live Orca, it REFUSES to run when +// a pre-existing Orca app process (not a daemon) is already running that it did +// not start. Existing installs and detached daemons are warned about, not +// treated as fatal (the update path is what exercises them). + +import path from 'node:path' +import { assertWin32, isElevated } from './platform-guard.mjs' +import { runCommandSync } from './powershell-runner.mjs' +import { captureBaseline } from './window-watch.mjs' +import { locateInstalledExe } from './installer-steps.mjs' +import { findDaemonProcesses } from './daemon-processes.mjs' + +/** + * Find running Orca APP processes (main window process), excluding daemons. + * The daemon runs as Orca.exe too but always carries the daemon-entry.js marker + * on its command line, so excluding that marker isolates the actual app. The + * ExecutablePath lets isolated mode decide whether a running app is under the + * test dir (fatal) or is the developer's real Orca elsewhere (informational). + */ +export function findAppProcesses() { + const command = [ + `$procs = @(Get-CimInstance Win32_Process -Filter "Name = 'Orca.exe'" -ErrorAction SilentlyContinue |`, + ` Where-Object { -not ($_.CommandLine -match 'daemon-entry\\.js') })`, + `$out = @($procs | ForEach-Object {`, + ` [pscustomobject]@{ pid = $_.ProcessId; path = $_.ExecutablePath; commandLine = $_.CommandLine } })`, + `ConvertTo-Json -InputObject @{ processes = $out } -Depth 4 -Compress` + ].join('\n') + // Fail closed: this guard protects the user's real processes, so a failed + // query must abort the run rather than look like "no Orca is running". + const { stdout, stderr, code, error } = runCommandSync(command) + if (error) { + throw new Error(`Failed to query Orca app processes: ${error.message}`) + } + if (code !== 0) { + throw new Error(`Failed to query Orca app processes (exit ${code}): ${stderr || stdout}`) + } + const trimmed = stdout.trim() + if (!trimmed) { + return [] + } + try { + const parsed = JSON.parse(trimmed) + const arr = parsed.processes + return Array.isArray(arr) ? arr : arr ? [arr] : [] + } catch (parseError) { + throw new Error( + `Orca app process query returned invalid JSON: ${parseError.message}\n` + + `stdout:\n${trimmed}\nstderr:\n${stderr}` + ) + } +} + +/** True if `childPath` is equal to or inside `parentDir` (case-insensitive). */ +function isPathUnder(childPath, parentDir) { + const child = path + .resolve(childPath) + .replace(/[\\/]+$/, '') + .toLowerCase() + const parent = path + .resolve(parentDir) + .replace(/[\\/]+$/, '') + .toLowerCase() + return child === parent || child.startsWith(`${parent}\\`) +} + +/** + * Run preflight. Returns { baseline, warnings, existingInstall }. Throws if a + * pre-existing Orca app is running (never kill a user's process) or if an Orca + * install already exists and allowExistingInstall was not passed (the run would + * overwrite a developer's real build). baselinePath receives the snapshot of + * currently-visible top-level windows. + * + * In isolated mode (`installDir` set) both refusals become target-scoped: only a + * running app whose exe is UNDER installDir is fatal, and only an install already + * in installDir triggers the existing-install refusal. A real Orca running or + * installed elsewhere is untouched by isolated mode and is merely noted. + */ +export function preflight({ baselinePath, allowExistingInstall = false, installDir = null }) { + assertWin32('preflight') + const warnings = [] + const isolated = Boolean(installDir) + + if (isElevated()) { + warnings.push( + 'Running elevated. A per-user oneClick install does not need elevation; ' + + 'an elevated run can install to an unexpected profile.' + ) + } + + const appProcesses = findAppProcesses() + if (isolated) { + const inTarget = appProcesses.filter((p) => p.path && isPathUnder(p.path, installDir)) + if (inTarget.length > 0) { + const listing = inTarget.map((p) => ` pid ${p.pid}: ${p.path}`).join('\n') + throw new Error( + `Refusing to run: ${inTarget.length} Orca app process(es) are running from the ` + + `isolated target dir ${installDir} that this harness did not start. Close them ` + + `first (this harness never kills pre-existing user processes):\n${listing}` + ) + } + const elsewhere = appProcesses.filter((p) => !(p.path && isPathUnder(p.path, installDir))) + if (elsewhere.length > 0) { + warnings.push( + `${elsewhere.length} Orca app process(es) are running from outside the isolated ` + + `target dir (pids: ${elsewhere.map((p) => p.pid).join(', ')}). Isolated mode never ` + + `touches them; proceeding.` + ) + } + } else if (appProcesses.length > 0) { + const listing = appProcesses.map((p) => ` pid ${p.pid}: ${p.commandLine}`).join('\n') + throw new Error( + `Refusing to run: ${appProcesses.length} Orca app process(es) are already ` + + `running that this harness did not start. Close them first (this harness ` + + `never kills pre-existing user processes):\n${listing}` + ) + } + + // Scope the existing-install check to the target dir in isolated mode; an + // install at the default location is left untouched and does not count. + const existingInstall = isolated ? locateInstalledExe(installDir) : locateInstalledExe() + if (existingInstall && !allowExistingInstall) { + throw new Error( + isolated + ? `Refusing to run: an install already exists in the isolated target dir ` + + `${existingInstall}. Pass --allow-existing-install to overwrite it (isolated mode ` + + `never touches the real install elsewhere), or point --install-dir at an empty dir.` + : `Refusing to run: an Orca install already exists at ${existingInstall}. ` + + `This run would silently OVERWRITE it with the --from/--to versions and ` + + `leave the --to version installed — destroying a real Orca install on a ` + + `developer machine. Pass --allow-existing-install to proceed anyway ` + + `(your prior build will NOT be restored), or uninstall Orca first. Clean ` + + `machines (CI/VM) never hit this.` + ) + } + if (existingInstall && !isolated) { + warnings.push( + `--allow-existing-install set: the existing install at ${existingInstall} will be ` + + `overwritten and the --to version left installed; teardown will NOT uninstall it.` + ) + } else if (existingInstall) { + warnings.push( + `A prior harness install exists in the target dir ${existingInstall}; it will be ` + + `overwritten and cleaned up at teardown (isolated mode owns the test dir).` + ) + } + + const existingDaemons = findDaemonProcesses() + if (existingDaemons.length > 0) { + warnings.push( + `${existingDaemons.length} pre-existing daemon process(es) found on this machine ` + + `(pids: ${existingDaemons.map((d) => d.pid).join(', ')}). The run uses an isolated ` + + `userData dir, so its daemon is tracked by scope and will not collide.` + ) + } + + const baseline = captureBaseline(baselinePath) + return { baseline, warnings, existingInstall } +} diff --git a/tools/win-update-e2e/registry-shortcut-backup.mjs b/tools/win-update-e2e/registry-shortcut-backup.mjs new file mode 100644 index 000000000..59f66e914 --- /dev/null +++ b/tools/win-update-e2e/registry-shortcut-backup.mjs @@ -0,0 +1,312 @@ +// Snapshot and restore the per-user install state that an NSIS install hijacks. +// +// electron-builder's NSIS honors the /D install-dir override for FILE layout, so +// isolated mode installs into a separate directory. But regardless of /D, the +// installer writes InstallLocation + the uninstall entry to the SAME per-user +// HKCU keys as the real install, and rewrites the Start Menu / Desktop shortcuts +// (node_modules/app-builder-lib/templates/nsis/include/installer.nsh). Left +// hijacked, a developer's next REAL update would target the test directory. +// +// This module snapshots those shared keys + shortcuts before an isolated run and +// restores them at teardown, always. All registry access is via reg.exe (atomic +// export/import/delete); discovery is read-only PowerShell. + +import { existsSync, mkdirSync, copyFileSync, writeFileSync, readdirSync, rmSync } from 'node:fs' +import path from 'node:path' +import { execFileSync } from 'node:child_process' +import { runCommandSync } from './powershell-runner.mjs' + +const UNINSTALL_ROOT = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall' +const APP_ROOT = 'HKCU\\Software' + +/** + * Read-only discovery of the machine's current Orca install registry state. + * The uninstall entry is found by DisplayName (electron-builder writes the app + * GUID as the key name, not a fixed string); the app key that carries + * InstallLocation is found under HKCU\Software by its ShortcutName/InstallLocation. + * Returns concrete reg.exe key paths + the current InstallLocation value (all + * null when no install exists). + */ +export function discoverInstallRegistryState() { + const ps = [ + `$un = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'`, + `$uninstallName = $null; $displayName = $null; $displayVersion = $null`, + `foreach ($k in @(Get-ChildItem $un -ErrorAction SilentlyContinue)) {`, + ` $dn = $k.GetValue('DisplayName'); $il = $k.GetValue('InstallLocation')`, + ` if ($dn -eq 'Orca' -or ($il -and $il -match '\\\\Programs\\\\orca')) {`, + ` $uninstallName = $k.PSChildName; $displayName = $dn; $displayVersion = $k.GetValue('DisplayVersion')`, + ` }`, + `}`, + `$appName = $null; $installLocation = $null`, + `foreach ($k in @(Get-ChildItem 'HKCU:\\Software' -ErrorAction SilentlyContinue)) {`, + ` $il = $k.GetValue('InstallLocation'); $sn = $k.GetValue('ShortcutName')`, + ` if ($il -and ($sn -eq 'Orca' -or $il -match 'orca')) {`, + ` $appName = $k.PSChildName; $installLocation = $il`, + ` }`, + `}`, + `ConvertTo-Json -Compress -InputObject @{ uninstallName = $uninstallName; appName = $appName; installLocation = $installLocation; displayName = $displayName; displayVersion = $displayVersion }` + ].join('\n') + const { stdout } = runCommandSync(ps) + let parsed = {} + try { + parsed = JSON.parse(stdout.trim() || '{}') + } catch { + parsed = {} + } + return { + uninstallKey: parsed.uninstallName ? `${UNINSTALL_ROOT}\\${parsed.uninstallName}` : null, + appKey: parsed.appName ? `${APP_ROOT}\\${parsed.appName}` : null, + installLocation: parsed.installLocation || null, + displayName: parsed.displayName || null, + displayVersion: parsed.displayVersion || null + } +} + +/** The two directories NSIS writes Orca shortcuts into: Start Menu + Desktop. */ +export function shortcutDirs() { + const appData = + process.env.APPDATA ?? path.join(process.env.USERPROFILE ?? '', 'AppData', 'Roaming') + const startMenu = path.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs') + return [startMenu, resolveDesktopDir()] +} + +function resolveDesktopDir() { + // Desktop can be redirected (OneDrive), so resolve via the shell folder API + // rather than assuming %USERPROFILE%\Desktop. + const { stdout } = runCommandSync(`[Environment]::GetFolderPath('Desktop')`) + const line = stdout.trim() + if (line && existsSync(line)) { + return line + } + return path.join(process.env.USERPROFILE ?? '', 'Desktop') +} + +/** Read-only: list Orca *.lnk shortcuts under the given dirs (recursive). */ +export function discoverOrcaShortcuts(dirs = shortcutDirs()) { + const found = [] + for (const dir of dirs) { + collectOrcaLnks(dir, found) + } + return found +} + +function collectOrcaLnks(dir, out) { + if (!existsSync(dir)) { + return + } + let entries = [] + try { + entries = readdirSync(dir, { withFileTypes: true }) + } catch { + return + } + for (const entry of entries) { + const full = path.join(dir, entry.name) + if (entry.isDirectory()) { + collectOrcaLnks(full, out) + } else if (entry.isFile() && /\.lnk$/i.test(entry.name) && /orca/i.test(entry.name)) { + out.push(full) + } + } +} + +/** + * Snapshot the shared install registry keys + Orca shortcuts before an isolated + * install writes over them. `reg export`s each existing key and copies each + * existing shortcut into runDir, recording a manifest of what pre-existed (and + * the pre-run InstallLocation) so restore knows what to put back vs. delete. + */ +export function backupInstallState(runDir) { + const backupDir = path.join(runDir, 'install-state-backup') + mkdirSync(backupDir, { recursive: true }) + const state = discoverInstallRegistryState() + const dirs = shortcutDirs() + const manifest = { + backupDir, + shortcutDirs: dirs, + installLocation: state.installLocation, + uninstall: null, + app: null, + shortcuts: [] + } + if (state.uninstallKey) { + const regFile = path.join(backupDir, 'uninstall.reg') + if (regExport(state.uninstallKey, regFile)) { + manifest.uninstall = { path: state.uninstallKey, regFile } + } + } + if (state.appKey) { + const regFile = path.join(backupDir, 'app.reg') + if (regExport(state.appKey, regFile)) { + manifest.app = { path: state.appKey, regFile } + } + } + let i = 0 + for (const lnk of discoverOrcaShortcuts(dirs)) { + const backup = path.join(backupDir, `shortcut-${i}-${path.basename(lnk)}`) + try { + copyFileSync(lnk, backup) + manifest.shortcuts.push({ path: lnk, backup }) + } catch { + manifest.shortcuts.push({ path: lnk, backup: null }) + } + i += 1 + } + writeFileSync(path.join(backupDir, 'manifest.json'), JSON.stringify(manifest, null, 2)) + return manifest +} + +/** + * Restore the shared install state captured by backupInstallState. Keys that + * pre-existed are `reg import`ed back to their original values; keys that did NOT + * pre-exist but exist now (created by the test install) are `reg delete`d. + * Pre-existing shortcuts are copied back; test-created Orca shortcuts are removed. + * Finally re-reads InstallLocation and, on mismatch, prints a LOUD block with the + * exact manual `reg import` command to recover. + */ +export function restoreInstallState(manifest) { + const result = { + imported: [], + deleted: [], + failures: [], + shortcutsRestored: [], + shortcutsDeleted: [], + verified: false + } + const current = discoverInstallRegistryState() + + if (manifest.uninstall) { + if (regImport(manifest.uninstall.regFile)) { + result.imported.push(manifest.uninstall.path) + } else { + result.failures.push(`Failed to import ${manifest.uninstall.regFile}`) + } + } else if (current.uninstallKey) { + if (regDelete(current.uninstallKey)) { + result.deleted.push(current.uninstallKey) + } else { + result.failures.push(`Failed to delete ${current.uninstallKey}`) + } + } + + if (manifest.app) { + if (regImport(manifest.app.regFile)) { + result.imported.push(manifest.app.path) + } else { + result.failures.push(`Failed to import ${manifest.app.regFile}`) + } + } else if (current.appKey) { + if (regDelete(current.appKey)) { + result.deleted.push(current.appKey) + } else { + result.failures.push(`Failed to delete ${current.appKey}`) + } + } + + restoreShortcuts(manifest, result) + + const after = discoverInstallRegistryState() + // A silently-failed import/delete can leave stale keys while InstallLocation + // still matches, so restore isn't "verified" unless every op also succeeded. + result.verified = + result.failures.length === 0 && + normLoc(manifest.installLocation) === normLoc(after.installLocation) + if (!result.verified) { + printMismatchWarning(manifest, manifest.installLocation, after.installLocation) + } + return result +} + +function restoreShortcuts(manifest, result) { + const preExisting = new Set(manifest.shortcuts.map((s) => s.path.toLowerCase())) + for (const s of manifest.shortcuts) { + if (s.backup && existsSync(s.backup)) { + try { + copyFileSync(s.backup, s.path) + result.shortcutsRestored.push(s.path) + } catch { + /* best effort — a missing dir means the shortcut target is gone anyway */ + } + } + } + for (const lnk of discoverOrcaShortcuts(manifest.shortcutDirs)) { + if (!preExisting.has(lnk.toLowerCase())) { + try { + rmSync(lnk, { force: true }) + result.shortcutsDeleted.push(lnk) + } catch { + /* best effort */ + } + } + } +} + +function printMismatchWarning(manifest, expected, actual) { + const bar = '!'.repeat(72) + const importCmds = [] + if (manifest.app) { + importCmds.push(`reg import "${manifest.app.regFile}"`) + } + if (manifest.uninstall) { + importCmds.push(`reg import "${manifest.uninstall.regFile}"`) + } + const recovery = + importCmds.length > 0 ? importCmds : ['(no backup was captured — no manual import available)'] + console.error(`\n${bar}`) + console.error('!! WIN-UPDATE-E2E: REGISTRY RESTORE VERIFICATION FAILED') + console.error(`!! Expected InstallLocation: ${expected ?? '(none / no pre-existing install)'}`) + console.error(`!! Actual InstallLocation: ${actual ?? '(none)'}`) + console.error('!! Your REAL Orca install pointer may be hijacked to the test directory.') + console.error('!! The next real Orca update could install into the test location.') + console.error('!! Recover manually by running these command(s) in an elevated-free shell:') + for (const cmd of recovery) { + console.error(`!! ${cmd}`) + } + console.error(`${bar}\n`) +} + +function normLoc(value) { + if (!value) { + return '' + } + return value.replace(/[\\/]+$/, '').toLowerCase() +} + +function regExport(keyPath, file) { + try { + execFileSync('reg', ['export', keyPath, file, '/y'], { stdio: 'ignore' }) + return existsSync(file) + } catch { + return false + } +} + +function regImport(file) { + if (!file || !existsSync(file)) { + return false + } + try { + execFileSync('reg', ['import', file], { stdio: 'ignore' }) + return true + } catch { + return false + } +} + +function regDelete(keyPath) { + try { + execFileSync('reg', ['delete', keyPath, '/f'], { stdio: 'ignore' }) + return true + } catch { + return false + } +} + +// Standalone read-only mode: print what an isolated run would snapshot. Touches +// nothing. `node registry-shortcut-backup.mjs` +if (process.argv[1] && path.resolve(process.argv[1]) === import.meta.filename) { + console.log('[registry-shortcut-backup] discovered install registry state:') + console.log(JSON.stringify(discoverInstallRegistryState(), null, 2)) + console.log('[registry-shortcut-backup] Orca shortcuts that would be backed up:') + console.log(JSON.stringify(discoverOrcaShortcuts(), null, 2)) +} diff --git a/tools/win-update-e2e/run.mjs b/tools/win-update-e2e/run.mjs new file mode 100644 index 000000000..7c8d8cde6 --- /dev/null +++ b/tools/win-update-e2e/run.mjs @@ -0,0 +1,628 @@ +// win-update-e2e — packaged NSIS update proof harness. +// +// Given two Orca Windows installers (version N and N+1), proves what happens to +// the terminal daemon and its sessions across a real silent update, with +// machine-checkable assertions. Windows-only. See README.md for usage and the +// design context in docs/windows-terminal-update-survival-plan.md (Phase 0). + +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { execFileSync } from 'node:child_process' +import { assertWin32 } from './platform-guard.mjs' +import { parseArgs } from './cli-args.mjs' +import { preflight } from './preflight.mjs' +import { resolveInstaller, silentInstall, silentUninstall } from './installer-steps.mjs' +import { backupInstallState, restoreInstallState } from './registry-shortcut-backup.mjs' +import { + launchInstalledApp, + ensureTerminal, + dismissOverlays, + createTerminalTab, + listTabIds, + startMarker, + readTerminalTextBestEffort, + closeApp, + captureFailureDiagnostics +} from './app-driver.mjs' +import { readDaemonPidFiles, findDaemonProcesses, isPidAlive } from './daemon-processes.mjs' +import { startWatch } from './window-watch.mjs' +import { + probeEcho, + probeHeartbeatAdvancing, + probeCtrlCInterruptsMarker, + probeCtrlCOnFreshLoop, + fileMtimeMs +} from './interactivity-probes.mjs' +import { buildAssertions, renderTable, allPassed } from './assertions.mjs' +import { createSeededRepo, buildFreshProfile } from './onboarding-profile.mjs' + +function log(step, msg) { + console.log(`[win-update-e2e] ${step}: ${msg}`) +} + +async function main() { + const opts = parseArgs(process.argv.slice(2)) + if (opts.help) { + console.log(opts.usage) + return 0 + } + if (opts.errors?.length) { + console.error(`Argument errors:\n - ${opts.errors.join('\n - ')}\n${opts.usage}`) + return 2 + } + assertWin32('win-update-e2e') + + const installDir = opts.installDir ?? null + const isolated = Boolean(installDir) + + const runId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}` + const canary = `ORCA-E2E-CANARY-${runId}` + const runDir = mkdtempSync(path.join(tmpdir(), `orca-win-update-e2e-${runId}-`)) + const userDataDir = path.join(runDir, 'userData') + const baselinePath = path.join(runDir, 'baseline.json') + const watchOut = path.join(runDir, 'window-watch.jsonl') + const markerPidFile = path.join(runDir, 'marker.pid') + const heartbeatFile = path.join(runDir, 'heartbeat.txt') + const created = { markerPid: null, daemonPids: new Set() } + + log( + 'setup', + `runId=${runId} runDir=${runDir} profile=${opts.expect}${isolated ? ` installDir=${installDir}` : ''}` + ) + if (isolated && opts.keepInstall) { + log( + 'setup', + '--keep-install is ignored in isolated mode: the test install and its per-user ' + + 'registry hijack are always cleaned up so the real install stays safe.' + ) + } + + const { warnings, existingInstall } = preflight({ + baselinePath, + allowExistingInstall: opts.allowExistingInstall, + installDir + }) + const hadPreexistingInstall = Boolean(existingInstall) + for (const w of warnings) { + log('preflight-warning', w) + } + + // Isolated mode: snapshot the shared per-user registry keys + shortcuts BEFORE + // any install writes over them. Everything after this must run through the + // try/finally so the snapshot is always restored, even on failure. + let manifest = null + if (isolated) { + manifest = backupInstallState(runDir) + log('isolated', `backed up install registry/shortcut state -> ${manifest.backupDir}`) + } + + const runArgs = { + opts, + installDir, + canary, + runDir, + userDataDir, + baselinePath, + watchOut, + markerPidFile, + heartbeatFile, + created + } + + // Both paths ALWAYS tear down (close the app, kill the marker/watch, uninstall) + // and, in isolated mode, restore registry/shortcuts — whatever happens in the + // proof body. A driving failure captures diagnostics first, then surfaces as a + // FATAL. Teardown in a finally is what keeps a driving hang from pinning the + // Node process alive until the CI job timeout. + const ctx = { session: null } + const diagDir = process.env.ORCA_E2E_DIAG_DIR || path.join(runDir, 'diag') + let passed = false + try { + passed = await runProof(ctx, runArgs) + } catch (err) { + console.error(`[win-update-e2e] FATAL: ${err.stack || err.message}`) + if (ctx.session?.page) { + const diag = await captureFailureDiagnostics(ctx.session.page, diagDir, 'driving-failure') + log('diag', `captured -> ${diagDir} (store=${diag.info?.hasStore ?? 'n/a'})`) + if (diag.info?.bodyText) { + log('diag', `visible text: ${diag.info.bodyText.replace(/\s+/g, ' ').slice(0, 300)}`) + } + } + passed = false + } finally { + await (isolated + ? isolatedTeardown({ + app: ctx.session?.app, + created, + userDataDir, + installDir, + manifest, + runDir + }) + : teardown({ + app: ctx.session?.app, + created, + userDataDir, + keepInstall: opts.keepInstall, + hadPreexistingInstall, + installedExePath: ctx.installedExePath ?? null, + runDir + })) + } + return passed ? 0 : 1 +} + +/** + * Run the install → drive → update → relaunch → assert proof. `ctx.session` is + * assigned as soon as each app launches so a caller's finally can tear down a + * partially-created session on failure. Returns whether every assertion passed. + */ +async function runProof(ctx, args) { + const { + opts, + installDir, + canary, + runDir, + userDataDir, + baselinePath, + watchOut, + markerPidFile, + heartbeatFile, + created + } = args + + const fromInstaller = resolveInstaller({ + localPath: opts.from, + releaseTag: opts.fromRelease, + assetPattern: opts.assetPattern + }) + log('install-base', `installing ${fromInstaller}`) + const base = silentInstall(fromInstaller, { installDir }) + // Track the install now (not only after the update at L238) so a failure + // anywhere before the update still tears down the base install this harness + // created, instead of orphaning it and blocking the next run's preflight. + ctx.installedExePath = base.exePath + log('install-base', `installed ${base.exePath} (version ${base.version})`) + + // Seed a fresh profile (onboarding dismissed + one throwaway git repo as a + // project) ONLY before the first launch. The relaunch must use the app's own + // persisted state so the cold-restore/survival assertions are meaningful. + const seededRepo = createSeededRepo(path.join(runDir, 'fixture-repo')) + const seedProfile = buildFreshProfile({ repo: seededRepo }) + + // --- Base version: launch, create sessions, start marker, record daemon --- + let session = await launchInstalledApp({ exePath: base.exePath, userDataDir, seedProfile }) + ctx.session = session + // A fresh profile has no terminal yet, so create a workspace + terminal, then + // clear the post-creation overlays that would intercept typing. + await ensureTerminal(session.page, { allowCreate: true }) + await dismissOverlays(session.page) + const tabIds = await listTabIds(session.page) + log('sessions', `terminal ready; tab ids: ${tabIds.join(', ')}`) + + // Baseline typed-input on the IDLE shell, before the perpetual marker loop + // takes over the foreground (a command typed against a running loop can't + // execute, so this must precede startMarker to be meaningful). + const echoBeforeUpdate = await probeEcho(session.page, runDir, 'echo-pre') + log('sessions', `pre-update echo interactive: ${echoBeforeUpdate}`) + + await startMarker(session.page, { canary, pidFile: markerPidFile, heartbeatFile }) + const markerLive = await probeHeartbeatAdvancing(heartbeatFile) + created.markerPid = readIntFile(markerPidFile) + log('marker', `pid=${created.markerPid} heartbeatAdvancing=${markerLive}`) + + const preDaemon = resolveScopedDaemon(userDataDir) + preDaemon.pids.forEach((p) => created.daemonPids.add(p)) + log('daemon', `pre-update daemon pid=${preDaemon.pid} appVersion=${preDaemon.appVersion}`) + log('daemon', `pre-update daemon exe: ${preDaemon.exePath ?? '(unknown)'}`) + + const preScrollback = await readTerminalTextBestEffort(session.page) + + // Close app normally; the detached daemon must remain alive. + await closeApp(session.app) + const daemonAliveAfterClose = preDaemon.pid != null && isPidAlive(preDaemon.pid) + log('daemon', `alive after app close: ${daemonAliveAfterClose}`) + + // --- Start the console-window watch through the whole update + soak --- + const watchDuration = 120 + opts.soakSeconds + const watch = startWatch({ baselinePath, outPath: watchOut, durationSec: watchDuration }) + log('watch', `started (duration ${watchDuration}s) -> ${watchOut}`) + + // --- Update: install N+1 --- + const toInstaller = resolveInstaller({ + localPath: opts.to, + releaseTag: opts.toRelease, + assetPattern: opts.assetPattern + }) + log('update', `installing ${toInstaller}`) + const updated = silentInstall(toInstaller, { installDir }) + // Record the exact dir the harness installed into so non-isolated teardown + // uninstalls THAT and never scan-discovers the developer's real install. + ctx.installedExePath = updated.exePath + log('update', `installed ${updated.exePath} (version ${updated.version})`) + + // --- Relaunch and gather post-update evidence --- + session = await launchInstalledApp({ exePath: updated.exePath, userDataDir }) + ctx.session = session + // No create on relaunch: the session must be RESTORED, not freshly made. + await ensureTerminal(session.page, { allowCreate: false }) + await dismissOverlays(session.page) + + const evidence = await gatherEvidence({ + profile: opts.expect, + page: session.page, + runDir, + heartbeatFile, + preDaemon, + userDataDir, + preScrollback, + echoBeforeUpdate + }) + evidence.postDaemon?.pids?.forEach((p) => created.daemonPids.add(p)) + + // --- Soak, then stop the watch and evaluate --- + log('soak', `waiting ${opts.soakSeconds}s for delayed flashes`) + await delay(opts.soakSeconds * 1000) + const { events } = await watch.stop() + log('watch', `recorded ${events.length} new-window events`) + + const assertionCtx = { + profile: opts.expect, + canary, + watchEvents: events, + markerPid: created.markerPid, + daemonLog: readDaemonLog(userDataDir), + ...evidence + } + const assertions = buildAssertions(assertionCtx) + const passed = allPassed(assertions) + console.log(renderTable(assertions)) + log('result', passed ? 'PASS' : 'FAIL') + return passed +} + +async function gatherEvidence(args) { + const { profile, page, runDir, heartbeatFile, preDaemon, userDataDir, preScrollback } = args + const postDaemon = resolveScopedDaemon(userDataDir) + + if (profile === 'survival') { + // The decisive survival signals: did the SPECIFIC pre-update daemon process + // live through the update, and is the new app running that same relocated + // exe or a fresh in-dir fork? Log both regardless of the assertion outcome. + const preDaemonAliveAfter = preDaemon.pid != null && isPidAlive(preDaemon.pid) + log( + 'daemon', + `post-update daemon pid=${postDaemon.pid} exe: ${postDaemon.exePath ?? '(unknown)'}` + ) + log( + 'daemon', + `pre-update daemon pid=${preDaemon.pid} still alive after update: ${preDaemonAliveAfter}` + ) + dumpDaemonLog(userDataDir) + const heartbeatBefore = fileMtimeMs(heartbeatFile) + const heartbeatAdvancedAfterUpdate = await heartbeatAdvancedSince( + heartbeatFile, + heartbeatBefore + ) + // Sample marker survival BEFORE interrupting it: the pre-update shell must be + // measured while its heartbeat loop still runs, not after + // probeCtrlCInterruptsMarker deliberately breaks that loop. + const markerAliveAfter = isMarkerAlive(runDir) + log( + 'marker', + `pid=${readIntFile(path.join(runDir, 'marker.pid'))} aliveAfterUpdate=${markerAliveAfter}` + ) + // Interrupt the foreground loop first so the shell returns to a prompt; only + // then can a freshly-typed command execute. Typing while the infinite + // heartbeat loop owns the shell never runs, regardless of input health — so + // the echo probe is meaningful only after the interrupt. + const ctrlCInterrupted = await probeCtrlCInterruptsMarker(page, runDir, heartbeatFile) + const echoObserved = await probeEcho(page, runDir, 'echo-post') + return { + preDaemonPid: preDaemon.pid, + preDaemonAliveAfter, + postDaemonPid: postDaemon.pid, + postDaemonAlive: postDaemon.pid != null && isPidAlive(postDaemon.pid), + postDaemon, + markerAliveAfter, + heartbeatAdvancedAfterUpdate, + echoObserved, + ctrlCInterrupted + } + } + + // cold-restore + const postScrollback = await readTerminalTextBestEffort(page) + const scrollbackRestored = scrollbackFidelity(preScrollback, postScrollback) + await createTerminalTab(page) + const echoObserved = await probeEcho(page, runDir, 'echo-fresh') + const ctrlCInterrupted = await probeCtrlCOnFreshLoop(page, runDir) + return { + preDaemonPid: preDaemon.pid, + preDaemonAliveAfter: preDaemon.pid != null && isPidAlive(preDaemon.pid), + postDaemonPid: postDaemon.pid, + postDaemonAlive: postDaemon.pid != null && isPidAlive(postDaemon.pid), + postDaemon, + scrollbackRestored, + echoObserved, + ctrlCInterrupted + } +} + +/** + * Resolve THIS run's daemon, scoped to its isolated userData dir so unrelated + * daemons on the machine are ignored. Prefers the pid file (authoritative, + * carries appVersion); cross-checks the live process scan. + */ +function resolveScopedDaemon(userDataDir) { + const pidFiles = readDaemonPidFiles(userDataDir) + const scan = findDaemonProcesses(userDataDir) + const pids = new Set() + for (const rec of pidFiles) { + if (typeof rec.pid === 'number') { + pids.add(rec.pid) + } + } + for (const proc of scan) { + if (typeof proc.pid === 'number') { + pids.add(proc.pid) + } + } + const primary = pidFiles.find((r) => typeof r.pid === 'number') + const pid = primary?.pid ?? scan[0]?.pid ?? null + const scanEntry = scan.find((p) => p.pid === pid) ?? scan[0] + return { + pid, + appVersion: primary?.appVersion ?? null, + startedAtMs: primary?.startedAtMs ?? null, + // Why: the daemon's exe path (first token of its command line) tells us + // whether it was forked from the relocated userData/daemon-host copy or the + // install-dir Orca.exe — the key survival signal. + exePath: daemonExePath(scanEntry?.commandLine), + pids: [...pids] + } +} + +/** Print the daemon's lifecycle log (Phase 0) so its startup/session events are + * visible in the CI log before teardown removes the userData dir. */ +function dumpDaemonLog(userDataDir) { + const logPath = path.join(userDataDir, 'logs', 'daemon.log') + try { + const lines = readFileSync(logPath, 'utf8').trim().split('\n') + log('daemon-log', `${logPath} (${lines.length} lines):`) + for (const line of lines.slice(-40)) { + console.log(` ${line}`) + } + } catch { + log('daemon-log', `${logPath} (unavailable)`) + } +} + +/** Extract the host exe path (first token) from a daemon command line. */ +function daemonExePath(commandLine) { + if (typeof commandLine !== 'string') { + return null + } + const trimmed = commandLine.trim() + if (trimmed.startsWith('"')) { + const end = trimmed.indexOf('"', 1) + return end > 0 ? trimmed.slice(1, end) : null + } + const space = trimmed.indexOf(' ') + return space > 0 ? trimmed.slice(0, space) : trimmed +} + +function isMarkerAlive(runDir) { + const pid = readIntFile(path.join(runDir, 'marker.pid')) + return pid != null && isPidAlive(pid) +} + +async function heartbeatAdvancedSince(heartbeatFile, sinceMs) { + await delay(1500) + return fileMtimeMs(heartbeatFile) > sinceMs +} + +function scrollbackFidelity(before, after) { + // WebGL renderer can leave both empty; report unknown (null) rather than a + // false failure. When text is available, check a stable prefix survived. + if (!before || !before.trim() || !after || !after.trim()) { + return null + } + const marker = before + .trim() + .split('\n') + .find((l) => l.trim().length > 3) + if (!marker) { + return null + } + return after.includes(marker.trim()) +} + +export function readDaemonLog(userDataDir) { + // The daemon log (when present) is JSONL: { src, ts, pid, event, ...details }. + // Only genuinely-bad records fail a run — matched by EVENT NAME, not by any + // string containing "error". The daemon logs benign 'uncaught-exception- + // suppressed' events with name:"Error" for native PTY errors it intentionally + // swallows (src/main/daemon/daemon-entry.ts); those must never fail, and + // 'client-hello-rejected' with reason expected-hello/protocol-mismatch is + // normal version-skew during an update. Non-JSON lines fall back to a raw + // FATAL match so an unstructured crash dump still counts. + const logPath = path.join(userDataDir, 'logs', 'daemon.log') + if (!existsSync(logPath)) { + return null + } + const errorLines = [] + let suppressedCount = 0 + for (const raw of readFileSync(logPath, 'utf8').split('\n')) { + const line = raw.trim() + if (!line) { + continue + } + let rec + try { + rec = JSON.parse(line) + } catch { + if (/\bFATAL\b/.test(line)) { + errorLines.push(line) + } + continue + } + if (rec.event === 'uncaught-exception-suppressed') { + suppressedCount += 1 + } else if ( + rec.event === 'uncaught-exception-fatal' || + (rec.event === 'client-hello-rejected' && rec.reason === 'invalid-token') + ) { + errorLines.push(line) + } + } + return { path: logPath, errorLines, suppressedCount } +} + +/** + * Isolated-mode teardown. The harness OWNS the isolated dir by construction, so + * it always uninstalls the test install, then ALWAYS restores the shared per-user + * registry keys + shortcuts the installer hijacked (the uninstaller clears the + * test install's copies; restore re-imports the real install's originals or + * deletes freshly-created keys). Finally removes the emptied install dir + runDir. + */ +async function isolatedTeardown({ app, created, userDataDir, installDir, manifest, runDir }) { + try { + await closeApp(app) + } catch { + /* already closed / never launched */ + } + killPid(created.markerPid) + for (const pid of resolveScopedDaemon(userDataDir).pids) { + killPid(pid) + } + for (const pid of created.daemonPids) { + killPid(pid) + } + + const uninstalled = silentUninstall(installDir) + log('isolated-teardown', `uninstalled test install: ${uninstalled}`) + + try { + const restore = restoreInstallState(manifest) + log( + 'isolated-teardown', + `registry restore verified=${restore.verified} imported=[${restore.imported.join(', ')}] ` + + `deleted=[${restore.deleted.join(', ')}] shortcutsRestored=${restore.shortcutsRestored.length} ` + + `shortcutsDeleted=${restore.shortcutsDeleted.length}` + ) + } catch (err) { + // Restore must never be silently skipped — surface it loudly and point at the + // manifest so the shared keys can be recovered by hand. + console.error( + `\n*** WIN-UPDATE-E2E: registry/shortcut restore THREW: ${err.stack || err.message}\n` + + ` Recover manually from the backups under ${manifest?.backupDir}. ***\n` + ) + } + + removeDirIfEmpty(installDir) + rmSync(runDir, { recursive: true, force: true }) +} + +/** Remove a directory only if it is empty (best-effort; leaves non-empty dirs). */ +function removeDirIfEmpty(dir) { + try { + if (existsSync(dir) && readdirSync(dir).length === 0) { + rmSync(dir, { recursive: true, force: true }) + } + } catch { + /* leave it in place */ + } +} + +async function teardown({ + app, + created, + userDataDir, + keepInstall, + hadPreexistingInstall, + installedExePath, + runDir +}) { + try { + await closeApp(app) + } catch { + /* already closed */ + } + // Kill ONLY processes this harness created: the marker and this run's daemon + // (scoped to the isolated userData). Never touch pre-existing user processes. + killPid(created.markerPid) + for (const pid of resolveScopedDaemon(userDataDir).pids) { + killPid(pid) + } + for (const pid of created.daemonPids) { + killPid(pid) + } + + if (keepInstall) { + log('teardown', `--keep-install set; leaving install + ${runDir}`) + return + } + // Only uninstall when the harness fully OWNS the install (no pre-existing + // build). When it overwrote a developer's existing install, leave it in place + // — uninstalling would remove a build we did not put there. + if (hadPreexistingInstall) { + console.log( + '\n*** NOTE: an Orca install existed before this run. It was OVERWRITTEN and the\n' + + ' --to version is now installed. Your prior build was NOT restored — reinstall\n' + + ' your intended build if needed. Skipping uninstall. ***\n' + ) + } else if (installedExePath) { + // Uninstall ONLY the exact directory the harness installed into this run, + // with the explicit default-location opt-in (non-isolated mode legitimately + // installs to the default path and owns it here). Never scan-and-discover. + const uninstalled = silentUninstall(path.dirname(installedExePath), { + allowDefaultLocation: true + }) + log('teardown', `uninstalled: ${uninstalled}`) + } else { + log('teardown', 'no install path recorded; skipping uninstall (nothing owned to remove)') + } + rmSync(runDir, { recursive: true, force: true }) +} + +function killPid(pid) { + if (!Number.isInteger(pid) || pid <= 0) { + return + } + try { + execFileSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }) + } catch { + /* already dead */ + } +} + +function readIntFile(filePath) { + try { + const n = Number(readFileSync(filePath, 'utf8').trim()) + return Number.isInteger(n) ? n : null + } catch { + return null + } +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +// Only run the orchestrator when invoked directly, so the module (and +// readDaemonLog) can be imported by tests without kicking off a real install. +if (process.argv[1] && path.resolve(process.argv[1]) === import.meta.filename) { + main() + .then((code) => { + // Why: force-exit. A launched Electron app or the window-watch child can + // keep libuv handles open; without this the process lingers to the CI job + // timeout instead of exiting when the run is logically done. + process.exit(code) + }) + .catch((err) => { + console.error('[win-update-e2e] FATAL:', err.stack || err.message) + process.exit(1) + }) +} diff --git a/tools/win-update-e2e/window-enum.ps1 b/tools/win-update-e2e/window-enum.ps1 new file mode 100644 index 000000000..c628ae115 --- /dev/null +++ b/tools/win-update-e2e/window-enum.ps1 @@ -0,0 +1,122 @@ +<# + window-enum.ps1 — enumerate visible top-level windows with owner attribution. + + Dot-source this file, then call Get-VisibleTopLevelWindows. It returns objects + { handle, pid, processName, title } for every visible, non-cloaked top-level + window that has a title. + + WHY window enumeration (and never conhost command-line heuristics): the July + 2026 post-mortem proved that (a) conhost flag interpretation inverts depending + on the parent's console state, and (b) MainWindowHandle is 0 for + Windows-Terminal-hosted consoles, so handle-based "is it visible" checks read + a visibly-flashing window as hidden. The only sound signal is a real visible + top-level window, attributed to an owner process and (for our own children) a + canary title. This function is the single instrument every probe shares. +#> + +# Compile the P/Invoke enumerator once. Guard on the type already existing so +# repeated dot-sourcing inside the watch loop does not re-run Add-Type (which +# throws on a duplicate type). +if (-not ('OrcaWinEnum.Native' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Text; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace OrcaWinEnum { + public static class Native { + private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); + + [DllImport("user32.dll")] + private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); + [DllImport("user32.dll")] + private static extern bool IsWindowVisible(IntPtr hWnd); + [DllImport("user32.dll")] + private static extern int GetWindowTextLength(IntPtr hWnd); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); + [DllImport("dwmapi.dll")] + private static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out int pvAttribute, int cbAttribute); + + // DWMWA_CLOAKED: a window can be IsWindowVisible()==true yet cloaked by the + // shell (e.g. background UWP hosts). Cloaked windows are not really on + // screen, so we skip them to keep the baseline diff free of ghost churn. + private const int DWMWA_CLOAKED = 14; + + public static string[] Enumerate() { + var rows = new List(); + EnumWindows(delegate(IntPtr hWnd, IntPtr lParam) { + if (!IsWindowVisible(hWnd)) { return true; } + int len = GetWindowTextLength(hWnd); + if (len <= 0) { return true; } + int cloaked = 0; + try { DwmGetWindowAttribute(hWnd, DWMWA_CLOAKED, out cloaked, sizeof(int)); } catch { } + if (cloaked != 0) { return true; } + var sb = new StringBuilder(len + 1); + GetWindowText(hWnd, sb, sb.Capacity); + uint pid; + GetWindowThreadProcessId(hWnd, out pid); + // Tab-separated: handle, pid, title. Titles never contain a tab, and + // the handle/pid are numeric, so this parses unambiguously downstream. + rows.Add(((long)hWnd).ToString() + "\t" + pid.ToString() + "\t" + sb.ToString()); + return true; + }, IntPtr.Zero); + return rows.ToArray(); + } + } +} +'@ +} + +function Get-VisibleTopLevelWindows { + # @() forces an array even when Enumerate() returns a single row — the PS 5.1 + # single-item unwrap pitfall that caused a production incident when a count + # of "1" silently became a scalar. + $rows = @([OrcaWinEnum.Native]::Enumerate()) + + # Cache pid -> process name so we resolve each owning process at most once. + $nameByPid = @{} + $result = New-Object System.Collections.Generic.List[object] + + foreach ($row in $rows) { + $parts = $row -split "`t", 3 + if ($parts.Count -lt 3) { continue } + $handle = [long]$parts[0] + $procId = [int]$parts[1] + $title = $parts[2] + + if (-not $nameByPid.ContainsKey($procId)) { + $procName = $null + try { + $procName = (Get-Process -Id $procId -ErrorAction Stop).ProcessName + } catch { + $procName = $null + } + $nameByPid[$procId] = $procName + } + + $result.Add([pscustomobject]@{ + handle = $handle + pid = $procId + processName = $nameByPid[$procId] + title = $title + }) + } + + # Return the raw array; callers wrap with @() to normalize the PS 5.1 + # single-item unwrap. (Do not use the comma operator here — combined with a + # caller's @() it produces a nested array.) + return $result.ToArray() +} + +# When run directly (not dot-sourced) emit the snapshot as JSON so this file +# doubles as the baseline-snapshot tool. Wrapped in an object with a `windows` +# array; the JS side normalizes single-element results because PS 5.1 +# ConvertTo-Json unwraps a one-element array to a bare object. +if ($MyInvocation.InvocationName -ne '.') { + [pscustomobject]@{ windows = @(Get-VisibleTopLevelWindows) } | + ConvertTo-Json -Depth 4 -Compress +} diff --git a/tools/win-update-e2e/window-watch.mjs b/tools/win-update-e2e/window-watch.mjs new file mode 100644 index 000000000..1f35ef8b2 --- /dev/null +++ b/tools/win-update-e2e/window-watch.mjs @@ -0,0 +1,174 @@ +// Node wrapper around window-watch.ps1: start/stop the background window watch +// and parse its JSONL event log. Also runnable standalone as `--selftest`, +// which opens a real transient PowerShell window and asserts the watch caught +// it — so the harness's own instrument is testable without any installers. + +import { existsSync, mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { assertWin32 } from './platform-guard.mjs' +import { runScriptFileJson, spawnScriptFile, runCommandSync } from './powershell-runner.mjs' + +const HERE = import.meta.dirname +const WATCH_SCRIPT = path.join(HERE, 'window-watch.ps1') +const ENUM_SCRIPT = path.join(HERE, 'window-enum.ps1') + +/** + * Take a one-shot baseline snapshot of visible top-level windows and write it + * to baselinePath. Returns the window array. Normalizes the PS 5.1 single-item + * unwrap (windows may arrive as one object or as a nested array). + */ +export function captureBaseline(baselinePath) { + assertWin32('window-watch baseline') + const parsed = runScriptFileJson(ENUM_SCRIPT) + const windows = normalizeWindows(parsed.windows) + writeFileSync(baselinePath, JSON.stringify({ windows }, null, 2)) + return windows +} + +function normalizeWindows(raw) { + if (!raw) { + return [] + } + // PS 5.1 ConvertTo-Json can hand back a single object, a flat array, or (from + // a stray comma operator) a one-element array wrapping the real array. + if (Array.isArray(raw)) { + if (raw.length === 1 && Array.isArray(raw[0])) { + return raw[0] + } + return raw + } + return [raw] +} + +/** + * Start the background watch. Returns a handle with stop() -> events array. + * The watch seeds from baselinePath and records new windows to outPath until + * stop() (which drops a stop-file) or durationSec elapses. + */ +export function startWatch({ baselinePath, outPath, stopFile, durationSec = 600, pollMs = 500 }) { + assertWin32('window-watch') + const resolvedStopFile = stopFile ?? `${outPath}.stop` + if (existsSync(resolvedStopFile)) { + rmSync(resolvedStopFile) + } + + const child = spawnScriptFile(WATCH_SCRIPT, [ + '-BaselinePath', + baselinePath, + '-OutPath', + outPath, + '-StopFile', + resolvedStopFile, + '-DurationSec', + String(durationSec), + '-PollMs', + String(pollMs), + '-EnumScript', + ENUM_SCRIPT + ]) + + let stderr = '' + child.stderr.on('data', (d) => { + stderr += d.toString() + }) + + const exited = new Promise((resolve) => child.once('exit', resolve)) + + return { + process: child, + stopFile: resolvedStopFile, + outPath, + async stop() { + // Signal the loop to end, then wait for it to flush and exit. Fall back + // to a hard kill if the loop is wedged so a stuck watch never hangs teardown. + writeFileSync(resolvedStopFile, 'stop') + const timer = setTimeout(() => child.kill(), 5000) + await exited + clearTimeout(timer) + return { events: readEvents(outPath), stderr } + } + } +} + +/** Parse a window-watch JSONL log into an array of event objects. */ +export function readEvents(outPath) { + if (!existsSync(outPath)) { + return [] + } + return readFileSync(outPath, 'utf8') + .split('\n') + .map((l) => l.trim()) + .filter(Boolean) + .flatMap((line) => { + try { + return [JSON.parse(line)] + } catch { + return [] + } + }) +} + +async function selftest() { + assertWin32('window-watch --selftest') + const dir = mkdtempSync(path.join(tmpdir(), 'orca-winwatch-selftest-')) + const baselinePath = path.join(dir, 'baseline.json') + const outPath = path.join(dir, 'events.jsonl') + const canary = `ORCA-E2E-SELFTEST-${Date.now()}` + + console.log(`[selftest] baseline snapshot -> ${baselinePath}`) + const baseline = captureBaseline(baselinePath) + console.log(`[selftest] baseline captured ${baseline.length} visible windows`) + + const watch = startWatch({ baselinePath, outPath, durationSec: 20, pollMs: 300 }) + // Give the watch a moment to compile Add-Type and take its first poll before + // the transient window appears, so the appearance is genuinely "new". + await delay(1500) + + console.log(`[selftest] opening transient window titled ${canary}`) + // Must be a real console window: Start-Process allocates one, whereas a + // detached Node spawn gets DETACHED_PROCESS (no console at all) and would + // never appear in enumeration. This mirrors how a daemon child that lacks + // CREATE_NO_WINDOW allocates a fresh visible console — exactly the flash the + // real harness must catch. + const transientScript = path.join(dir, 'transient.ps1') + writeFileSync(transientScript, `$host.UI.RawUI.WindowTitle='${canary}'; Start-Sleep -Seconds 5`) + runCommandSync( + `Start-Process -FilePath 'powershell.exe' -ArgumentList '-NoProfile','-File','${transientScript}'` + ) + + // Poll cycles at 300ms; 3.5s covers several polls while the window is alive. + await delay(3500) + const { events, stderr } = await watch.stop() + rmSync(dir, { recursive: true, force: true }) + + const caught = events.filter((e) => typeof e.title === 'string' && e.title.includes(canary)) + console.log(`[selftest] watch recorded ${events.length} new windows total`) + if (stderr.trim()) { + console.log(`[selftest] watch stderr:\n${stderr.trim()}`) + } + if (caught.length === 0) { + console.error( + `[selftest] FAIL: watch did not capture a window titled "${canary}". ` + + `New windows seen: ${JSON.stringify(events.map((e) => e.title))}` + ) + process.exitCode = 1 + return + } + console.log(`[selftest] PASS: caught canary window: ${JSON.stringify(caught[0])}`) +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +if (process.argv[1] && path.resolve(process.argv[1]) === import.meta.filename) { + if (process.argv.includes('--selftest')) { + selftest().catch((err) => { + console.error(err) + process.exitCode = 1 + }) + } else { + console.log('Usage: node window-watch.mjs --selftest') + } +} diff --git a/tools/win-update-e2e/window-watch.ps1 b/tools/win-update-e2e/window-watch.ps1 new file mode 100644 index 000000000..7b1b73a5c --- /dev/null +++ b/tools/win-update-e2e/window-watch.ps1 @@ -0,0 +1,91 @@ +<# + window-watch.ps1 — poll visible top-level windows and record every NEW one. + + Runs a tight loop (default 500ms) that diffs the current visible top-level + windows against a baseline snapshot, appending any window handle it has not + seen before to a JSONL file as one event per line: + { "ts": "", "handle": , "pid": , "processName": "...", "title": "..." } + + It stops when -DurationSec elapses or -StopFile appears (whichever comes + first), so the orchestrator can end the watch deterministically after the + post-relaunch soak window. + + Attribution is by owner process + title only (see window-enum.ps1 for why + conhost heuristics are invalid). Classification of which new windows count as + "unexpected" (canary title, terminal/console owner) is done by the JS + assertions layer against this raw event log — this probe records everything. +#> +param( + [Parameter(Mandatory = $true)][string]$BaselinePath, + [Parameter(Mandatory = $true)][string]$OutPath, + [string]$StopFile = '', + [int]$DurationSec = 600, + [int]$PollMs = 500, + [string]$EnumScript = '' +) + +$ErrorActionPreference = 'Stop' + +if (-not $EnumScript) { + $EnumScript = Join-Path $PSScriptRoot 'window-enum.ps1' +} +. $EnumScript + +# Seed the baseline handle set so pre-existing windows never register. Their +# later title churn (clocks, tab names) is irrelevant noise, so baseline +# handles are excluded outright. Baseline JSON is { windows: [ { handle, ... } ] }; +# tolerate the PS 5.1 single-element unwrap by wrapping with @(). +$baselineHandles = New-Object System.Collections.Generic.HashSet[long] +if (Test-Path $BaselinePath) { + $baseline = Get-Content -Raw $BaselinePath | ConvertFrom-Json + foreach ($w in @($baseline.windows)) { + if ($null -ne $w -and $null -ne $w.handle) { + [void]$baselineHandles.Add([long]$w.handle) + } + } +} + +# Track the last-seen title of each NEW window. A window is emitted on first +# sighting ("appear") and again whenever its title changes ("retitle"): a real +# flashing console often opens with a generic title (e.g. WindowsTerminal's +# "Terminal") and only later shows our child's canary title, so title evolution +# must be captured or canary attribution is missed. +$titleByHandle = @{} + +# Truncate/create the output file up front so the reader can always open it. +[System.IO.File]::WriteAllText($OutPath, '') + +$deadline = (Get-Date).AddSeconds($DurationSec) + +while ((Get-Date) -lt $deadline) { + if ($StopFile -and (Test-Path $StopFile)) { break } + + $windows = @(Get-VisibleTopLevelWindows) + $now = (Get-Date).ToString('o') + foreach ($w in $windows) { + $handle = [long]$w.handle + if ($baselineHandles.Contains($handle)) { continue } + + $title = [string]$w.title + $prior = $null + $isNew = -not $titleByHandle.ContainsKey($handle) + if (-not $isNew) { $prior = $titleByHandle[$handle] } + if ($isNew -or $prior -ne $title) { + $titleByHandle[$handle] = $title + $event = [pscustomobject]@{ + ts = $now + kind = if ($isNew) { 'appear' } else { 'retitle' } + handle = $handle + pid = $w.pid + processName = $w.processName + title = $title + } + $line = ($event | ConvertTo-Json -Compress -Depth 3) + # AppendAllText with an explicit newline keeps each event on its own line + # even if the process is killed mid-write (no buffered partial records). + [System.IO.File]::AppendAllText($OutPath, $line + "`n") + } + } + + Start-Sleep -Milliseconds $PollMs +}