diff --git a/package.json b/package.json index 8faad00f1..d5ab3164f 100644 --- a/package.json +++ b/package.json @@ -80,6 +80,7 @@ "test:e2e:terminal-perf:check-report": "node config/scripts/check-terminal-perf-report-budgets.mjs", "test:e2e:terminal-perf:summarize": "node config/scripts/summarize-terminal-perf-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/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 aeffb7aa2..6123d864b 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,34 @@ 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 - const shutdown = async (): Promise => { + const shutdown = async (reason: string): Promise => { + daemonLog.log('shutdown', { reason }) if (daemon) { await daemon.shutdown() daemon = null } + daemonLog.close() 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) }) @@ -85,6 +106,7 @@ async function main(): Promise { if (process.send) { process.send({ type: 'ready' }) } + 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..b4c5867f2 --- /dev/null +++ b/src/main/daemon/daemon-file-log.ts @@ -0,0 +1,131 @@ +// 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 { + 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-init.test.ts b/src/main/daemon/daemon-init.test.ts index 349cd1fbe..273d30ac0 100644 --- a/src/main/daemon/daemon-init.test.ts +++ b/src/main/daemon/daemon-init.test.ts @@ -968,7 +968,7 @@ 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']), expect.objectContaining({ cwd: '/fake/userData', detached: true }) ) }) @@ -1094,7 +1094,7 @@ 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']), expect.objectContaining({ cwd: '/fake/userData', detached: true }) ) }) @@ -1211,7 +1211,7 @@ 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']), expect.objectContaining({ detached: true }) ) }) @@ -1471,7 +1471,7 @@ 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']), expect.objectContaining({ detached: true }) ) }) @@ -1556,7 +1556,7 @@ 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']), expect.objectContaining({ detached: true }) ) }) diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index ff18ecc33..ba7d8388d 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -44,6 +44,7 @@ import { rebindLocalProviderListeners } from '../ipc/pty' import { isStartupDiagnosticsEnabled, logStartupDiagnostic } from '../startup/startup-diagnostics' +import { getDaemonLogFilePath } from '../observability/logs-directory' // Why: daemon init runs concurrently with window load, so harness-side stderr // arrival times are useless — in-process `t` lets the startup benchmark derive @@ -89,6 +90,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. @@ -260,27 +273,31 @@ 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 + const child = fork( + entryPath, + ['--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: 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) => { 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 @@ -48,6 +50,7 @@ export class DaemonServer { private socketPath: string private tokenPath: string private ptySpawnHealthCheck: () => Promise + private log: DaemonFileLog private clients = new Map() private streamDataBatcher = new DaemonStreamDataBatcher((clientId) => this.clients.get(clientId)) @@ -66,6 +69,7 @@ export class DaemonServer { this.token = randomUUID() this.host = new TerminalHost({ spawnSubprocess: opts.spawnSubprocess }) this.ptySpawnHealthCheck = opts.ptySpawnHealthCheck ?? checkPtySpawnHealth + this.log = opts.log ?? createNoopDaemonFileLog() } async start(): Promise { @@ -139,23 +143,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') { @@ -297,6 +308,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) this.lastInputAtBySessionId.delete(p.sessionId) if (client?.streamSocket) { @@ -312,6 +324,10 @@ export class DaemonServer { } } }) + this.log.log(result.isNew ? 'session-created' : 'session-attached', { + sessionId: p.sessionId, + pid: result.pid + }) return { isNew: result.isNew, snapshot: result.snapshot, @@ -349,6 +365,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 {} @@ -359,6 +379,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': @@ -402,6 +423,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/observability/bundle.test.ts b/src/main/observability/bundle.test.ts index 539eebc70..83ae2ac67 100644 --- a/src/main/observability/bundle.test.ts +++ b/src/main/observability/bundle.test.ts @@ -141,6 +141,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/tools/win-update-e2e/README.md b/tools/win-update-e2e/README.md new file mode 100644 index 000000000..c97c3abcc --- /dev/null +++ b/tools/win-update-e2e/README.md @@ -0,0 +1,154 @@ +# 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) | +| `--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 | + +### 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. + +## 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 | +| `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..2db40ce7b --- /dev/null +++ b/tools/win-update-e2e/app-driver.mjs @@ -0,0 +1,173 @@ +// 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' + +const NEW_TAB_BUTTON = { role: 'button', name: 'New tab' } +const NEW_TERMINAL_ITEM = /New Terminal/i +const SORTABLE_TAB = '[data-testid="sortable-tab"]' +const TERMINAL_SURFACE = '[data-terminal-tab-id]' +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. + */ +export async function launchInstalledApp({ exePath, userDataDir, extraEnv = {} }) { + const { ELECTRON_RUN_AS_NODE: _drop, ...cleanEnv } = process.env + 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 } +} + +/** Wait until at least one terminal surface is mounted and interactive. */ +export async function waitForTerminalReady(page, timeoutMs = 60_000) { + await page.waitForSelector(TERMINAL_SURFACE, { timeout: timeoutMs }) + await page.waitForSelector(XTERM_INPUT, { timeout: timeoutMs }) +} + +/** Create a new terminal tab via the New tab menu. Returns the count after. */ +export async function createTerminalTab(page) { + const before = await page.locator(SORTABLE_TAB).count() + await page.getByRole(NEW_TAB_BUTTON.role, { name: NEW_TAB_BUTTON.name }).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 active terminal's xterm input textarea. */ +export async function focusActiveTerminal(page) { + const input = page.locator(`${XTERM_INPUT}:visible`).last() + await input.focus() + 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, shell-agnostically: + * invoking powershell.exe works whether the pty's shell is cmd, pwsh, + * PowerShell, or a POSIX shell on Windows. Used to write sentinel files. + */ +export async function runShellCommand(page, psCommand) { + const escaped = psCommand.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..7135db5d7 --- /dev/null +++ b/tools/win-update-e2e/cli-args.mjs @@ -0,0 +1,100 @@ +// 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. + +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: + --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. + --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'), + keepInstall: argv.includes('--keep-install'), + allowExistingInstall: argv.includes('--allow-existing-install'), + usage: USAGE + } + + const errors = validate(opts) + return { ...opts, errors } +} + +function validate(opts) { + 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') + } + 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..abce3e805 --- /dev/null +++ b/tools/win-update-e2e/daemon-processes.mjs @@ -0,0 +1,170 @@ +// 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) + try { + const 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()) + 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..dbcfe89f9 --- /dev/null +++ b/tools/win-update-e2e/installer-steps.mjs @@ -0,0 +1,155 @@ +// 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. + */ +export function silentInstall(setupExe, { timeoutMs = 180_000 } = {}) { + 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. + const proc = spawnSync(setupExe, ['/S'], { encoding: 'utf8' }) + if (proc.error) { + throw new Error(`Failed to launch installer ${setupExe}: ${proc.error.message}`) + } + + const exePath = waitForInstalledExe(timeoutMs) + if (!exePath) { + throw new Error( + `Installed ${EXE_NAME} did not appear under ${programsRoot()} within ${timeoutMs}ms` + ) + } + return { exePath, version: getExeVersion(exePath) } +} + +function waitForInstalledExe(timeoutMs) { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + const exe = locateInstalledExe() + if (exe) { + return exe + } + sleepSync(1000) + } + return null +} + +/** Locate the installed Orca.exe under %LOCALAPPDATA%\Programs (case-tolerant). */ +export function locateInstalledExe() { + 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 via the NSIS-generated uninstaller. Best-effort: returns + * false if no uninstaller is found rather than throwing, so teardown never + * masks the real assertion result. + */ +export function silentUninstall() { + assertWin32('silentUninstall') + const exe = locateInstalledExe() + if (!exe) { + return false + } + const installDir = path.dirname(exe) + const uninstaller = path.join(installDir, `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', `_?=${installDir}`], { encoding: 'utf8' }) + sleepSync(2000) + return !existsSync(exe) +} + +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/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..383ee0f43 --- /dev/null +++ b/tools/win-update-e2e/powershell-runner.mjs @@ -0,0 +1,82 @@ +// 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'] + +/** + * 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, + ...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, + ...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..64c5353d0 --- /dev/null +++ b/tools/win-update-e2e/preflight.mjs @@ -0,0 +1,99 @@ +// 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 { 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. + */ +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; commandLine = $_.CommandLine } })`, + `ConvertTo-Json -InputObject @{ processes = $out } -Depth 4 -Compress` + ].join('\n') + const { stdout } = runCommandSync(command) + 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 { + return [] + } +} + +/** + * 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. + */ +export function preflight({ baselinePath, allowExistingInstall = false }) { + assertWin32('preflight') + const warnings = [] + + 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 (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}` + ) + } + + const existingInstall = locateInstalledExe() + if (existingInstall && !allowExistingInstall) { + throw new Error( + `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) { + 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.` + ) + } + + 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/run.mjs b/tools/win-update-e2e/run.mjs new file mode 100644 index 000000000..d973fa5cb --- /dev/null +++ b/tools/win-update-e2e/run.mjs @@ -0,0 +1,377 @@ +// 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, 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 { + launchInstalledApp, + waitForTerminalReady, + createTerminalTab, + listTabIds, + startMarker, + readTerminalTextBestEffort, + closeApp +} 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' + +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 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}`) + + const { warnings, existingInstall } = preflight({ + baselinePath, + allowExistingInstall: opts.allowExistingInstall + }) + const hadPreexistingInstall = Boolean(existingInstall) + for (const w of warnings) { + log('preflight-warning', w) + } + + const fromInstaller = resolveInstaller({ + localPath: opts.from, + releaseTag: opts.fromRelease, + assetPattern: opts.assetPattern + }) + log('install-base', `installing ${fromInstaller}`) + const base = silentInstall(fromInstaller) + log('install-base', `installed ${base.exePath} (version ${base.version})`) + + // --- Base version: launch, create sessions, start marker, record daemon --- + let session = await launchInstalledApp({ exePath: base.exePath, userDataDir }) + await waitForTerminalReady(session.page) + await createTerminalTab(session.page) + const tabIds = await listTabIds(session.page) + log('sessions', `tab ids: ${tabIds.join(', ')}`) + + 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 echoBeforeUpdate = await probeEcho(session.page, runDir, 'echo-pre') + log('sessions', `pre-update echo interactive: ${echoBeforeUpdate}`) + + const preDaemon = resolveScopedDaemon(userDataDir) + preDaemon.pids.forEach((p) => created.daemonPids.add(p)) + log('daemon', `pre-update daemon pid=${preDaemon.pid} appVersion=${preDaemon.appVersion}`) + + 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) + log('update', `installed ${updated.exePath} (version ${updated.version})`) + + // --- Relaunch and gather post-update evidence --- + session = await launchInstalledApp({ exePath: updated.exePath, userDataDir }) + await waitForTerminalReady(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 ctx = { + profile: opts.expect, + canary, + watchEvents: events, + markerPid: created.markerPid, + daemonLog: readDaemonLog(userDataDir), + ...evidence + } + const assertions = buildAssertions(ctx) + const passed = allPassed(assertions) + console.log(renderTable(assertions)) + log('result', passed ? 'PASS' : 'FAIL') + + await teardown({ + app: session.app, + created, + userDataDir, + keepInstall: opts.keepInstall, + hadPreexistingInstall, + runDir + }) + return passed ? 0 : 1 +} + +async function gatherEvidence(args) { + const { profile, page, runDir, heartbeatFile, preDaemon, userDataDir, preScrollback } = args + const postDaemon = resolveScopedDaemon(userDataDir) + + if (profile === 'survival') { + const heartbeatBefore = fileMtimeMs(heartbeatFile) + const heartbeatAdvancedAfterUpdate = await heartbeatAdvancedSince( + heartbeatFile, + heartbeatBefore + ) + const echoObserved = await probeEcho(page, runDir, 'echo-post') + const ctrlCInterrupted = await probeCtrlCInterruptsMarker(page, runDir, heartbeatFile) + return { + preDaemonPid: preDaemon.pid, + postDaemonPid: postDaemon.pid, + postDaemonAlive: postDaemon.pid != null && isPidAlive(postDaemon.pid), + postDaemon, + markerAliveAfter: isMarkerAlive(runDir), + 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') + return { + pid: primary?.pid ?? scan[0]?.pid ?? null, + appVersion: primary?.appVersion ?? null, + startedAtMs: primary?.startedAtMs ?? null, + pids: [...pids] + } +} + +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 } +} + +async function teardown({ app, created, userDataDir, keepInstall, hadPreexistingInstall, 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 { + const uninstalled = silentUninstall() + log('teardown', `uninstalled: ${uninstalled}`) + } + 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) => { + process.exitCode = code + }) + .catch((err) => { + console.error('[win-update-e2e] FATAL:', err.stack || err.message) + process.exitCode = 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 +}