Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: quit ends the engine and the app when shutdown gets stuck

ogsamrat1a74ff6c4cd8
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 5f765e2e..5d7dab44 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -127,6 +127,7 @@ import {
import { installStdioErrorHandlers } from "./stdio-errors.mjs";
import { createTurnGuard } from "./turn-guard.mjs";
import { KEEP_AWAKE_FILE, createKeepAwake } from "./keep-awake.mjs";
+import { armQuitWatchdog } from "./quit-watchdog.mjs";
import { projectChecklist } from "./buildathon-checklist.mjs";
import {
createRendererCrashRecovery,
@@ -3447,6 +3448,8 @@ or use: pnpm dev:worktree`);
event.preventDefault();
if (runtimeDisposeInProgress) return;
showShutdownScreen();
+ // A teardown stuck past its bounds (seen after a sign-out on Windows): the engine and the rest are killed, the app exits.
+ const disarmQuitWatchdog = armQuitWatchdog({ exit: () => app.exit(0), log: (message) => console.warn(`[quit] ${message}`) });
desktopAutomationRunner.stop();
browserLoginSync.shutdown();
// The queued placement events: best effort, never waited for (the rest go next start).
@@ -3470,8 +3473,11 @@ or use: pnpm dev:worktree`);
keepAwake.stop();
scheduleBlankSlateProfileCleanup();
const installUpdateAndQuit = await updateInstall;
- if (installUpdateAndQuit) installUpdateAndQuit();
- else {
+ // An update installing on quit is never cut short (the installer quits the app itself).
+ if (installUpdateAndQuit) {
+ disarmQuitWatchdog();
+ installUpdateAndQuit();
+ } else {
if (restartAfterQuit) app.relaunch();
app.quit();
}
diff --git a/apps/desktop/electron/quit-watchdog.mjs b/apps/desktop/electron/quit-watchdog.mjs
new file mode 100644
index 00000000..2d119832
--- /dev/null
+++ b/apps/desktop/electron/quit-watchdog.mjs
@@ -0,0 +1,73 @@
+// The quit's last resort: a teardown that has not finished in time (a stop
+// stuck behind an engine restart after a sign-out, an upload that never ends)
+// must not leave the window and the engine running. When the watchdog fires,
+// every process this app started (the engine and its children, helpers,
+// Electron's own) is killed and the app exits.
+import { spawnSync } from "node:child_process";
+
+/** Longer than a normal teardown can take: box checkpoints (10 s) + capture stop (20 s) + the engine's stop. */
+export const QUIT_WATCHDOG_MS = 45_000;
+
+/** Every pid below `rootPid` in `rows` ({pid, ppid}), children before their parents' siblings. */
+export function descendantPids(rows, rootPid) {
+ const children = new Map();
+ for (const { pid, ppid } of rows) {
+ if (!children.has(ppid)) children.set(ppid, []);
+ children.get(ppid).push(pid);
+ }
+ const found = [];
+ const seen = new Set([rootPid]);
+ const queue = [rootPid];
+ while (queue.length) {
+ for (const child of children.get(queue.shift()) ?? []) {
+ if (seen.has(child)) continue;
+ seen.add(child);
+ found.push(child);
+ queue.push(child);
+ }
+ }
+ return found;
+}
+
+/** This machine's processes as {pid, ppid} (empty when they cannot be listed). */
+export function listProcesses(platform = process.platform, run = spawnSync) {
+ const result = platform === "win32"
+ ? run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId)\" }"], { encoding: "utf8", windowsHide: true, timeout: 10_000 })
+ : run("ps", ["-Ao", "pid=,ppid="], { encoding: "utf8", timeout: 5_000 });
+ return String(result?.stdout ?? "").split(/\r?\n/).flatMap((line) => {
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
+ return match ? [{ pid: Number(match[1]), ppid: Number(match[2]) }] : [];
+ });
+}
+
+/** Kills every process below `rootPid` (Windows: taskkill /F; elsewhere SIGKILL). Returns the pids it went for. */
+export function killDescendants({ rootPid = process.pid, platform = process.platform, run = spawnSync, kill = process.kill.bind(process) } = {}) {
+ const listing = { pid: -1 };
+ // The listing's own process (powershell / ps) has ended by now: its pid is left out.
+ const pids = descendantPids(listProcesses(platform, (...args) => Object.assign(listing, run(...args))), rootPid).filter((pid) => pid !== listing.pid);
+ if (!pids.length) return pids;
+ if (platform === "win32") {
+ run("taskkill", ["/F", ...pids.flatMap((pid) => ["/PID", String(pid)])], { windowsHide: true, timeout: 10_000 });
+ } else {
+ for (const pid of pids) {
+ try { kill(pid, "SIGKILL"); } catch { /* already gone */ }
+ }
+ }
+ return pids;
+}
+
+/**
+ * Armed once when the quit's teardown starts: after `timeoutMs` the app's
+ * processes are killed and `exit` runs. Returns a disarm (the teardown ended).
+ */
+export function armQuitWatchdog({ timeoutMs = QUIT_WATCHDOG_MS, killAll = () => killDescendants(), exit, log = () => undefined, setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
+ const timer = setTimer(() => {
+ log(`quit did not finish in ${Math.round(timeoutMs / 1000)} s: ending the engine and the app's other processes`);
+ let pids = [];
+ try { pids = killAll(); } catch (error) { log(`killing the app's processes failed: ${error?.message ?? error}`); }
+ log(`killed ${pids.length} process(es)`);
+ exit();
+ }, timeoutMs);
+ timer?.unref?.();
+ return () => clearTimer(timer);
+}
diff --git a/apps/desktop/electron/quit-watchdog.test.mjs b/apps/desktop/electron/quit-watchdog.test.mjs
new file mode 100644
index 00000000..d1df79fb
--- /dev/null
+++ b/apps/desktop/electron/quit-watchdog.test.mjs
@@ -0,0 +1,56 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import test from "node:test";
+
+import { armQuitWatchdog, descendantPids, killDescendants, listProcesses } from "./quit-watchdog.mjs";
+
+test("descendantPids: the whole tree below the app, nothing beside it, no loop on a reused pid", () => {
+ const rows = [
+ { pid: 10, ppid: 1 }, // the app
+ { pid: 11, ppid: 10 }, { pid: 12, ppid: 10 }, // engine, gpu
+ { pid: 13, ppid: 11 }, { pid: 14, ppid: 13 }, // engine's shell and its child
+ { pid: 20, ppid: 1 }, { pid: 21, ppid: 20 }, // someone else's
+ { pid: 10, ppid: 14 }, // a row naming the app as a child again
+ ];
+ assert.deepEqual(descendantPids(rows, 10).sort(), [11, 12, 13, 14]);
+ assert.deepEqual(descendantPids(rows, 99), []);
+});
+
+test("Windows: one taskkill /F for every process below the app, never the listing's own powershell", () => {
+ const calls = [];
+ const run = (command, args) => {
+ calls.push([command, args]);
+ if (command === "powershell.exe") return { pid: 31, stdout: "10 1\r\n11 10\r\n13 11\r\n31 10\r\n40 1\r\n" };
+ return { pid: 32, stdout: "" };
+ };
+ assert.deepEqual(killDescendants({ rootPid: 10, platform: "win32", run }), [11, 13]);
+ assert.deepEqual(calls.at(-1), ["taskkill", ["/F", "/PID", "11", "/PID", "13"]]);
+});
+
+test("the watchdog kills and exits only when the teardown has not finished in time", async () => {
+ const events = [];
+ const disarm = armQuitWatchdog({ timeoutMs: 20, killAll: () => { events.push("kill"); return [1, 2]; }, exit: () => events.push("exit") });
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ assert.deepEqual(events, ["kill", "exit"]);
+ disarm();
+ const quiet = [];
+ const disarmQuiet = armQuitWatchdog({ timeoutMs: 20, killAll: () => { quiet.push("kill"); return []; }, exit: () => quiet.push("exit") });
+ disarmQuiet();
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ assert.deepEqual(quiet, []);
+});
+
+test("a real child tree (the engine and its shell) is killed", { skip: process.platform === "win32" }, async () => {
+ // An "engine" that starts a long-lived child of its own.
+ const engine = spawn(process.execPath, ["-e", "require('node:child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); setInterval(() => {}, 1000)"], { stdio: "ignore" });
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ const before = descendantPids(listProcesses(), process.pid);
+ assert.ok(before.includes(engine.pid), "the engine is listed below this process");
+ assert.ok(before.length >= 2, "and its child too");
+ const exited = new Promise((resolve) => engine.once("exit", (_code, signal) => resolve(signal)));
+ killDescendants();
+ assert.equal(await exited, "SIGKILL");
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ const alive = before.filter((pid) => { try { process.kill(pid, 0); return true; } catch { return false; } });
+ assert.deepEqual(alive, []);
+});
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index ec1b5844..b52d0734 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -27,7 +27,7 @@
"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs",
"pretest": "pnpm --filter @omnirush/headless-threads build",
"test:omnirush-account": "node --test electron/omnirush-account.test.mjs",
- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/prepare-box-helpers.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/browser-task.test.mjs electron/background-rendering.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/window-size.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/build-variant.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/computer-use-gate.test.mjs electron/computer-use-agent-browser.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs electron/app-request-secret.test.mjs electron/disk-cleanup.test.mjs electron/lima-packaging.test.mjs",
+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/prepare-box-helpers.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/browser-task.test.mjs electron/background-rendering.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/window-size.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/build-variant.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/computer-use-gate.test.mjs electron/computer-use-agent-browser.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs electron/app-request-secret.test.mjs electron/disk-cleanup.test.mjs electron/lima-packaging.test.mjs electron/quit-watchdog.test.mjs",
"test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",
"pretest:core": "pnpm --filter @omnirush/headless-threads build"
},