From b69c6043e33b0ee6c9bb5fa184328f99c7a2dc91 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 12 Jul 2026 23:50:00 -0700 Subject: [PATCH] Ssh watcher isolation e2e (#8494) * Add a Docker SSH watcher-isolation E2E test to verify remote relay-watch - Covers two scenarios: crashed watcher children are respawned under the same relay without dropping the terminal PTY or file-explorer view, and a missing deployed relay-watcher.js artifact is repaired on reconnect - Extracts shared connect/disconnect/reconnect logic out of the perf spec into docker-ssh-relay-connection.ts, and adds docker-ssh-relay-processes.ts for inspecting/signaling remote relay and watcher PIDs - Wires the new spec into a dedicated CI job and pnpm script * Fix Windows and Linux-only issues in Docker SSH watcher-isolation E2E ha - node-gyp override only applies on Linux runners now, since the CI job moved to ubuntu-latest but shares the workflow with non-Linux jobs - spawn the e2e runner scripts through a shell on win32 to satisfy Node's CVE-2024-27980 restriction on unshelled .cmd spawns - harden relay process row parsing against empty pid/ppid fields so a vanished /proc entry fails loudly instead of coercing to pid 0 - dedupe the reconnect helpers and export shellQuote for reuse across the docker-ssh-relay test helpers --- .github/workflows/e2e.yml | 56 +++++ .../run-ssh-docker-watcher-isolation-e2e.mjs | 41 +++ package.json | 1 + .../helpers/docker-ssh-relay-connection.ts | 129 ++++++++++ .../e2e/helpers/docker-ssh-relay-processes.ts | 191 ++++++++++++++ tests/e2e/helpers/docker-ssh-relay-target.ts | 20 +- tests/e2e/ssh-docker-relay-perf.spec.ts | 103 +------- .../e2e/ssh-docker-watcher-isolation.spec.ts | 238 ++++++++++++++++++ 8 files changed, 682 insertions(+), 97 deletions(-) create mode 100644 config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs create mode 100644 tests/e2e/helpers/docker-ssh-relay-connection.ts create mode 100644 tests/e2e/helpers/docker-ssh-relay-processes.ts create mode 100644 tests/e2e/ssh-docker-watcher-isolation.spec.ts diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index ce603bc76..0e18d3ca5 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -173,3 +173,59 @@ jobs: path: test-results/ retention-days: 7 if-no-files-found: ignore + + ssh-docker-watcher-isolation: + name: ssh docker watcher isolation + needs: build + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ inputs.ref || github.ref }} + + - name: Install native build and headless UI tools + run: sudo apt-get update && sudo apt-get install -y build-essential openssh-client python3 xvfb + + - 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: same Linux-only node-gyp pin as build/e2e jobs so the workaround + # stays consistent across workflows even while this job is ubuntu-latest. + - name: Use external node-gyp to avoid pnpm's bundled copy (Linux only) + if: runner.os == 'Linux' + run: | + npm install -g node-gyp@11.5.0 + echo "npm_config_node_gyp=$(npm root -g)/node-gyp/bin/node-gyp.js" >> "$GITHUB_ENV" + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Download E2E build output + uses: actions/download-artifact@v8 + with: + name: e2e-build-out + path: out/ + + # Why: this is the release-path proof that the deployed Linux relay keeps + # its PTY and explorer live across a real watcher SIGSEGV. + - name: Run Docker SSH watcher isolation E2E + run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:ssh-docker-watcher-isolation + + - name: Upload watcher isolation traces + if: failure() + uses: actions/upload-artifact@v7 + with: + name: playwright-traces-ssh-docker-watcher-isolation + path: test-results/ + retention-days: 7 + if-no-files-found: ignore diff --git a/config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs b/config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs new file mode 100644 index 000000000..5fc10e9e4 --- /dev/null +++ b/config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs @@ -0,0 +1,41 @@ +import { spawnSync } from 'node:child_process' + +const rawExtraArgs = process.argv.slice(2) +const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArgs +const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm' +const env = { + ...process.env, + ORCA_E2E_SSH_DOCKER: '1' +} + +// Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows. +const spawnOptions = { + stdio: 'inherit', + env, + shell: process.platform === 'win32' +} + +const runtime = spawnSync(pnpm, ['run', 'ensure:electron-runtime'], spawnOptions) + +if (runtime.status !== 0) { + process.exit(runtime.status ?? 1) +} + +const result = spawnSync( + pnpm, + [ + 'exec', + 'playwright', + 'test', + 'tests/e2e/ssh-docker-watcher-isolation.spec.ts', + '--config', + 'tests/playwright.config.ts', + '--project', + 'electron-headless', + '--workers=1', + ...extraArgs + ], + spawnOptions +) + +process.exit(result.status ?? 1) diff --git a/package.json b/package.json index 64c06de41..78f44dc5f 100644 --- a/package.json +++ b/package.json @@ -83,6 +83,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", + "test:e2e:ssh-docker-watcher-isolation": "node config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs", "test:e2e:source-control-scale": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/source-control-large-file-count.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "win-update-e2e": "node tools/win-update-e2e/run.mjs", "test:e2e:ssh-codex-artifacts-repro": "node config/scripts/run-ssh-codex-artifacts-repro-e2e.mjs", diff --git a/tests/e2e/helpers/docker-ssh-relay-connection.ts b/tests/e2e/helpers/docker-ssh-relay-connection.ts new file mode 100644 index 000000000..d924d6347 --- /dev/null +++ b/tests/e2e/helpers/docker-ssh-relay-connection.ts @@ -0,0 +1,129 @@ +import type { Page } from '@stablyai/playwright-test' + +import { + DOCKER_SSH_RELAY_REMOTE_REPO_PATH, + type DockerSshRelayTarget +} from './docker-ssh-relay-target' + +export type ConnectedDockerSshRelayTarget = { + targetId: string + repoId: string + worktreeId: string +} + +type DockerSshRelayConnectionOptions = { + relayGracePeriodSeconds?: number +} + +export async function connectDockerSshRelayTarget( + page: Page, + target: DockerSshRelayTarget, + options: DockerSshRelayConnectionOptions = {} +): Promise { + return page.evaluate( + async ({ target, remotePath, relayGracePeriodSeconds }) => { + const store = window.__store + if (!store) { + throw new Error('Store unavailable') + } + const credentialUnsub = window.api.ssh.onCredentialRequest((request) => { + void window.api.ssh.submitCredential({ requestId: request.requestId, value: null }) + }) + try { + const { target: createdTarget, repoReadoptions } = await window.api.ssh.addTarget({ + target: { + label: `Docker SSH Relay E2E ${Date.now()}`, + host: '127.0.0.1', + port: target.port, + username: 'root', + identityFile: target.identityFile, + identitiesOnly: true, + relayGracePeriodSeconds + } + }) + store.getState().recordSshRepoReadoptions(repoReadoptions) + const state = await window.api.ssh.connect({ targetId: createdTarget.id }) + if (!state || state.status !== 'connected') { + throw new Error(`SSH target did not connect: ${JSON.stringify(state)}`) + } + store.getState().setSshConnectionState(createdTarget.id, state) + const labels = new Map(store.getState().sshTargetLabels) + labels.set(createdTarget.id, createdTarget.label) + store.getState().setSshTargetLabels(labels) + + const result = await window.api.repos.addRemote({ + connectionId: createdTarget.id, + remotePath, + displayName: 'Docker SSH Relay E2E' + }) + if ('error' in result) { + throw new Error(result.error) + } + await store.getState().fetchRepos() + await store.getState().fetchWorktrees(result.repo.id) + const worktree = (store.getState().worktreesByRepo[result.repo.id] ?? [])[0] + if (!worktree) { + throw new Error(`No remote worktree found for ${result.repo.path}`) + } + store.getState().setActiveWorktree(worktree.id) + if ((store.getState().tabsByWorktree[worktree.id] ?? []).length === 0) { + store.getState().createTab(worktree.id) + } + store.getState().setActiveTabType('terminal') + return { + targetId: createdTarget.id, + repoId: result.repo.id, + worktreeId: worktree.id + } + } finally { + credentialUnsub() + } + }, + { + target, + remotePath: DOCKER_SSH_RELAY_REMOTE_REPO_PATH, + relayGracePeriodSeconds: options.relayGracePeriodSeconds ?? 1 + } + ) +} + +export async function disconnectDockerSshRelayTarget(page: Page, targetId: string): Promise { + await page.evaluate(async (targetId) => { + await window.api.ssh.disconnect({ targetId }) + }, targetId) +} + +async function performDockerSshRelayReconnect( + page: Page, + targetId: string, + disconnectFirst: boolean +): Promise { + await page.evaluate( + async ({ targetId, disconnectFirst }) => { + const store = window.__store + if (!store) { + throw new Error('Store unavailable') + } + if (disconnectFirst) { + await window.api.ssh.disconnect({ targetId }) + } + const state = await window.api.ssh.connect({ targetId }) + if (!state || state.status !== 'connected') { + throw new Error(`SSH target did not reconnect: ${JSON.stringify(state)}`) + } + store.getState().setSshConnectionState(targetId, state) + }, + { targetId, disconnectFirst } + ) +} + +export async function reconnectDockerSshRelayTarget(page: Page, targetId: string): Promise { + return performDockerSshRelayReconnect(page, targetId, true) +} + +export async function reconnectDisconnectedDockerSshRelayTarget( + page: Page, + targetId: string +): Promise { + return performDockerSshRelayReconnect(page, targetId, false) +} diff --git a/tests/e2e/helpers/docker-ssh-relay-processes.ts b/tests/e2e/helpers/docker-ssh-relay-processes.ts new file mode 100644 index 000000000..bd809bd86 --- /dev/null +++ b/tests/e2e/helpers/docker-ssh-relay-processes.ts @@ -0,0 +1,191 @@ +import { + execDockerSshRelayTargetCommand, + shellQuote, + type DockerSshRelayTarget +} from './docker-ssh-relay-target' + +export type DockerSshRelayProcessSnapshot = { + relayPid: number + watcherPids: number[] + relayDir: string +} + +export type DockerSshRelayArtifactState = { + installComplete: boolean + relayWatcher: boolean +} + +type RelayProcessRow = { + type: 'relay' | 'watcher' + pid: number + parentPid: number + cwd: string +} + +const LIST_RELAY_PROCESSES_COMMAND = ` +for proc in /proc/[0-9]*; do + [ -r "$proc/cmdline" ] || continue + argv=() + mapfile -d '' -t argv < "$proc/cmdline" 2>/dev/null || continue + entry="\${argv[1]:-}" + base="\${entry##*/}" + type= + if [ "$base" = relay-watcher.js ]; then + type=watcher + elif [ "$base" = relay.js ]; then + for arg in "\${argv[@]:2}"; do + if [ "$arg" = --detached ]; then type=relay; break; fi + done + fi + [ -n "$type" ] || continue + pid="\${proc##*/}" + ppid="$(awk '/^PPid:/{print $2}' "$proc/status" 2>/dev/null)" + cwd="$(readlink "$proc/cwd" 2>/dev/null)" + printf '%s\\t%s\\t%s\\t%s\\n' "$type" "$pid" "$ppid" "$cwd" +done +` + +function parseRelayProcessRows(output: string): RelayProcessRow[] { + if (!output) { + return [] + } + return output.split('\n').map((line) => { + const [type, rawPid, rawParentPid, cwd] = line.split('\t') + // Why: Number('') is 0, so empty pid/ppid (e.g. vanished /proc status) must + // throw and let expect.poll retry instead of accepting parentPid: 0. + const pid = Number(rawPid) + const parentPid = Number(rawParentPid) + if ( + (type !== 'relay' && type !== 'watcher') || + rawPid === undefined || + rawPid === '' || + rawParentPid === undefined || + rawParentPid === '' || + !Number.isInteger(pid) || + !Number.isInteger(parentPid) || + !cwd + ) { + throw new Error(`Unexpected Docker SSH relay process row: ${line}`) + } + return { type, pid, parentPid, cwd } + }) +} + +export function readDockerSshRelayProcessSnapshot( + target: DockerSshRelayTarget +): DockerSshRelayProcessSnapshot | null { + const rows = parseRelayProcessRows( + execDockerSshRelayTargetCommand(target, LIST_RELAY_PROCESSES_COMMAND) + ) + const relays = rows.filter((row) => row.type === 'relay') + const groups = relays.flatMap((relay) => { + const watcherPids = rows + .filter((row) => row.type === 'watcher' && row.parentPid === relay.pid) + .map((row) => row.pid) + .sort((left, right) => left - right) + return watcherPids.length > 0 ? [{ relayPid: relay.pid, watcherPids, relayDir: relay.cwd }] : [] + }) + if (groups.length > 1) { + throw new Error(`Expected one Docker SSH relay process group, found ${groups.length}`) + } + return groups[0] ?? null +} + +export function signalDockerSshRelayWatchers( + target: DockerSshRelayTarget, + snapshot: DockerSshRelayProcessSnapshot +): void { + const { relayPid, watcherPids } = snapshot + if (!Number.isInteger(relayPid) || watcherPids.some((pid) => !Number.isInteger(pid))) { + throw new Error('Docker SSH relay process IDs must be integers') + } + execDockerSshRelayTargetCommand( + target, + [ + `relay_proc=/proc/${relayPid}`, + '[ -r "$relay_proc/cmdline" ]', + 'relay_argv=()', + 'mapfile -d \'\' -t relay_argv < "$relay_proc/cmdline"', + '[ "${relay_argv[1]##*/}" = relay.js ]', + '[[ " ${relay_argv[*]:2} " = *" --detached "* ]]', + ...watcherPids.flatMap((watcherPid) => [ + `proc=/proc/${watcherPid}`, + '[ -r "$proc/cmdline" ]', + 'argv=()', + 'mapfile -d \'\' -t argv < "$proc/cmdline"', + '[ "${argv[1]##*/}" = relay-watcher.js ]', + `ppid="$(awk '/^PPid:/{print $2}' "$proc/status")"`, + `[ "$ppid" = ${relayPid} ]`, + `kill -SEGV ${watcherPid}` + ]) + ].join(' && ') + ) +} + +export function terminateDockerSshRelay( + target: DockerSshRelayTarget, + snapshot: DockerSshRelayProcessSnapshot +): void { + const { relayPid } = snapshot + if (!Number.isInteger(relayPid)) { + throw new Error('Docker SSH relay process ID must be an integer') + } + execDockerSshRelayTargetCommand( + target, + [ + `proc=/proc/${relayPid}`, + '[ -r "$proc/cmdline" ]', + 'argv=()', + 'mapfile -d \'\' -t argv < "$proc/cmdline"', + '[ "${argv[1]##*/}" = relay.js ]', + '[[ " ${argv[*]:2} " = *" --detached "* ]]', + `kill -TERM ${relayPid}` + ].join(' && ') + ) +} + +export function isDockerSshRelayPidRunning( + target: DockerSshRelayTarget, + relayPid: number +): boolean { + if (!Number.isInteger(relayPid)) { + return false + } + const result = execDockerSshRelayTargetCommand( + target, + `proc=/proc/${relayPid}; ` + + 'if [ -r "$proc/cmdline" ]; then ' + + 'argv=(); mapfile -d \'\' -t argv < "$proc/cmdline"; ' + + 'if [ "${argv[1]##*/}" = relay.js ] && ' + + '[[ " ${argv[*]:2} " = *" --detached "* ]]; then echo ALIVE; else echo DEAD; fi; ' + + 'else echo DEAD; fi' + ) + return result === 'ALIVE' +} + +export function readDockerSshRelayArtifactState( + target: DockerSshRelayTarget, + relayDir: string +): DockerSshRelayArtifactState { + const quotedDir = shellQuote(relayDir) + const output = execDockerSshRelayTargetCommand( + target, + `test -f ${quotedDir}/.install-complete && marker=yes || marker=no; ` + + `test -f ${quotedDir}/relay-watcher.js && watcher=yes || watcher=no; ` + + 'printf "%s %s" "$marker" "$watcher"' + ) + const [marker, watcher] = output.split(' ') + return { installComplete: marker === 'yes', relayWatcher: watcher === 'yes' } +} + +export function removeDockerSshRelayWatcherArtifact( + target: DockerSshRelayTarget, + relayDir: string +): void { + const quotedDir = shellQuote(relayDir) + execDockerSshRelayTargetCommand( + target, + `test -f ${quotedDir}/.install-complete && rm -f ${quotedDir}/relay-watcher.js && ` + + `test -f ${quotedDir}/.install-complete && test ! -e ${quotedDir}/relay-watcher.js` + ) +} diff --git a/tests/e2e/helpers/docker-ssh-relay-target.ts b/tests/e2e/helpers/docker-ssh-relay-target.ts index 403588d18..7d368620d 100644 --- a/tests/e2e/helpers/docker-ssh-relay-target.ts +++ b/tests/e2e/helpers/docker-ssh-relay-target.ts @@ -28,11 +28,14 @@ function tryRun(command: string, args: string[], opts: { timeoutMs?: number } = spawnSync(command, args, { stdio: 'ignore', timeout: opts.timeoutMs ?? 10_000 }) } -function shellQuote(value: string): string { +export function shellQuote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'` } -function dockerExec(target: DockerSshRelayTarget, command: string): string { +export function execDockerSshRelayTargetCommand( + target: DockerSshRelayTarget, + command: string +): string { return run('docker', ['exec', target.containerName, 'bash', '-lc', command], { timeoutMs: 60_000 }) @@ -74,7 +77,7 @@ function waitForSsh(target: DockerSshRelayTarget): void { } function seedRemoteRepo(target: DockerSshRelayTarget): void { - dockerExec( + execDockerSshRelayTargetCommand( target, [ `rm -rf ${shellQuote(DOCKER_SSH_RELAY_REMOTE_REPO_PATH)}`, @@ -90,6 +93,17 @@ function seedRemoteRepo(target: DockerSshRelayTarget): void { ) } +export function writeDockerSshRelayTargetFile( + target: DockerSshRelayTarget, + filePath: string, + contents: string +): void { + execDockerSshRelayTargetCommand( + target, + `printf '%s' ${shellQuote(contents)} > ${shellQuote(filePath)}` + ) +} + export function startDockerSshRelayTarget(testInfo: TestInfo): DockerSshRelayTarget { const tempDir = mkdtempSync(path.join(os.tmpdir(), 'orca-ssh-docker-')) const identityFile = path.join(tempDir, 'id_ed25519') diff --git a/tests/e2e/ssh-docker-relay-perf.spec.ts b/tests/e2e/ssh-docker-relay-perf.spec.ts index 13f90d439..231dd43cd 100644 --- a/tests/e2e/ssh-docker-relay-perf.spec.ts +++ b/tests/e2e/ssh-docker-relay-perf.spec.ts @@ -1,4 +1,3 @@ -import type { Page } from '@stablyai/playwright-test' import { test, expect } from './helpers/orca-app' import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' import { @@ -15,6 +14,10 @@ import { startDockerSshRelayTarget, type DockerSshRelayTarget } from './helpers/docker-ssh-relay-target' +import { + connectDockerSshRelayTarget, + reconnectDockerSshRelayTarget +} from './helpers/docker-ssh-relay-connection' const RUN_DOCKER_SSH = process.env.ORCA_E2E_SSH_DOCKER === '1' const KEY_LATENCY_SAMPLES = 'abcdefghij' @@ -42,12 +45,6 @@ type SshPtyAckGateWindow = Window & { } } -type ConnectedDockerRemote = { - targetId: string - repoId: string - worktreeId: string -} - function shellQuote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'` } @@ -89,73 +86,6 @@ function remoteBackgroundFloodScript(runId: string): string { ].join(';') } -async function connectDockerRemote( - page: Page, - target: DockerSshRelayTarget -): Promise { - return await page.evaluate( - async ({ target, remotePath }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const credentialUnsub = window.api.ssh.onCredentialRequest((request) => { - void window.api.ssh.submitCredential({ requestId: request.requestId, value: null }) - }) - try { - const { target: createdTarget, repoReadoptions } = await window.api.ssh.addTarget({ - target: { - label: `Docker SSH Relay Perf ${Date.now()}`, - host: '127.0.0.1', - port: target.port, - username: 'root', - identityFile: target.identityFile, - identitiesOnly: true, - relayGracePeriodSeconds: 1 - } - }) - store.getState().recordSshRepoReadoptions(repoReadoptions) - const state = await window.api.ssh.connect({ targetId: createdTarget.id }) - if (!state || state.status !== 'connected') { - throw new Error(`SSH target did not connect: ${JSON.stringify(state)}`) - } - store.getState().setSshConnectionState(createdTarget.id, state) - const labels = new Map(store.getState().sshTargetLabels) - labels.set(createdTarget.id, createdTarget.label) - store.getState().setSshTargetLabels(labels) - - const result = await window.api.repos.addRemote({ - connectionId: createdTarget.id, - remotePath, - displayName: 'Docker SSH Relay Perf' - }) - if ('error' in result) { - throw new Error(result.error) - } - await store.getState().fetchRepos() - await store.getState().fetchWorktrees(result.repo.id) - const worktree = (store.getState().worktreesByRepo[result.repo.id] ?? [])[0] - if (!worktree) { - throw new Error(`No remote worktree found for ${result.repo.path}`) - } - store.getState().setActiveWorktree(worktree.id) - if ((store.getState().tabsByWorktree[worktree.id] ?? []).length === 0) { - store.getState().createTab(worktree.id) - } - store.getState().setActiveTabType('terminal') - return { - targetId: createdTarget.id, - repoId: result.repo.id, - worktreeId: worktree.id - } - } finally { - credentialUnsub() - } - }, - { target, remotePath: DOCKER_SSH_RELAY_REMOTE_REPO_PATH } - ) -} - function median(values: number[]): number { const sorted = [...values].sort((a, b) => a - b) return sorted[Math.floor(sorted.length / 2)] ?? 0 @@ -208,21 +138,6 @@ async function stopRemoteLoad(page: Page, ptyId: string): Promise { await page.evaluate((targetPtyId) => window.api.pty.write(targetPtyId, '\x03'), ptyId) } -async function reconnectDockerTarget(page: Page, targetId: string): Promise { - await page.evaluate(async (targetId) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - await window.api.ssh.disconnect({ targetId }) - const state = await window.api.ssh.connect({ targetId }) - if (!state || state.status !== 'connected') { - throw new Error(`SSH target did not reconnect: ${JSON.stringify(state)}`) - } - store.getState().setSshConnectionState(targetId, state) - }, targetId) -} - test.describe('Docker SSH relay perf', () => { test.skip(!RUN_DOCKER_SSH, 'Set ORCA_E2E_SSH_DOCKER=1 to run Docker-backed SSH relay perf.') test.skip(process.platform === 'win32', 'Docker SSH relay perf uses POSIX ssh tooling.') @@ -236,7 +151,7 @@ test.describe('Docker SSH relay perf', () => { target = startDockerSshRelayTarget(testInfo) await waitForSessionReady(orcaPage) await waitForActiveWorktree(orcaPage) - await connectDockerRemote(orcaPage, target) + await connectDockerSshRelayTarget(orcaPage, target) await ensureTerminalVisible(orcaPage, 45_000) await waitForActiveTerminalManager(orcaPage, 60_000) const ptyId = await waitForActivePanePtyId(orcaPage, 60_000) @@ -274,7 +189,7 @@ test.describe('Docker SSH relay perf', () => { target = startDockerSshRelayTarget(testInfo) await waitForSessionReady(orcaPage) await waitForActiveWorktree(orcaPage) - await connectDockerRemote(orcaPage, target) + await connectDockerSshRelayTarget(orcaPage, target) await ensureTerminalVisible(orcaPage, 45_000) await waitForActiveTerminalManager(orcaPage, 60_000) backgroundPtyId = await waitForActivePanePtyId(orcaPage, 60_000) @@ -350,7 +265,7 @@ test.describe('Docker SSH relay perf', () => { target = startDockerSshRelayTarget(testInfo) await waitForSessionReady(orcaPage) await waitForActiveWorktree(orcaPage) - const remote = await connectDockerRemote(orcaPage, target) + const remote = await connectDockerSshRelayTarget(orcaPage, target) await ensureTerminalVisible(orcaPage, 45_000) await waitForActiveTerminalManager(orcaPage, 60_000) const ptyId = await waitForActivePanePtyId(orcaPage, 60_000) @@ -448,7 +363,7 @@ test.describe('Docker SSH relay perf', () => { target = startDockerSshRelayTarget(testInfo) await waitForSessionReady(orcaPage) await waitForActiveWorktree(orcaPage) - const remote = await connectDockerRemote(orcaPage, target) + const remote = await connectDockerSshRelayTarget(orcaPage, target) await ensureTerminalVisible(orcaPage, 45_000) await waitForActiveTerminalManager(orcaPage, 60_000) const beforePtyId = await waitForActivePanePtyId(orcaPage, 60_000) @@ -456,7 +371,7 @@ test.describe('Docker SSH relay perf', () => { await execInTerminal(orcaPage, beforePtyId, `printf ${shellQuote(beforeMarker)}`) await waitForTerminalOutput(orcaPage, beforeMarker, 20_000, 60_000) - await reconnectDockerTarget(orcaPage, remote.targetId) + await reconnectDockerSshRelayTarget(orcaPage, remote.targetId) await ensureTerminalVisible(orcaPage, 45_000) await waitForActiveTerminalManager(orcaPage, 60_000) const afterPtyId = await waitForActivePanePtyId(orcaPage, 60_000) diff --git a/tests/e2e/ssh-docker-watcher-isolation.spec.ts b/tests/e2e/ssh-docker-watcher-isolation.spec.ts new file mode 100644 index 000000000..c9804f682 --- /dev/null +++ b/tests/e2e/ssh-docker-watcher-isolation.spec.ts @@ -0,0 +1,238 @@ +import type { Locator, Page } from '@stablyai/playwright-test' + +import { + connectDockerSshRelayTarget, + disconnectDockerSshRelayTarget, + reconnectDisconnectedDockerSshRelayTarget +} from './helpers/docker-ssh-relay-connection' +import { + isDockerSshRelayPidRunning, + readDockerSshRelayArtifactState, + readDockerSshRelayProcessSnapshot, + removeDockerSshRelayWatcherArtifact, + signalDockerSshRelayWatchers, + terminateDockerSshRelay, + type DockerSshRelayProcessSnapshot +} from './helpers/docker-ssh-relay-processes' +import { + cleanupDockerSshRelayTarget, + DOCKER_SSH_RELAY_REMOTE_REPO_PATH, + startDockerSshRelayTarget, + writeDockerSshRelayTargetFile, + type DockerSshRelayTarget +} from './helpers/docker-ssh-relay-target' +import { openFileExplorer } from './helpers/file-explorer' +import { test, expect } from './helpers/orca-app' +import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { + execInTerminal, + waitForActivePanePtyId, + waitForActiveTerminalManager +} from './helpers/terminal' + +const RUN_DOCKER_SSH = process.env.ORCA_E2E_SSH_DOCKER === '1' + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'` +} + +function remoteRepoFile(fileName: string): string { + return `${DOCKER_SSH_RELAY_REMOTE_REPO_PATH}/${fileName}` +} + +function fileExplorerRow(page: Page, fileName: string): Locator { + return page.locator('[data-file-explorer-row]').filter({ hasText: fileName }) +} + +async function waitForRelayWatcherProcessGroup( + target: DockerSshRelayTarget +): Promise { + let snapshot: DockerSshRelayProcessSnapshot | null = null + await expect + .poll( + () => { + snapshot = readDockerSshRelayProcessSnapshot(target) + return snapshot !== null + }, + { timeout: 30_000, message: 'remote relay/watcher process group did not appear' } + ) + .toBe(true) + if (!snapshot) { + throw new Error('remote relay/watcher process group disappeared after polling') + } + return snapshot +} + +async function openRemoteFileExplorer(page: Page, target: DockerSshRelayTarget): Promise { + await openFileExplorer(page) + await expect(page.locator('[data-orca-explorer-shell]')).toBeVisible({ timeout: 15_000 }) + await expect(fileExplorerRow(page, 'README.md')).toBeVisible({ timeout: 30_000 }) + // Why: the child appears only after the real explorer watch subscribes, so + // external file creation below cannot race the initial watch registration. + await waitForRelayWatcherProcessGroup(target) +} + +async function closeRemoteFileExplorer(page: Page): Promise { + await page.evaluate(() => window.__store?.getState().setRightSidebarOpen(false)) + await expect + .poll(() => page.evaluate(() => window.__store?.getState().rightSidebarOpen ?? true), { + timeout: 5_000 + }) + .toBe(false) +} + +async function enableTerminalAccessibilityDom(page: Page, ptyId: string): Promise { + await page.evaluate((ptyId) => { + const managers = Array.from(window.__paneManagers?.values() ?? []) + const pane = managers + .flatMap((manager) => manager.getPanes?.() ?? []) + .find((candidate) => candidate.container.dataset.ptyId === ptyId) + if (!pane) { + throw new Error(`Terminal pane ${ptyId} is unavailable`) + } + // Why: xterm normally paints to canvas. Screen-reader mode mirrors the + // user-visible buffer into DOM rows so the survival assertion stays DOM-based. + pane.terminal.options.screenReaderMode = true + pane.terminal.refresh(0, pane.terminal.rows - 1) + }, ptyId) + await expect( + page.locator(`[data-pty-id=${JSON.stringify(ptyId)}] .xterm-accessibility-tree`) + ).toBeAttached({ timeout: 10_000 }) +} + +test.describe('Docker SSH relay watcher isolation', () => { + test.skip(!RUN_DOCKER_SSH, 'Set ORCA_E2E_SSH_DOCKER=1 to run Docker-backed SSH tests.') + test.skip(process.platform === 'win32', 'Docker SSH watcher isolation uses POSIX tooling.') + + test('keeps the relay, terminal, and explorer alive when only relay-watcher.js crashes', async ({ + orcaPage + }, testInfo) => { + test.slow() + let target: DockerSshRelayTarget | null = null + try { + target = startDockerSshRelayTarget(testInfo) + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + const remote = await connectDockerSshRelayTarget(orcaPage, target) + await ensureTerminalVisible(orcaPage, 45_000) + await waitForActiveTerminalManager(orcaPage, 60_000) + const ptyId = await waitForActivePanePtyId(orcaPage, 60_000) + await enableTerminalAccessibilityDom(orcaPage, ptyId) + await openRemoteFileExplorer(orcaPage, target) + + const beforeFile = 'before-crash.txt' + writeDockerSshRelayTargetFile(target, remoteRepoFile(beforeFile), 'before watcher crash\n') + await expect(fileExplorerRow(orcaPage, beforeFile)).toBeVisible({ timeout: 30_000 }) + + const beforeCrash = await waitForRelayWatcherProcessGroup(target) + // Why: the relay shards roots across bounded watcher children. Crashing + // every verified child guarantees the explorer's shard crosses the boundary. + signalDockerSshRelayWatchers(target, beforeCrash) + + let afterCrash: DockerSshRelayProcessSnapshot | null = null + await expect + .poll( + () => { + afterCrash = readDockerSshRelayProcessSnapshot(target!) + return Boolean( + afterCrash && + afterCrash.relayPid === beforeCrash.relayPid && + afterCrash.watcherPids.every( + (watcherPid) => !beforeCrash.watcherPids.includes(watcherPid) + ) + ) + }, + { + timeout: 30_000, + message: 'watcher children were not replaced under the same relay PID' + } + ) + .toBe(true) + + const terminalMarker = `SSH_WATCHER_CRASH_SURVIVED_${Date.now()}` + // Why: the shell echoes input before executing it. Encoding keeps the + // plaintext marker exclusive to command output, proving a live remote PTY. + const terminalMarkerBase64 = Buffer.from(terminalMarker).toString('base64') + const afterFile = 'after-crash.txt' + await execInTerminal( + orcaPage, + ptyId, + `printf '%s' ${shellQuote(terminalMarkerBase64)} | base64 -d && printf '\\n' && ` + + `printf '%s\\n' 'after watcher crash' > ${shellQuote(remoteRepoFile(afterFile))}` + ) + const terminalDom = orcaPage.locator( + `[data-pty-id=${JSON.stringify(ptyId)}] .xterm-accessibility-tree` + ) + await expect(terminalDom).toContainText(terminalMarker, { timeout: 30_000 }) + + const finalProcesses = await waitForRelayWatcherProcessGroup(target) + expect(finalProcesses.relayPid).toBe(beforeCrash.relayPid) + expect( + finalProcesses.watcherPids.some((watcherPid) => + beforeCrash.watcherPids.includes(watcherPid) + ) + ).toBe(false) + testInfo.annotations.push({ + type: 'docker-ssh-watcher-isolation', + description: + `target=${remote.targetId} relayPid=${beforeCrash.relayPid} ` + + `watcherPids=${beforeCrash.watcherPids.join(',')}->${finalProcesses.watcherPids.join(',')} ` + + `pty=${ptyId}` + }) + await expect(fileExplorerRow(orcaPage, afterFile)).toBeVisible({ timeout: 30_000 }) + } finally { + cleanupDockerSshRelayTarget(target) + } + }) + + test('repairs a missing deployed relay-watcher.js on reconnect', async ({ + orcaPage + }, testInfo) => { + test.slow() + let target: DockerSshRelayTarget | null = null + try { + target = startDockerSshRelayTarget(testInfo) + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + const remote = await connectDockerSshRelayTarget(orcaPage, target) + await openRemoteFileExplorer(orcaPage, target) + + const beforeRepair = await waitForRelayWatcherProcessGroup(target) + expect(readDockerSshRelayArtifactState(target, beforeRepair.relayDir)).toEqual({ + installComplete: true, + relayWatcher: true + }) + removeDockerSshRelayWatcherArtifact(target, beforeRepair.relayDir) + expect(readDockerSshRelayArtifactState(target, beforeRepair.relayDir)).toEqual({ + installComplete: true, + relayWatcher: false + }) + + await closeRemoteFileExplorer(orcaPage) + await disconnectDockerSshRelayTarget(orcaPage, remote.targetId) + // Why: normal relays deliberately retain PTYs for the reconnect grace + // window. Stop this disconnected instance so reconnect must deploy anew. + terminateDockerSshRelay(target, beforeRepair) + await expect + .poll(() => isDockerSshRelayPidRunning(target!, beforeRepair.relayPid), { + timeout: 30_000, + message: 'disconnected relay did not exit after explicit termination' + }) + .toBe(false) + await reconnectDisconnectedDockerSshRelayTarget(orcaPage, remote.targetId) + + await openRemoteFileExplorer(orcaPage, target) + const afterRepair = await waitForRelayWatcherProcessGroup(target) + expect(afterRepair.relayPid).not.toBe(beforeRepair.relayPid) + expect(readDockerSshRelayArtifactState(target, afterRepair.relayDir)).toEqual({ + installComplete: true, + relayWatcher: true + }) + const repairedFile = 'after-artifact-repair.txt' + writeDockerSshRelayTargetFile(target, remoteRepoFile(repairedFile), 'artifact repaired\n') + await expect(fileExplorerRow(orcaPage, repairedFile)).toBeVisible({ timeout: 30_000 }) + } finally { + cleanupDockerSshRelayTarget(target) + } + }) +})