From c27724cbea985691bcebc64f046627ab35a28efe Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Tue, 7 Jul 2026 16:58:19 -0400 Subject: [PATCH] Address review feedback: arch-aware trim + daemon/harness hardening Shipped daemon code: - daemon-host-relocation: key the node-pty prebuild filter on the host arch (keep prebuilds/win32-, drop the other) instead of always dropping win32-arm64, so a future Windows-arm64 build keeps the prebuild it needs. Test now asserts host-arch kept / other-arch dropped on any runner. - daemon-entry: make shutdown idempotent, bounded (5s race), and fault-tolerant so concurrent SIGTERM/SIGINT can't double-shutdown or leave an unhandled rejection that skips process.exit. - daemon-file-log: guard rotate() when maxRotatedFiles < 1 so it no longer falsely resets the byte counter and defeats the overflow check. - daemon-init test: assert the actual --log-file path value, not just the flag. CI proof harness / spike (test-only): - persist-credentials: false on the three new workflows' checkout. - powershell-runner: default timeout on sync PowerShell calls. - preflight: fail closed when app-process discovery errors. - cli-args: fail closed on a valueless or unreadable --install-dir. - installer-steps: wait for the target-version exe, not any exe, on updates. - daemon-processes: read each pid file once (no crash-on-re-read). - app-driver: scope the xterm helper textarea to the visible surface. - run: track the base install immediately so an early failure still tears down. - registry-shortcut-backup: fold reg import/delete failures into verified. - spike: keep the child handle on a pre-ready rejection; use win32 path semantics + check PowerShell exit status in the loaded-module probe. --- .github/workflows/daemon-relocation-spike.yml | 3 ++ .github/workflows/win-update-e2e.yml | 3 ++ .github/workflows/win-update-survival-e2e.yml | 3 ++ src/main/daemon/daemon-entry.ts | 32 ++++++++++--- src/main/daemon/daemon-file-log.ts | 6 +++ .../daemon/daemon-host-relocation.test.ts | 31 ++++++++----- src/main/daemon/daemon-host-relocation.ts | 18 +++++--- src/main/daemon/daemon-init.test.ts | 45 ++++++++++++++++--- .../daemon-relocation-spike/daemon-launch.mjs | 3 ++ .../loaded-module-probe.mjs | 16 +++++-- tools/daemon-relocation-spike/spike.mjs | 3 ++ tools/win-update-e2e/app-driver.mjs | 4 +- tools/win-update-e2e/cli-args.mjs | 20 ++++++--- tools/win-update-e2e/daemon-processes.mjs | 7 ++- tools/win-update-e2e/installer-steps.mjs | 10 +++-- tools/win-update-e2e/powershell-runner.mjs | 5 +++ tools/win-update-e2e/preflight.mjs | 17 +++++-- .../registry-shortcut-backup.mjs | 15 ++++++- tools/win-update-e2e/run.mjs | 4 ++ 19 files changed, 198 insertions(+), 47 deletions(-) diff --git a/.github/workflows/daemon-relocation-spike.yml b/.github/workflows/daemon-relocation-spike.yml index aa7854e59..319580dc2 100644 --- a/.github/workflows/daemon-relocation-spike.yml +++ b/.github/workflows/daemon-relocation-spike.yml @@ -33,6 +33,9 @@ jobs: 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 diff --git a/.github/workflows/win-update-e2e.yml b/.github/workflows/win-update-e2e.yml index c9b3ce505..21c788256 100644 --- a/.github/workflows/win-update-e2e.yml +++ b/.github/workflows/win-update-e2e.yml @@ -75,6 +75,9 @@ jobs: 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 diff --git a/.github/workflows/win-update-survival-e2e.yml b/.github/workflows/win-update-survival-e2e.yml index 6ab76f271..f5e7cb093 100644 --- a/.github/workflows/win-update-survival-e2e.yml +++ b/.github/workflows/win-update-survival-e2e.yml @@ -48,6 +48,9 @@ jobs: 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 diff --git a/src/main/daemon/daemon-entry.ts b/src/main/daemon/daemon-entry.ts index 6123d864b..713cc8402 100644 --- a/src/main/daemon/daemon-entry.ts +++ b/src/main/daemon/daemon-entry.ts @@ -81,15 +81,35 @@ async function main(): Promise { }) 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 (reason: string): Promise => { - daemonLog.log('shutdown', { reason }) - if (daemon) { - await daemon.shutdown() - daemon = null + // 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) } - daemonLog.close() - process.exit(0) } process.on('SIGTERM', () => void shutdown('SIGTERM')) diff --git a/src/main/daemon/daemon-file-log.ts b/src/main/daemon/daemon-file-log.ts index b4c5867f2..01090aedf 100644 --- a/src/main/daemon/daemon-file-log.ts +++ b/src/main/daemon/daemon-file-log.ts @@ -70,6 +70,12 @@ export function createDaemonFileLog( // 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}` diff --git a/src/main/daemon/daemon-host-relocation.test.ts b/src/main/daemon/daemon-host-relocation.test.ts index 6025027b3..1d3ab98db 100644 --- a/src/main/daemon/daemon-host-relocation.test.ts +++ b/src/main/daemon/daemon-host-relocation.test.ts @@ -66,12 +66,19 @@ function buildInstallFixture(root: string): void { writeFileSync(join(nativeDir, 'conpty.pdb'), 'debug-symbols') mkdirSync(join(nativeDir, 'conpty'), { recursive: true }) writeFileSync(join(nativeDir, 'conpty', 'conpty.dll'), 'conpty-dll') - // Other-arch prebuild the x64 host never loads — must be filtered from the copy. - const arm64Dir = join(root, 'resources', 'node_modules', 'node-pty', 'prebuilds', 'win32-arm64') - mkdirSync(arm64Dir, { recursive: true }) - writeFileSync(join(arm64Dir, 'pty.node'), 'arm64-prebuild') + // 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') @@ -130,12 +137,13 @@ describe('buildDaemonHostManifest', () => { // 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 + other-arch prebuilds. + // 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/win32-arm64/pty.node')).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) }) }) @@ -159,7 +167,8 @@ describe('materializeRelocatedDaemonHost', () => { expect( existsSync(join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'chunks', 'a.js')) ).toBe(true) - // Trim: GPU DLLs, .pdb debug symbols, and other-arch prebuilds are excluded. + // 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( @@ -167,11 +176,9 @@ describe('materializeRelocatedDaemonHost', () => { join(dest, 'resources', 'node_modules', 'node-pty', 'build', 'Release', 'conpty.pdb') ) ).toBe(false) - expect( - existsSync( - join(dest, 'resources', 'node_modules', 'node-pty', 'prebuilds', 'win32-arm64', 'pty.node') - ) - ).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') diff --git a/src/main/daemon/daemon-host-relocation.ts b/src/main/daemon/daemon-host-relocation.ts index 167832eec..ac674fdd2 100644 --- a/src/main/daemon/daemon-host-relocation.ts +++ b/src/main/daemon/daemon-host-relocation.ts @@ -133,13 +133,21 @@ function collectDaemonHostSources(): DaemonHostSources | null { } } -// node-pty ships debug symbols (.pdb) and prebuilds for other CPU arches; the -// run-as-node daemon loads neither (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 — leaving only the arch-native binaries the host actually loads. +// 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() - return !p.endsWith('.pdb') && !p.includes('win32-arm64') + 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 } /** diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts index bb2f1f4b7..536d3cc9b 100644 --- a/src/main/daemon/daemon-init.test.ts +++ b/src/main/daemon/daemon-init.test.ts @@ -996,7 +996,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - expect.arrayContaining(['--socket', '/fake/socket', '--token', '/fake/token', '--log-file']), + 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 }) ) }) @@ -1122,7 +1129,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - expect.arrayContaining(['--socket', '/fake/socket', '--token', '/fake/token', '--log-file']), + 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 }) ) }) @@ -1239,7 +1253,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - expect.arrayContaining(['--socket', '/fake/socket', '--token', '/fake/token', '--log-file']), + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) @@ -1499,7 +1520,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - expect.arrayContaining(['--socket', '/fake/socket', '--token', '/fake/token', '--log-file']), + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) @@ -1584,7 +1612,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - expect.arrayContaining(['--socket', '/fake/socket', '--token', '/fake/token', '--log-file']), + 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/tools/daemon-relocation-spike/daemon-launch.mjs b/tools/daemon-relocation-spike/daemon-launch.mjs index f90d44eba..74784db9f 100644 --- a/tools/daemon-relocation-spike/daemon-launch.mjs +++ b/tools/daemon-relocation-spike/daemon-launch.mjs @@ -72,6 +72,9 @@ export function launchDaemonHost(options) { 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 }) diff --git a/tools/daemon-relocation-spike/loaded-module-probe.mjs b/tools/daemon-relocation-spike/loaded-module-probe.mjs index a3dacdbf3..07170a508 100644 --- a/tools/daemon-relocation-spike/loaded-module-probe.mjs +++ b/tools/daemon-relocation-spike/loaded-module-probe.mjs @@ -3,15 +3,18 @@ // NSIS update and defeat the relocation. import { spawnSync } from 'node:child_process' -import { join, normalize, sep } from 'node:path' +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 for Windows paths. +// 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 normalize(p) + return win32 + .normalize(p) .replace(/[\\/]+$/, '') .toLowerCase() } @@ -23,7 +26,7 @@ function normalizeForCompare(p) { */ export function findAppDirResidentModules(modulePaths, appDir) { const needle = normalizeForCompare(appDir) - const prefix = `${needle}${sep}` + const prefix = `${needle}${win32.sep}` return modulePaths.filter((raw) => { const candidate = normalizeForCompare(raw) return candidate === needle || candidate.startsWith(prefix) @@ -43,6 +46,11 @@ export function probeLoadedModules(pid) { 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( diff --git a/tools/daemon-relocation-spike/spike.mjs b/tools/daemon-relocation-spike/spike.mjs index 8a58f6988..5ce1c9eac 100644 --- a/tools/daemon-relocation-spike/spike.mjs +++ b/tools/daemon-relocation-spike/spike.mjs @@ -227,6 +227,9 @@ async function runLaunch(opts) { 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) { diff --git a/tools/win-update-e2e/app-driver.mjs b/tools/win-update-e2e/app-driver.mjs index 8c4004141..8f16a4464 100644 --- a/tools/win-update-e2e/app-driver.mjs +++ b/tools/win-update-e2e/app-driver.mjs @@ -256,7 +256,9 @@ export async function focusActiveTerminal(page) { } const surface = page.locator(TERMINAL_SURFACE_VISIBLE).first() await surface.click({ position: { x: 24, y: 24 }, timeout: 15_000 }).catch(() => {}) - const input = page.locator(XTERM_INPUT).last() + // 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 } diff --git a/tools/win-update-e2e/cli-args.mjs b/tools/win-update-e2e/cli-args.mjs index e7a091848..ed5041231 100644 --- a/tools/win-update-e2e/cli-args.mjs +++ b/tools/win-update-e2e/cli-args.mjs @@ -74,7 +74,9 @@ export function parseArgs(argv) { usage: USAGE } - const errors = validate(opts) + // 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 } } @@ -136,8 +138,14 @@ export function validateInstallDir(installDir) { let entries = [] try { entries = readdirSync(installDir) - } catch { - /* unreadable — treat as empty below */ + } 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( @@ -150,7 +158,7 @@ export function validateInstallDir(installDir) { return errors } -function validate(opts) { +function validate(opts, installDirFlagPresent) { const errors = [] if (!opts.from && !opts.fromRelease) { errors.push('Missing base installer: pass --from or --from-release ') @@ -172,7 +180,9 @@ function validate(opts) { if (!Number.isFinite(opts.soakSeconds) || opts.soakSeconds < 0) { errors.push('--soak-seconds must be a non-negative number') } - if (opts.installDir !== undefined) { + 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 diff --git a/tools/win-update-e2e/daemon-processes.mjs b/tools/win-update-e2e/daemon-processes.mjs index abce3e805..cfd9c5d41 100644 --- a/tools/win-update-e2e/daemon-processes.mjs +++ b/tools/win-update-e2e/daemon-processes.mjs @@ -78,13 +78,16 @@ export function readDaemonPidFiles(userDataDir = defaultUserDataDir()) { 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 { - const raw = readFileSync(filePath, 'utf8').trim() + 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(readFileSync(filePath, 'utf8').trim()) + const pid = Number(raw) if (Number.isInteger(pid)) { records.push({ file: filePath, pid }) } diff --git a/tools/win-update-e2e/installer-steps.mjs b/tools/win-update-e2e/installer-steps.mjs index c6b7c36f6..18ba4ed09 100644 --- a/tools/win-update-e2e/installer-steps.mjs +++ b/tools/win-update-e2e/installer-steps.mjs @@ -92,7 +92,11 @@ export function silentInstall(setupExe, { timeoutMs = 180_000, installDir = null throw new Error(`Failed to launch installer ${setupExe}: ${proc.error.message}`) } - const exePath = waitForInstalledExe(timeoutMs, installDir) + // 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`) @@ -100,11 +104,11 @@ export function silentInstall(setupExe, { timeoutMs = 180_000, installDir = null return { exePath, version: getExeVersion(exePath) } } -function waitForInstalledExe(timeoutMs, installDir = null) { +function waitForInstalledExe(timeoutMs, installDir = null, expectedVersion = null) { const deadline = Date.now() + timeoutMs while (Date.now() < deadline) { const exe = locateInstalledExe(installDir) - if (exe) { + if (exe && (!expectedVersion || getExeVersion(exe) === expectedVersion)) { return exe } sleepSync(1000) diff --git a/tools/win-update-e2e/powershell-runner.mjs b/tools/win-update-e2e/powershell-runner.mjs index 383ee0f43..68561b261 100644 --- a/tools/win-update-e2e/powershell-runner.mjs +++ b/tools/win-update-e2e/powershell-runner.mjs @@ -9,6 +9,9 @@ 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 }. @@ -18,6 +21,7 @@ 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 { @@ -71,6 +75,7 @@ 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 { diff --git a/tools/win-update-e2e/preflight.mjs b/tools/win-update-e2e/preflight.mjs index c31c31c3f..b5218ed01 100644 --- a/tools/win-update-e2e/preflight.mjs +++ b/tools/win-update-e2e/preflight.mjs @@ -28,7 +28,15 @@ export function findAppProcesses() { ` [pscustomobject]@{ pid = $_.ProcessId; path = $_.ExecutablePath; commandLine = $_.CommandLine } })`, `ConvertTo-Json -InputObject @{ processes = $out } -Depth 4 -Compress` ].join('\n') - const { stdout } = runCommandSync(command) + // 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 [] @@ -37,8 +45,11 @@ export function findAppProcesses() { const parsed = JSON.parse(trimmed) const arr = parsed.processes return Array.isArray(arr) ? arr : arr ? [arr] : [] - } catch { - return [] + } catch (parseError) { + throw new Error( + `Orca app process query returned invalid JSON: ${parseError.message}\n` + + `stdout:\n${trimmed}\nstderr:\n${stderr}` + ) } } diff --git a/tools/win-update-e2e/registry-shortcut-backup.mjs b/tools/win-update-e2e/registry-shortcut-backup.mjs index ef55491cb..59f66e914 100644 --- a/tools/win-update-e2e/registry-shortcut-backup.mjs +++ b/tools/win-update-e2e/registry-shortcut-backup.mjs @@ -168,6 +168,7 @@ export function restoreInstallState(manifest) { const result = { imported: [], deleted: [], + failures: [], shortcutsRestored: [], shortcutsDeleted: [], verified: false @@ -177,27 +178,39 @@ export function restoreInstallState(manifest) { 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() - result.verified = normLoc(manifest.installLocation) === normLoc(after.installLocation) + // 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) } diff --git a/tools/win-update-e2e/run.mjs b/tools/win-update-e2e/run.mjs index babdf561f..7c8d8cde6 100644 --- a/tools/win-update-e2e/run.mjs +++ b/tools/win-update-e2e/run.mjs @@ -179,6 +179,10 @@ async function runProof(ctx, args) { }) 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