Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

test(windows): Electron-level regression test for the quit-time tree sweep

Pontus Munck87ef8d5523dd
diff --git a/package.json b/package.json
index 97bb375a..eeaf286a 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/release-notes.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/ide-image.test.cjs test/win-cmd-shim.test.cjs test/hive-windows-prompt.test.cjs test/release-drop.test.cjs test/skills.test.cjs test/skills-install.test.cjs test/hero-payload.test.cjs",
+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/quit-sweep.electron.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/release-notes.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/ide-image.test.cjs test/win-cmd-shim.test.cjs test/hive-windows-prompt.test.cjs test/release-drop.test.cjs test/skills.test.cjs test/skills-install.test.cjs test/hero-payload.test.cjs",
"check:links": "node tools/check-release-links.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
diff --git a/test/fixtures/quit-sweep-main.cjs b/test/fixtures/quit-sweep-main.cjs
new file mode 100644
index 00000000..381b2b4d
--- /dev/null
+++ b/test/fixtures/quit-sweep-main.cjs
@@ -0,0 +1,98 @@
+'use strict';
+/**
+ * Electron main fixture for test/quit-sweep.electron.test.cjs — runs INSIDE
+ * Electron (real lifecycle, real ConPTY-patched node-pty, which is rebuilt for
+ * Electron's ABI and therefore unloadable from plain Node).
+ *
+ * Reproduces the quit path that leaked agent trees on Windows: spawn a real
+ * PTY whose child has a child of its own, record the live tree's PIDs to
+ * --pid-file, then run PtyManager.killAll() and exit ~1.2s later — the same
+ * bounded window teardownAndQuit/will-quit gives the analytics flush. Pre-fix,
+ * ensureKilled's 4s unref'd taskkill timer could never fire inside that window,
+ * so the tree survived the app; the synchronous win32 sweep must kill it here.
+ */
+const { app } = require('electron');
+const { execFileSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+const pidFile = process.argv.find((a) => a.startsWith('--pid-file='))?.slice('--pid-file='.length);
+
+function bail(code, message) {
+ try {
+ if (pidFile) fs.writeFileSync(pidFile, JSON.stringify({ error: message }), 'utf8');
+ } catch { /* the outer test will report the missing file instead */ }
+ console.error(`[fixture] ${message}`);
+ app.exit(code);
+}
+
+/** All live descendants of `root`, walked from one Win32_Process snapshot. */
+function descendantsOf(root) {
+ const raw = execFileSync('powershell.exe', [
+ '-NoProfile', '-Command',
+ 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId | ConvertTo-Json -Compress'
+ ], { encoding: 'utf8', timeout: 30_000, windowsHide: true });
+ const byParent = new Map();
+ for (const row of JSON.parse(raw)) {
+ const list = byParent.get(row.ParentProcessId) ?? [];
+ list.push(row.ProcessId);
+ byParent.set(row.ParentProcessId, list);
+ }
+ const out = [];
+ const stack = [root];
+ while (stack.length) {
+ for (const child of byParent.get(stack.pop()) ?? []) {
+ out.push(child);
+ stack.push(child);
+ }
+ }
+ return out;
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// Belt-and-braces: if anything below wedges, die loudly instead of hanging the
+// outer test until its own timeout. app.exit() on the happy path preempts this.
+setTimeout(() => bail(4, 'fixture timed out'), 45_000);
+
+app.whenReady().then(async () => {
+ if (!pidFile) return bail(2, 'missing --pid-file argument');
+
+ const loadTs = require('../load-ts.cjs');
+ const { PtyManager } = loadTs('src/main/pty.ts');
+ const mgr = new PtyManager();
+
+ // powershell (PTY root) that starts a hidden child powershell — a minimal
+ // stand-in for an agent CLI with helper processes of its own.
+ const psExe = path.join(
+ process.env.SystemRoot || 'C:\\Windows',
+ 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'
+ );
+ const script =
+ `Start-Process -WindowStyle Hidden -FilePath '${psExe}' ` +
+ `-ArgumentList '-NoProfile','-Command','Start-Sleep 300'; Start-Sleep 300`;
+ const res = mgr.spawn({
+ id: 'quit-sweep-fixture',
+ cwd: os.tmpdir(),
+ command: psExe,
+ args: ['-NoProfile', '-Command', script]
+ });
+ if (!res.ok) return bail(2, `pty spawn failed: ${res.error}`);
+ const rootPid = mgr.list()[0]?.pid;
+ if (!rootPid) return bail(2, 'pty spawned but reported no pid');
+
+ // Wait until the grandchild exists — killing a tree of one proves nothing.
+ let pids = [];
+ for (let i = 0; i < 30 && pids.length < 2; i++) {
+ await sleep(500);
+ pids = [rootPid, ...descendantsOf(rootPid)];
+ }
+ if (pids.length < 2) return bail(2, `tree never grew a descendant (root ${rootPid})`);
+ fs.writeFileSync(pidFile, JSON.stringify({ root: rootPid, pids }), 'utf8');
+
+ // The quit path under test: killAll, then exit inside the same ~1.2s window
+ // the real teardown allows will-quit's bounded analytics flush.
+ mgr.killAll();
+ setTimeout(() => app.exit(0), 1_200);
+}).catch((e) => bail(3, `fixture threw: ${e?.stack || e}`));
diff --git a/test/quit-sweep.electron.test.cjs b/test/quit-sweep.electron.test.cjs
new file mode 100644
index 00000000..4440ed98
--- /dev/null
+++ b/test/quit-sweep.electron.test.cjs
@@ -0,0 +1,89 @@
+'use strict';
+/**
+ * Regression test for the Windows quit-time process-tree leak (276f782):
+ * PtyManager.killAll() deferred its `taskkill /T /F` backstop 4s on an unref'd
+ * timer, but the quit path exits the main process ~1.2s after killAll, so the
+ * sweep never ran and agent trees survived the app. The bug lived in the
+ * ELECTRON lifecycle (early process exit killing unref'd timers) and node-pty
+ * here is rebuilt for Electron's ABI — so this test launches the real Electron
+ * binary with test/fixtures/quit-sweep-main.cjs as its main script. The fixture
+ * spawns a real PTY tree, records its PIDs, runs killAll(), and exits on the
+ * same ~1.2s schedule as teardownAndQuit; we then assert every recorded PID is
+ * gone. Pre-fix code fails this test (the tree outlives Electron).
+ *
+ * Self-contained, no framework — run with `node test/quit-sweep.electron.test.cjs`
+ * (mirrors test/proc-kill.test.cjs). Windows-only by nature; elsewhere it exits
+ * 0 after a smoke check (POSIX quits kill trees via pty-closure HUP instead).
+ */
+
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawn, execFileSync } = require('node:child_process');
+
+if (process.platform !== 'win32') {
+ console.log(' ok (non-win32: the synchronous quit sweep is Windows-only — POSIX quits HUP the group via pty closure)');
+ process.exit(0);
+}
+
+// From plain Node (not inside Electron), the electron package exports the
+// path to the Electron executable.
+const electronBin = require('electron');
+assert.strictEqual(typeof electronBin, 'string', 'expected electron package to export the binary path');
+
+const fixture = path.join(__dirname, 'fixtures', 'quit-sweep-main.cjs');
+const pidFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'quit-sweep-')), 'pids.json');
+
+function isAlive(pid) {
+ const out = execFileSync('tasklist', ['/FI', `PID eq ${pid}`, '/NH', '/FO', 'CSV'], { encoding: 'utf8' });
+ return out.includes(`"${pid}"`);
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+(async () => {
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE; // must launch as Electron, not as Node
+
+ const child = spawn(electronBin, [fixture, `--pid-file=${pidFile}`], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env,
+ windowsHide: true
+ });
+ let output = '';
+ child.stdout.on('data', (d) => { output += d; });
+ child.stderr.on('data', (d) => { output += d; });
+
+ const exitCode = await new Promise((resolve) => {
+ const timeout = setTimeout(() => {
+ // Hung fixture: reap it (and anything it spawned) so the TEST never leaks.
+ try { execFileSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { timeout: 10_000 }); } catch { /* gone */ }
+ resolve('timeout');
+ }, 60_000);
+ child.on('exit', (code) => { clearTimeout(timeout); resolve(code); });
+ });
+
+ try {
+ assert.notStrictEqual(exitCode, 'timeout', `electron fixture hung; output:\n${output}`);
+ assert.ok(fs.existsSync(pidFile), `fixture never wrote the pid file; output:\n${output}`);
+ const recorded = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
+ assert.ok(!recorded.error, `fixture bailed: ${recorded.error}; output:\n${output}`);
+ assert.strictEqual(exitCode, 0, `electron exited ${exitCode}; output:\n${output}`);
+ assert.ok(recorded.pids.length >= 2, `expected root+descendant, saw: ${recorded.pids.join(',')}`);
+
+ await sleep(500); // let the OS finish reaping what taskkill force-killed
+ const survivors = recorded.pids.filter(isAlive);
+ if (survivors.length) {
+ // Clean up the leak before failing, so a red run doesn't strand processes.
+ for (const pid of survivors) {
+ try { execFileSync('taskkill', ['/pid', String(pid), '/T', '/F'], { timeout: 10_000 }); } catch { /* gone */ }
+ }
+ assert.fail(`process tree survived Electron quit — leaked PIDs: ${survivors.join(',')} of ${recorded.pids.join(',')}`);
+ }
+ console.log(` ok quit sweep reaped the whole tree inside Electron (pids: ${recorded.pids.join(',')})`);
+ } catch (e) {
+ console.error(`FAIL ${e.message}`);
+ process.exit(1);
+ }
+})();