Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: quit guard asks once per turn

ogsamratc713544316e9
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index c67c64be..e16157b5 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -1452,6 +1452,8 @@ const wakeAutomationRunner = (wakeEvent) => {
}
};
powerMonitor.on("resume", () => wakeAutomationRunner("resume"));
+// OS shutdown or logout never waits on the turn guard (a prevented quit would block it).
+powerMonitor.on("shutdown", () => turnGuard.allowQuit());
powerMonitor.on("unlock-screen", () => wakeAutomationRunner("unlock-screen"));
let runtimeDisposedForQuit = false;
@@ -2138,6 +2140,7 @@ const desktopCommandHandlers = {
runtimeManager,
uiControlServer,
removeWindowsBrandShortcut,
+ allowQuit: () => turnGuard.allowQuit(),
}, {
preserveBootstrap: args[0]?.preserveBootstrap !== false,
input: {
@@ -2566,6 +2569,7 @@ if (isDevMode) {
// Best effort — never block the relaunch on a flush failure.
}
setTimeout(() => {
+ turnGuard.allowQuit();
app.relaunch();
// Graceful quit (not app.exit) so before-quit teardown runs and managed
// sidecars are stopped — a hard exit orphans them and they can hold
@@ -2730,8 +2734,9 @@ async function createMainWindow() {
flushPendingDeepLinks();
});
+ // Windows logout or shutdown never waits on the turn guard.
+ mainWindow.on("session-end", () => turnGuard.allowQuit());
// A turn still running: ask before the window goes (turn-guard.mjs).
- turnGuard.reset();
mainWindow.on("close", (event) => {
const win = mainWindow;
turnGuard.guardClose(event, () => {
@@ -2758,6 +2763,8 @@ async function createMainWindow() {
},
});
mainWindow.webContents.on("render-process-gone", (_event, details) => {
+ // The renderer that said a turn runs is gone; a reload says it again.
+ turnGuard.setTurnRunning(false);
recoverRendererCrash(details);
});
@@ -2847,6 +2854,7 @@ ipcMain.handle("omnirush:update-gate:refresh", async () => {
setInterval(readProfile, 30 * 60_000).unref?.();
}
ipcMain.handle("omnirush:shell:relaunch", async () => {
+ turnGuard.allowQuit();
app.relaunch();
app.quit();
});
@@ -2934,6 +2942,7 @@ registerMigrationIpc({ app, ipcMain });
const { ensureAutoUpdater, prepareInstallOnQuit } = registerUpdaterIpc({
app,
ipcMain,
+ allowQuit: () => turnGuard.allowQuit(),
getMainWindow: () => mainWindow,
// All distributions intentionally share one application identifier, so they also
// share Squirrel's ShipIt domain. Keep the shared default rather than
diff --git a/apps/desktop/electron/nuke.mjs b/apps/desktop/electron/nuke.mjs
index 7e334c29..cd0e51f6 100644
--- a/apps/desktop/electron/nuke.mjs
+++ b/apps/desktop/electron/nuke.mjs
@@ -794,7 +794,7 @@ export async function runPendingNukeCleanup(input, options = {}) {
}
/** @returns {Promise<import("@omnirush/types/desktop-ipc").NukeReceipt>} */
-export async function executeNukeFreshStart({ app, session, runtimeManager, uiControlServer, removeWindowsBrandShortcut }, options = {}) {
+export async function executeNukeFreshStart({ app, session, runtimeManager, uiControlServer, removeWindowsBrandShortcut, allowQuit = () => {} }, options = {}) {
const input = {
...(options.input ?? {
env: process.env,
@@ -852,6 +852,7 @@ export async function executeNukeFreshStart({ app, session, runtimeManager, uiCo
});
setTimeout(() => {
+ allowQuit();
if (!workerScheduled) app.relaunch();
app.quit();
}, 100);
diff --git a/apps/desktop/electron/turn-guard.mjs b/apps/desktop/electron/turn-guard.mjs
index b59c7b15..08d670ae 100644
--- a/apps/desktop/electron/turn-guard.mjs
+++ b/apps/desktop/electron/turn-guard.mjs
@@ -2,12 +2,56 @@
// running (`__setTurnRunning`); closing the window or quitting the app while
// one runs asks first, because a cut-off last turn keeps the session from
// counting as a Good session ★. "Wait for it" is the default (and Escape);
-// "Quit anyway" goes ahead.
+// "Quit anyway" goes ahead. A second close or quit request, while the dialog
+// is up or after "Wait for it" in the same turn, quits without asking; the
+// guard re-arms when the turn ends. OS shutdown, updater installs and
+// relaunches call `allowQuit()` first and are never asked.
+//
+// `createQuitGuard` is the CLI's and the renderer's state machine
+// (apps/app/src/app/lib/good-session.ts, the CLI's good-session-lib.js).
export const TURN_GUARD_TITLE = "A turn is still running.";
export const TURN_GUARD_DETAIL = "Quit now and this session won't count as a Good session ★.";
export const TURN_GUARD_BUTTONS = Object.freeze(["Wait for it", "Quit anyway"]);
-const QUIT_ANYWAY = 1;
+const WAIT = 0;
+
+/**
+ * `request({ running, interactive, hangup })` answers "quit" (go ahead) or
+ * "ask" (show TURN_GUARD_MESSAGE with "Wait for it" / "Quit anyway"). The
+ * first quit request while a turn runs asks; a second one, whatever the
+ * answer, quits. `answer(wait)` takes the user's choice; `turnEnded()`
+ * re-arms the guard for the next turn and says whether the user was waiting.
+ * Headless runs and a closed terminal (hangup) never ask.
+ */
+export function createQuitGuard() {
+ let state = "idle"; // idle | asking | waiting
+ return {
+ get state() {
+ return state;
+ },
+ request({ running = false, interactive = true, hangup = false } = {}) {
+ if (!interactive || hangup || !running) return "quit";
+ if (state === "idle") {
+ state = "asking";
+ return "ask";
+ }
+ return "quit";
+ },
+ answer(wait) {
+ if (state !== "asking") return wait ? "wait" : "quit";
+ if (wait) {
+ state = "waiting";
+ return "wait";
+ }
+ return "quit";
+ },
+ turnEnded() {
+ const was = state;
+ state = "idle";
+ return was === "waiting" || was === "asking";
+ },
+ };
+}
/**
* @param {{
@@ -17,72 +61,83 @@ const QUIT_ANYWAY = 1;
* }} deps
*/
export function createTurnGuard(deps) {
+ const guard = createQuitGuard();
let turnRunning = false;
- let quitConfirmed = false;
- /** @type {Promise<boolean> | null} */
- let asking = null;
+ let allowed = false;
+ /** @type {AbortController | null} */
+ let open = null;
+
+ function closeDialog() {
+ if (!open) return;
+ const controller = open;
+ open = null;
+ controller.abort();
+ }
- async function confirmLeave() {
- if (!turnRunning || quitConfirmed) return true;
- // A second close or quit while the dialog is open waits for the same answer.
- asking ??= deps.showMessageBox(deps.getWindow() ?? null, {
+ /**
+ * One close or quit request. Returns true when it may go on now; otherwise
+ * it has prevented the event and calls `proceed` once the user picks
+ * "Quit anyway".
+ */
+ function decide(event, proceed) {
+ if (allowed) return true;
+ if (guard.request({ running: turnRunning }) === "quit") {
+ // The second request: it quits, and the open dialog goes with it.
+ closeDialog();
+ return true;
+ }
+ event.preventDefault();
+ const controller = new AbortController();
+ open = controller;
+ void deps.showMessageBox(deps.getWindow() ?? null, {
type: "warning",
title: deps.appName ?? "OmniRush.ai",
message: TURN_GUARD_TITLE,
detail: TURN_GUARD_DETAIL,
buttons: [...TURN_GUARD_BUTTONS],
- defaultId: 0,
- cancelId: 0,
+ defaultId: WAIT,
+ cancelId: WAIT,
noLink: true,
+ signal: controller.signal,
})
- .then((result) => result.response === QUIT_ANYWAY)
- .catch(() => true)
- .finally(() => {
- asking = null;
+ .then((result) => result.response === WAIT)
+ .catch(() => false)
+ .then((wait) => {
+ // Closed by a second request, which already went ahead.
+ if (controller.signal.aborted) return;
+ open = null;
+ if (guard.answer(wait) === "quit") proceed();
});
- return asking;
+ return false;
}
return {
setTurnRunning(value) {
- turnRunning = value === true;
+ const running = value === true;
+ // The turn ended: the next turn asks again. An open dialog stays;
+ // either answer is fine now.
+ if (turnRunning && !running) guard.turnEnded();
+ turnRunning = running;
return turnRunning;
},
isTurnRunning() {
return turnRunning;
},
- /**
- * `before-quit`: returns true when the quit may go on now. Otherwise it
- * has prevented the event and quits again (`quit`) once the user picks
- * "Quit anyway".
- */
+ /** `before-quit`: true when the quit may go on now; `quit` quits again after "Quit anyway". */
guardQuit(event, quit) {
- if (!turnRunning || quitConfirmed) return true;
- event.preventDefault();
- void confirmLeave().then((leave) => {
- if (!leave) return;
- quitConfirmed = true;
- quit();
- });
- return false;
+ return decide(event, quit);
},
- /**
- * The window's `close`: the same question; "Quit anyway" closes it
- * (`close`), which quits the app where closing the last window does.
- */
+ /** The window's `close`: the same question; "Quit anyway" closes it (`close`). */
guardClose(event, close) {
- if (!turnRunning || quitConfirmed) return true;
- event.preventDefault();
- void confirmLeave().then((leave) => {
- if (!leave) return;
- quitConfirmed = true;
- close();
- });
- return false;
+ return decide(event, close);
+ },
+ /** OS shutdown or logout, an updater install, a relaunch, a reset: never ask again. */
+ allowQuit() {
+ allowed = true;
+ closeDialog();
},
- /** A window opened again (macOS keeps the app running): ask next time too. */
- reset() {
- quitConfirmed = false;
+ get state() {
+ return guard.state;
},
};
}
diff --git a/apps/desktop/electron/turn-guard.test.mjs b/apps/desktop/electron/turn-guard.test.mjs
index 9b37fbf7..c3266957 100644
--- a/apps/desktop/electron/turn-guard.test.mjs
+++ b/apps/desktop/electron/turn-guard.test.mjs
@@ -1,108 +1,155 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { TURN_GUARD_BUTTONS, TURN_GUARD_DETAIL, TURN_GUARD_TITLE, createTurnGuard } from "./turn-guard.mjs";
+import { TURN_GUARD_BUTTONS, TURN_GUARD_DETAIL, TURN_GUARD_TITLE, createQuitGuard, createTurnGuard } from "./turn-guard.mjs";
function fakeEvent() {
return { prevented: false, preventDefault() { this.prevented = true; } };
}
-function setup(responses) {
- const asked = [];
+/** A dialog the test answers: `answer(index)`; an abort resolves it with the cancel button, as Electron does. */
+function setup() {
+ const dialogs = [];
const guard = createTurnGuard({
getWindow: () => /** @type {any} */ ("win"),
- showMessageBox: async (win, options) => {
- asked.push({ win, options });
- return { response: responses.shift() ?? 0 };
- },
+ showMessageBox: (win, options) => new Promise((resolve) => {
+ const dialog = { win, options, answer: (response) => resolve({ response }), aborted: false };
+ options.signal?.addEventListener("abort", () => {
+ dialog.aborted = true;
+ resolve({ response: options.cancelId });
+ });
+ dialogs.push(dialog);
+ }),
});
- return { guard, asked };
+ return { guard, dialogs };
}
const settle = () => new Promise((resolve) => setImmediate(resolve));
test("no turn running: quit and close go ahead without asking", () => {
- const { guard, asked } = setup([]);
+ const { guard, dialogs } = setup();
const event = fakeEvent();
assert.equal(guard.guardQuit(event, () => assert.fail("no re-quit")), true);
assert.equal(guard.guardClose(fakeEvent(), () => assert.fail("no re-close")), true);
assert.equal(event.prevented, false);
- assert.equal(asked.length, 0);
+ assert.equal(dialogs.length, 0);
});
-test("a turn running: quitting asks, with Wait for it as the default", async () => {
- const { guard, asked } = setup([0]);
+test("a turn running: the first quit asks, with Wait for it as the default", async () => {
+ const { guard, dialogs } = setup();
guard.setTurnRunning(true);
const event = fakeEvent();
let quits = 0;
assert.equal(guard.guardQuit(event, () => { quits += 1; }), false);
assert.equal(event.prevented, true);
- await settle();
- assert.equal(asked.length, 1);
- const { options } = asked[0];
+ assert.equal(dialogs.length, 1);
+ const { options } = dialogs[0];
assert.equal(options.message, "A turn is still running.");
assert.equal(options.detail, "Quit now and this session won't count as a Good session ★.");
assert.deepEqual(options.buttons, ["Wait for it", "Quit anyway"]);
assert.equal(options.defaultId, 0);
assert.equal(options.cancelId, 0);
+ dialogs[0].answer(0);
+ await settle();
assert.equal(quits, 0, "Wait for it keeps the app open");
});
-test("Quit anyway quits, and the second before-quit goes through", async () => {
- const { guard, asked } = setup([1]);
+test("quit, Wait for it, quit again: the second quit quits without asking", async () => {
+ const { guard, dialogs } = setup();
guard.setTurnRunning(true);
- let quits = 0;
- guard.guardQuit(fakeEvent(), () => { quits += 1; });
+ guard.guardQuit(fakeEvent(), () => assert.fail("waited"));
+ dialogs[0].answer(0);
await settle();
- assert.equal(quits, 1);
const again = fakeEvent();
- assert.equal(guard.guardQuit(again, () => assert.fail("asked twice")), true);
+ assert.equal(guard.guardQuit(again, () => assert.fail("no dialog")), true);
assert.equal(again.prevented, false);
- assert.equal(asked.length, 1);
+ assert.equal(dialogs.length, 1);
});
-test("closing the window asks the same; Quit anyway closes it and the quit that follows is not asked again", async () => {
- const { guard, asked } = setup([1]);
+test("a second quit while the dialog is open quits and closes the dialog", async () => {
+ const { guard, dialogs } = setup();
+ guard.setTurnRunning(true);
+ let proceeded = 0;
+ guard.guardClose(fakeEvent(), () => { proceeded += 1; });
+ const second = fakeEvent();
+ assert.equal(guard.guardQuit(second, () => assert.fail("no second dialog")), true);
+ assert.equal(second.prevented, false);
+ await settle();
+ assert.equal(dialogs.length, 1);
+ assert.equal(dialogs[0].aborted, true);
+ assert.equal(proceeded, 0, "the first request does not run twice");
+});
+
+test("Quit anyway quits; the quit that follows (close → last window → before-quit) is not asked again", async () => {
+ const { guard, dialogs } = setup();
guard.setTurnRunning(true);
let closes = 0;
- const event = fakeEvent();
- assert.equal(guard.guardClose(event, () => { closes += 1; }), false);
- assert.equal(event.prevented, true);
+ guard.guardClose(fakeEvent(), () => { closes += 1; });
+ dialogs[0].answer(1);
await settle();
assert.equal(closes, 1);
- assert.equal(guard.guardQuit(fakeEvent(), () => assert.fail("asked twice")), true);
- assert.equal(asked.length, 1);
+ assert.equal(guard.guardClose(fakeEvent(), () => assert.fail("asked")), true);
+ assert.equal(guard.guardQuit(fakeEvent(), () => assert.fail("asked")), true);
+ assert.equal(dialogs.length, 1);
});
-test("a close and a quit while the dialog is open share one dialog", async () => {
- const { guard, asked } = setup([0]);
+test("the turn ending re-arms the guard: an aborted quit leaves later turns guarded", async () => {
+ const { guard, dialogs } = setup();
guard.setTurnRunning(true);
- guard.guardClose(fakeEvent(), () => assert.fail("waited"));
- guard.guardQuit(fakeEvent(), () => assert.fail("waited"));
+ guard.guardQuit(fakeEvent(), () => undefined);
+ dialogs[0].answer(0);
await settle();
- assert.equal(asked.length, 1);
+ guard.setTurnRunning(false);
+ assert.equal(guard.guardQuit(fakeEvent(), () => assert.fail("idle")), true, "no turn: quits");
+ guard.setTurnRunning(true);
+ assert.equal(guard.guardQuit(fakeEvent(), () => undefined), false, "the next turn asks again");
+ assert.equal(dialogs.length, 2);
});
-test("the turn finishing while asked: later quits go through; a reopened window asks again", async () => {
- const { guard, asked } = setup([1, 0]);
+test("OS shutdown, updater installs and relaunches (allowQuit) never ask", async () => {
+ const { guard, dialogs } = setup();
guard.setTurnRunning(true);
- guard.guardClose(fakeEvent(), () => undefined);
- await settle();
- guard.reset();
- assert.equal(guard.guardClose(fakeEvent(), () => assert.fail("waited")), false);
+ guard.allowQuit();
+ const event = fakeEvent();
+ assert.equal(guard.guardQuit(event, () => assert.fail("asked")), true);
+ assert.equal(guard.guardClose(fakeEvent(), () => assert.fail("asked")), true);
+ assert.equal(event.prevented, false);
+ assert.equal(dialogs.length, 0);
+});
+
+test("allowQuit while the dialog is open closes it", async () => {
+ const { guard, dialogs } = setup();
+ guard.setTurnRunning(true);
+ guard.guardQuit(fakeEvent(), () => assert.fail("the shutdown quits on its own"));
+ guard.allowQuit();
await settle();
- assert.equal(asked.length, 2);
- guard.setTurnRunning(false);
- assert.equal(guard.guardQuit(fakeEvent(), () => undefined), true);
+ assert.equal(dialogs[0].aborted, true);
});
test("only a strict true marks a turn running", () => {
- const { guard } = setup([]);
+ const { guard } = setup();
assert.equal(guard.setTurnRunning("yes"), false);
assert.equal(guard.setTurnRunning(true), true);
assert.equal(guard.isTurnRunning(), true);
});
+test("createQuitGuard: idle → asking → waiting; any second request quits; turnEnded re-arms", () => {
+ const quit = createQuitGuard();
+ assert.equal(quit.request({ running: false }), "quit");
+ assert.equal(quit.request({ running: true, interactive: false }), "quit");
+ assert.equal(quit.request({ running: true, hangup: true }), "quit");
+ assert.equal(quit.request({ running: true }), "ask");
+ assert.equal(quit.state, "asking");
+ assert.equal(quit.request({ running: true }), "quit", "a second request while asking");
+ assert.equal(quit.answer(true), "wait");
+ assert.equal(quit.state, "waiting");
+ assert.equal(quit.request({ running: true }), "quit", "a second request after Wait for it");
+ assert.equal(quit.turnEnded(), true);
+ assert.equal(quit.state, "idle");
+ assert.equal(quit.request({ running: true }), "ask");
+ assert.equal(quit.answer(false), "quit");
+});
+
test("constants", () => {
assert.equal(TURN_GUARD_TITLE, "A turn is still running.");
assert.match(TURN_GUARD_DETAIL, /Good session ★/);
diff --git a/apps/desktop/electron/updater.mjs b/apps/desktop/electron/updater.mjs
index f16557e6..c766936b 100644
--- a/apps/desktop/electron/updater.mjs
+++ b/apps/desktop/electron/updater.mjs
@@ -492,6 +492,8 @@ export function preventPendingUpdaterInstall(updater) {
export function registerUpdaterIpc({
app,
ipcMain,
+ // Called before the updater quits or restarts the app (the turn guard lets it through).
+ allowQuit = () => {},
getMainWindow,
loadAutoUpdater = () => import("electron-updater"),
manifestChannel = "latest",
@@ -524,6 +526,10 @@ export function registerUpdaterIpc({
relaunchAppImage = relaunchAppImageAfterExit,
restartDelayMs = 300,
}) {
+ const quitApp = () => {
+ allowQuit();
+ app.quit();
+ };
const feedOptions = updaterFeedOptions({
manifestChannel,
alphaFeedUrl,
@@ -713,7 +719,7 @@ export function registerUpdaterIpc({
// update; quitAndInstall reports a descriptive failure if it is gone.
console.warn("[updater] error", err);
// A failed quit-time install must not leave the app running.
- if (quitInstallInProgress) app.quit();
+ if (quitInstallInProgress) quitApp();
});
autoUpdaterInstance.on("update-downloaded", (info) => {
updateDownloaded = true;
@@ -989,6 +995,7 @@ export function registerUpdaterIpc({
updater.autoInstallOnAppQuit = true;
await updater.downloadUpdate();
installTriggered = true;
+ allowQuit();
updater.quitAndInstall(false, true);
return { ok: true, action: "install" };
} catch (error) {
@@ -1288,7 +1295,7 @@ export function registerUpdaterIpc({
installTriggered = true;
void selfInstall(installMode, { relaunch: false })
.catch((error) => console.warn("[updater] install on quit failed", error?.message ?? error))
- .finally(() => app.quit());
+ .finally(() => quitApp());
};
}
return () => {
@@ -1296,12 +1303,13 @@ export function registerUpdaterIpc({
quitInstallInProgress = true;
// Quit means quit: install silently without relaunching.
updater.autoRunAppAfterInstall = false;
- setTimeout(() => app.quit(), quitInstallFallbackMs);
+ setTimeout(() => quitApp(), quitInstallFallbackMs);
try {
+ allowQuit();
updater.quitAndInstall(true, false);
} catch (error) {
console.warn("[updater] install on quit failed", error?.message ?? error);
- app.quit();
+ quitApp();
}
};
} catch (error) {
@@ -1390,7 +1398,7 @@ export function registerUpdaterIpc({
}
installTriggered = true;
// Let the renderer show "Restarting…" before the window goes away.
- setTimeout(() => app.quit(), restartDelayMs);
+ setTimeout(() => quitApp(), restartDelayMs);
return { ok: true, mode: "in-place" };
}
if (installMode === "manual-dmg") {
@@ -1407,7 +1415,7 @@ export function registerUpdaterIpc({
if (openError) return { ok: false, reason: openError };
// Let the renderer show its instructions and Finder mount the image
// before this copy quits; the user replaces it from the DMG.
- setTimeout(() => app.quit(), quitDelayMs);
+ setTimeout(() => quitApp(), quitDelayMs);
return { ok: true, mode: "manual-dmg", path: downloadedInstallerPath };
} catch (error) {
return { ok: false, reason: String(error?.message ?? error) };
@@ -1418,6 +1426,7 @@ export function registerUpdaterIpc({
// defaults domain may have been wiped when stale state was cleaned.
await enableSquirrelDirectContentsWrite();
installTriggered = true;
+ allowQuit();
updater.quitAndInstall(false, true);
return { ok: true, mode: "in-place" };
} catch (error) {