From 95415014e4a905c2b245f99dc80ded1633818f86 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 6 Jul 2026 16:43:48 -0400 Subject: [PATCH] ci: add manual Windows update-survival E2E workflow + harden harness uninstall MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds .github/workflows/win-update-e2e.yml (workflow_dispatch): on a clean windows-2022 runner, downloads two release installers, runs the update-survival harness, and uploads the output log. A CI runner is the only safe home for install-based testing — electron-builder oneClick uninstalls the registry-registered app before every install, so running the harness on a machine with a real Orca install deletes it. Also hardens the harness against that exact hazard: silentUninstall now requires an explicit install directory (no scan-and-discover fallback) and refuses the default per-user location unless a caller that owns the install opts in; non-isolated teardown uninstalls only the exact dir it installed into. --- .github/workflows/win-update-e2e.yml | 115 +++++++++++++ tools/win-update-e2e/installer-steps.mjs | 83 +++++++--- tools/win-update-e2e/run.mjs | 197 ++++++++++++++++++++--- 3 files changed, 355 insertions(+), 40 deletions(-) create mode 100644 .github/workflows/win-update-e2e.yml diff --git a/.github/workflows/win-update-e2e.yml b/.github/workflows/win-update-e2e.yml new file mode 100644 index 000000000..6bda424f9 --- /dev/null +++ b/.github/workflows/win-update-e2e.yml @@ -0,0 +1,115 @@ +name: Windows Update-Survival E2E + +# Why: proves what happens to terminal sessions across a real Windows app update +# by installing one released version, updating to another, and asserting on the +# packaged artifacts (daemon survival, terminal interactivity, zero console +# flashes). This MUST run on a disposable CI Windows: electron-builder's oneClick +# installer uninstalls the registry-registered copy of the app before every +# install, so running the harness on a machine with a real Orca install would +# delete it. A fresh runner has no Orca registered, so it is the only safe home +# for install-based testing. Manual dispatch only. + +on: + workflow_dispatch: + inputs: + from_tag: + description: Release tag to install first (e.g. v1.4.124-rc.8) + required: true + type: string + to_tag: + description: Release tag to update to (e.g. v1.4.124-rc.9) + required: true + type: string + expect: + description: Expected outcome profile + required: true + type: choice + default: cold-restore + options: + - cold-restore + - survival + asset_pattern: + description: Installer asset glob + required: false + type: string + default: '*windows-setup.exe' + soak_seconds: + description: Post-relaunch console-window watch duration + required: false + type: string + default: '60' + +permissions: + contents: read + +concurrency: + group: win-update-e2e-${{ github.ref }} + cancel-in-progress: false + +jobs: + update-e2e: + name: update ${{ inputs.from_tag }} -> ${{ inputs.to_tag }} (${{ inputs.expect }}) + runs-on: windows-2022 + timeout-minutes: 30 + + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + # Why: the harness only needs its runtime deps (the Playwright Electron + # driver); it drives already-built installer artifacts, so no app build. + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Why: fail fast with a readable message if a tag has no matching Windows + # installer, rather than deep inside the harness. + - name: Download installers + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: pwsh + run: | + New-Item -ItemType Directory -Force artifacts/from | Out-Null + New-Item -ItemType Directory -Force artifacts/to | Out-Null + gh release download "${{ inputs.from_tag }}" --repo "${{ github.repository }}" --pattern "${{ inputs.asset_pattern }}" --dir artifacts/from + gh release download "${{ inputs.to_tag }}" --repo "${{ github.repository }}" --pattern "${{ inputs.asset_pattern }}" --dir artifacts/to + $from = Get-ChildItem artifacts/from -Filter *.exe | Select-Object -First 1 + $to = Get-ChildItem artifacts/to -Filter *.exe | Select-Object -First 1 + if (-not $from) { throw "No installer matching '${{ inputs.asset_pattern }}' in ${{ inputs.from_tag }}" } + if (-not $to) { throw "No installer matching '${{ inputs.asset_pattern }}' in ${{ inputs.to_tag }}" } + "FROM_EXE=$($from.FullName)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + "TO_EXE=$($to.FullName)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + + # Why: no --install-dir here. A CI runner has no real Orca registered, so + # the harness installs to the default per-user location and owns it — the + # isolated-install machinery exists only to (imperfectly) protect a real + # developer install, which does not apply on a throwaway runner. + - name: Run update-survival harness + id: harness + shell: pwsh + run: | + $log = "artifacts/harness-output.log" + node tools/win-update-e2e/run.mjs ` + --from "$env:FROM_EXE" ` + --to "$env:TO_EXE" ` + --expect "${{ inputs.expect }}" ` + --soak-seconds "${{ inputs.soak_seconds }}" 2>&1 | Tee-Object -FilePath $log + exit $LASTEXITCODE + + - name: Upload harness output + if: always() + uses: actions/upload-artifact@v7 + with: + name: win-update-e2e-output + path: artifacts/harness-output.log + retention-days: 7 + if-no-files-found: warn diff --git a/tools/win-update-e2e/installer-steps.mjs b/tools/win-update-e2e/installer-steps.mjs index dbcfe89f9..c6b7c36f6 100644 --- a/tools/win-update-e2e/installer-steps.mjs +++ b/tools/win-update-e2e/installer-steps.mjs @@ -70,32 +70,40 @@ function findSetupExe(dir) { * Run an NSIS installer in one-click silent mode and wait for the installed exe * to appear. Returns { exePath, version }. The installer process returns before * copying finishes, so completion is confirmed by polling for the exe. + * + * When `installDir` is set (isolated-install mode), `/D=` overrides the + * install location. `/D` is special in NSIS: it must be the LAST argument and + * cannot be quoted, so the path must be spaces-free (validated upstream) and is + * passed as a single unquoted argv entry. */ -export function silentInstall(setupExe, { timeoutMs = 180_000 } = {}) { +export function silentInstall(setupExe, { timeoutMs = 180_000, installDir = null } = {}) { assertWin32('silentInstall') if (!existsSync(setupExe)) { throw new Error(`Installer not found: ${setupExe}`) } // /S is the NSIS silent switch; the electron-builder oneClick installer needs - // no other flags for a per-user install. - const proc = spawnSync(setupExe, ['/S'], { encoding: 'utf8' }) + // no other flags for a per-user install. /D, when present, MUST be last. + const args = ['/S'] + if (installDir) { + args.push(`/D=${installDir}`) + } + const proc = spawnSync(setupExe, args, { encoding: 'utf8' }) if (proc.error) { throw new Error(`Failed to launch installer ${setupExe}: ${proc.error.message}`) } - const exePath = waitForInstalledExe(timeoutMs) + const exePath = waitForInstalledExe(timeoutMs, installDir) if (!exePath) { - throw new Error( - `Installed ${EXE_NAME} did not appear under ${programsRoot()} within ${timeoutMs}ms` - ) + const where = installDir ?? programsRoot() + throw new Error(`Installed ${EXE_NAME} did not appear under ${where} within ${timeoutMs}ms`) } return { exePath, version: getExeVersion(exePath) } } -function waitForInstalledExe(timeoutMs) { +function waitForInstalledExe(timeoutMs, installDir = null) { const deadline = Date.now() + timeoutMs while (Date.now() < deadline) { - const exe = locateInstalledExe() + const exe = locateInstalledExe(installDir) if (exe) { return exe } @@ -104,8 +112,16 @@ function waitForInstalledExe(timeoutMs) { return null } -/** Locate the installed Orca.exe under %LOCALAPPDATA%\Programs (case-tolerant). */ -export function locateInstalledExe() { +/** + * Locate the installed Orca.exe. In isolated mode (`installDir` set), the exe is + * at a known fixed path (\Orca.exe). Otherwise it is discovered + * under %LOCALAPPDATA%\Programs (case-tolerant — casing is not guaranteed). + */ +export function locateInstalledExe(installDir = null) { + if (installDir) { + const exe = path.join(installDir, EXE_NAME) + return existsSync(exe) ? exe : null + } const root = programsRoot() if (!existsSync(root)) { return null @@ -126,28 +142,55 @@ export function getExeVersion(exePath) { } /** - * 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. + * Silently uninstall the test install at an EXPLICIT directory via its + * NSIS-generated uninstaller. Best-effort: returns false if no uninstaller is + * found rather than throwing, so teardown never masks the real assertion result. + * + * SAFETY: `installDir` is REQUIRED and must be the exact directory the harness + * installed into this run — there is deliberately no scan-and-discover fallback, + * because a `null` default once made this function locate and uninstall the + * developer's REAL Orca. It additionally refuses to run against the default + * per-user install location unless `allowDefaultLocation` is explicitly set (only + * the owns-the-install non-isolated teardown may do so). */ -export function silentUninstall() { +export function silentUninstall(installDir, { allowDefaultLocation = false } = {}) { assertWin32('silentUninstall') - const exe = locateInstalledExe() - if (!exe) { + if (typeof installDir !== 'string' || installDir.trim() === '') { + throw new Error('silentUninstall requires an explicit install directory (no scan fallback)') + } + const resolved = path.resolve(installDir) + if (!allowDefaultLocation && pathsEqual(resolved, path.join(programsRoot(), PRODUCT_NAME))) { + throw new Error( + `Refusing to uninstall the default install location "${resolved}" — this is where a ` + + `developer's REAL Orca lives. Isolated mode must target a separate --install-dir.` + ) + } + const exe = path.join(resolved, EXE_NAME) + if (!existsSync(exe)) { return false } - const installDir = path.dirname(exe) - const uninstaller = path.join(installDir, `Uninstall ${PRODUCT_NAME}.exe`) + const exeDir = resolved + const uninstaller = path.join(exeDir, `Uninstall ${PRODUCT_NAME}.exe`) if (!existsSync(uninstaller)) { return false } // NSIS uninstallers must be run from a copy (they relocate themselves); _?= // forces synchronous, in-place uninstall so we can assert completion. - spawnSync(uninstaller, ['/S', `_?=${installDir}`], { encoding: 'utf8' }) + spawnSync(uninstaller, ['/S', `_?=${exeDir}`], { encoding: 'utf8' }) sleepSync(2000) return !existsSync(exe) } +/** Case-insensitive path equality after trailing-separator normalization. */ +function pathsEqual(a, b) { + const norm = (p) => + path + .resolve(p) + .replace(/[\\/]+$/, '') + .toLowerCase() + return norm(a) === norm(b) +} + function sleepSync(ms) { // Blocking sleep via Atomics keeps install polling simple and synchronous. const sab = new Int32Array(new SharedArrayBuffer(4)) diff --git a/tools/win-update-e2e/run.mjs b/tools/win-update-e2e/run.mjs index d973fa5cb..c7ba288b4 100644 --- a/tools/win-update-e2e/run.mjs +++ b/tools/win-update-e2e/run.mjs @@ -5,7 +5,7 @@ // 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 { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import { execFileSync } from 'node:child_process' @@ -13,6 +13,7 @@ import { assertWin32 } from './platform-guard.mjs' import { parseArgs } from './cli-args.mjs' import { preflight } from './preflight.mjs' import { resolveInstaller, silentInstall, silentUninstall } from './installer-steps.mjs' +import { backupInstallState, restoreInstallState } from './registry-shortcut-backup.mjs' import { launchInstalledApp, waitForTerminalReady, @@ -49,6 +50,9 @@ async function main() { } assertWin32('win-update-e2e') + const installDir = opts.installDir ?? null + const isolated = Boolean(installDir) + const runId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}` const canary = `ORCA-E2E-CANARY-${runId}` const runDir = mkdtempSync(path.join(tmpdir(), `orca-win-update-e2e-${runId}-`)) @@ -59,28 +63,115 @@ async function main() { const heartbeatFile = path.join(runDir, 'heartbeat.txt') const created = { markerPid: null, daemonPids: new Set() } - log('setup', `runId=${runId} runDir=${runDir} profile=${opts.expect}`) + log( + 'setup', + `runId=${runId} runDir=${runDir} profile=${opts.expect}${isolated ? ` installDir=${installDir}` : ''}` + ) + if (isolated && opts.keepInstall) { + log( + 'setup', + '--keep-install is ignored in isolated mode: the test install and its per-user ' + + 'registry hijack are always cleaned up so the real install stays safe.' + ) + } const { warnings, existingInstall } = preflight({ baselinePath, - allowExistingInstall: opts.allowExistingInstall + allowExistingInstall: opts.allowExistingInstall, + installDir }) const hadPreexistingInstall = Boolean(existingInstall) for (const w of warnings) { log('preflight-warning', w) } + // Isolated mode: snapshot the shared per-user registry keys + shortcuts BEFORE + // any install writes over them. Everything after this must run through the + // try/finally so the snapshot is always restored, even on failure. + let manifest = null + if (isolated) { + manifest = backupInstallState(runDir) + log('isolated', `backed up install registry/shortcut state -> ${manifest.backupDir}`) + } + + const runArgs = { + opts, + installDir, + canary, + runDir, + userDataDir, + baselinePath, + watchOut, + markerPidFile, + heartbeatFile, + created + } + + // Isolated mode ALWAYS restores registry/shortcuts and tears down the test + // install, whatever happens in the proof body. Non-isolated flow is unchanged: + // teardown runs after a successful body only (a thrown body surfaces as FATAL). + const ctx = { session: null } + if (isolated) { + let passed = false + try { + passed = await runProof(ctx, runArgs) + } finally { + await isolatedTeardown({ + app: ctx.session?.app, + created, + userDataDir, + installDir, + manifest, + runDir + }) + } + return passed ? 0 : 1 + } + + const passed = await runProof(ctx, runArgs) + await teardown({ + app: ctx.session?.app, + created, + userDataDir, + keepInstall: opts.keepInstall, + hadPreexistingInstall, + installedExePath: ctx.installedExePath ?? null, + runDir + }) + return passed ? 0 : 1 +} + +/** + * Run the install → drive → update → relaunch → assert proof. `ctx.session` is + * assigned as soon as each app launches so a caller's finally can tear down a + * partially-created session on failure. Returns whether every assertion passed. + */ +async function runProof(ctx, args) { + const { + opts, + installDir, + canary, + runDir, + userDataDir, + baselinePath, + watchOut, + markerPidFile, + heartbeatFile, + created + } = args + const fromInstaller = resolveInstaller({ localPath: opts.from, releaseTag: opts.fromRelease, assetPattern: opts.assetPattern }) log('install-base', `installing ${fromInstaller}`) - const base = silentInstall(fromInstaller) + const base = silentInstall(fromInstaller, { installDir }) 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 }) + ctx.session = session await waitForTerminalReady(session.page) await createTerminalTab(session.page) const tabIds = await listTabIds(session.page) @@ -117,11 +208,15 @@ async function main() { assetPattern: opts.assetPattern }) log('update', `installing ${toInstaller}`) - const updated = silentInstall(toInstaller) + const updated = silentInstall(toInstaller, { installDir }) + // Record the exact dir the harness installed into so non-isolated teardown + // uninstalls THAT and never scan-discovers the developer's real install. + ctx.installedExePath = updated.exePath log('update', `installed ${updated.exePath} (version ${updated.version})`) // --- Relaunch and gather post-update evidence --- session = await launchInstalledApp({ exePath: updated.exePath, userDataDir }) + ctx.session = session await waitForTerminalReady(session.page) const evidence = await gatherEvidence({ @@ -142,7 +237,7 @@ async function main() { const { events } = await watch.stop() log('watch', `recorded ${events.length} new-window events`) - const ctx = { + const assertionCtx = { profile: opts.expect, canary, watchEvents: events, @@ -150,20 +245,11 @@ async function main() { daemonLog: readDaemonLog(userDataDir), ...evidence } - const assertions = buildAssertions(ctx) + const assertions = buildAssertions(assertionCtx) 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 + return passed } async function gatherEvidence(args) { @@ -303,7 +389,71 @@ export function readDaemonLog(userDataDir) { return { path: logPath, errorLines, suppressedCount } } -async function teardown({ app, created, userDataDir, keepInstall, hadPreexistingInstall, runDir }) { +/** + * Isolated-mode teardown. The harness OWNS the isolated dir by construction, so + * it always uninstalls the test install, then ALWAYS restores the shared per-user + * registry keys + shortcuts the installer hijacked (the uninstaller clears the + * test install's copies; restore re-imports the real install's originals or + * deletes freshly-created keys). Finally removes the emptied install dir + runDir. + */ +async function isolatedTeardown({ app, created, userDataDir, installDir, manifest, runDir }) { + try { + await closeApp(app) + } catch { + /* already closed / never launched */ + } + killPid(created.markerPid) + for (const pid of resolveScopedDaemon(userDataDir).pids) { + killPid(pid) + } + for (const pid of created.daemonPids) { + killPid(pid) + } + + const uninstalled = silentUninstall(installDir) + log('isolated-teardown', `uninstalled test install: ${uninstalled}`) + + try { + const restore = restoreInstallState(manifest) + log( + 'isolated-teardown', + `registry restore verified=${restore.verified} imported=[${restore.imported.join(', ')}] ` + + `deleted=[${restore.deleted.join(', ')}] shortcutsRestored=${restore.shortcutsRestored.length} ` + + `shortcutsDeleted=${restore.shortcutsDeleted.length}` + ) + } catch (err) { + // Restore must never be silently skipped — surface it loudly and point at the + // manifest so the shared keys can be recovered by hand. + console.error( + `\n*** WIN-UPDATE-E2E: registry/shortcut restore THREW: ${err.stack || err.message}\n` + + ` Recover manually from the backups under ${manifest?.backupDir}. ***\n` + ) + } + + removeDirIfEmpty(installDir) + rmSync(runDir, { recursive: true, force: true }) +} + +/** Remove a directory only if it is empty (best-effort; leaves non-empty dirs). */ +function removeDirIfEmpty(dir) { + try { + if (existsSync(dir) && readdirSync(dir).length === 0) { + rmSync(dir, { recursive: true, force: true }) + } + } catch { + /* leave it in place */ + } +} + +async function teardown({ + app, + created, + userDataDir, + keepInstall, + hadPreexistingInstall, + installedExePath, + runDir +}) { try { await closeApp(app) } catch { @@ -332,9 +482,16 @@ async function teardown({ app, created, userDataDir, keepInstall, hadPreexisting ' --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() + } else if (installedExePath) { + // Uninstall ONLY the exact directory the harness installed into this run, + // with the explicit default-location opt-in (non-isolated mode legitimately + // installs to the default path and owns it here). Never scan-and-discover. + const uninstalled = silentUninstall(path.dirname(installedExePath), { + allowDefaultLocation: true + }) log('teardown', `uninstalled: ${uninstalled}`) + } else { + log('teardown', 'no install path recorded; skipping uninstall (nothing owned to remove)') } rmSync(runDir, { recursive: true, force: true }) }