Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(desktop): keep scheduled runner alive when quit is cancelled

zszz34aee6d9df981
diff --git a/apps/desktop/electron/main/bootstrap/confirmed-quit.ts b/apps/desktop/electron/main/bootstrap/confirmed-quit.ts
new file mode 100644
index 000000000..4bfc28ee2
--- /dev/null
+++ b/apps/desktop/electron/main/bootstrap/confirmed-quit.ts
@@ -0,0 +1,53 @@
+import type { Logger } from "../logger";
+
+/**
+ * Teardown for long-lived main-process services that must outlive a
+ * cancelled quit.
+ *
+ * `before-quit` is not a shutdown signal: the shutdown handler prevents the
+ * first one to ask for confirmation, and the user can cancel, after which the
+ * app keeps running. A service that stopped itself from its own `before-quit`
+ * listener would then stay stopped for the rest of the process lifetime
+ * (issue #2048: the scheduled-task runner went silent until a restart).
+ * Services register here instead; the shutdown handler runs the listeners
+ * once the quit is committed.
+ */
+const listeners = new Set<() => void>();
+let ran = false;
+
+/** Register teardown for a committed quit. Returns an unregister function. */
+export function onConfirmedQuit(listener: () => void): () => void {
+ if (ran) {
+ listener();
+ return () => undefined;
+ }
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/**
+ * Run every registered teardown exactly once. Called by the shutdown handler
+ * after the quit can no longer be cancelled. A failing listener is reported
+ * and does not keep the remaining services alive.
+ */
+export function runConfirmedQuitTeardown(logger: Pick<Logger, "app">): void {
+ if (ran) return;
+ ran = true;
+ const pending = [...listeners];
+ listeners.clear();
+ for (const listener of pending) {
+ try {
+ listener();
+ } catch (error) {
+ logger.app("lifecycle", "warn", "quit teardown failed", { data: String(error) });
+ }
+ }
+}
+
+/** Test seam: forget registrations and the committed state between cases. */
+export function resetConfirmedQuitForTests(): void {
+ listeners.clear();
+ ran = false;
+}
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.ts
index c7f6e2a6d..a72180e1c 100644
--- a/apps/desktop/electron/main/bootstrap/shutdown.ts
+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts
@@ -15,6 +15,7 @@ import type { UserMcpRuntime } from "../user-mcp";
import type { McpControlServer } from "../mcp-control";
import type { McpOAuthManager } from "../mcp-oauth";
import { getActiveRemoteHostsBoot, setActiveRemoteHostsBoot } from "./remote-hosts";
+import { runConfirmedQuitTeardown } from "./confirmed-quit";
import type { LiveCallService } from "../live-voice/call-service";
const QUIT_TURN_SETTLE_BUDGET_MS = 2_000;
@@ -144,6 +145,9 @@ export function registerShutdownHandlers({
// Persist the confirmed shutdown before any awaited cleanup so a forced
// process termination still leaves an observable lifecycle boundary.
logger.app("lifecycle", "info", "app shutdown");
+ // The quit can no longer be cancelled; services that must survive a
+ // cancelled confirmation stop only from here (issue #2048).
+ runConfirmedQuitTeardown(logger);
disposePowerSaveBlockers();
state.tray?.destroy();
state.tray = null;
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index 4981e0091..15950a8a3 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -1,5 +1,6 @@
import { app, BrowserWindow, crashReporter, Menu, safeStorage } from "electron";
import { createScheduledRunner } from "../runtime/scheduled-runner";
+import { onConfirmedQuit } from "./confirmed-quit";
import {
APP_NAME,
APP_VERSION,
@@ -308,7 +309,14 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
report: (error) => logger.app("runtime", "warn", "scheduled task dispatch failed", { data: String(error) }),
});
scheduledRunner.start();
- app.once("before-quit", () => scheduledRunner.stop());
+ logger.app("runtime", "info", "scheduled runner started");
+ // Stop only on a committed quit: a cancelled quit confirmation keeps the
+ // app running, and a runner stopped from `before-quit` would stay silent
+ // until restart (issue #2048).
+ onConfirmedQuit(() => {
+ scheduledRunner.stop();
+ logger.app("runtime", "info", "scheduled runner stopped", { data: "app-quit" });
+ });
if (!bootError && state.agentHostBridge) {
// Restore the persisted turn queue now that host-core answers. Restored
// entries stay held until a controller attaches (D375).
diff --git a/apps/desktop/electron/main/voice-service.ts b/apps/desktop/electron/main/voice-service.ts
index 2ae68c492..fd91f43bb 100644
--- a/apps/desktop/electron/main/voice-service.ts
+++ b/apps/desktop/electron/main/voice-service.ts
@@ -5,8 +5,9 @@
* means zero import overhead at startup.
*/
-import { app, BrowserWindow } from "electron";
+import { BrowserWindow } from "electron";
import { randomUUID } from "node:crypto";
+import { onConfirmedQuit } from "./bootstrap/confirmed-quit";
import { PvRecorderBackend, checkMicrophonePermission, requestMicrophonePermission } from "./audio-backend";
import type {
AudioCaptureFactory,
@@ -254,6 +255,8 @@ export function createVoiceService(
acquireMicrophoneLease?: (token: string) => () => void,
): VoiceService {
const service = new VoiceService(modelCacheDir, getWindow, acquireMicrophoneLease);
- app.once("before-quit", () => service.dispose());
+ // A cancelled quit keeps the app running, so disposal waits for a committed
+ // quit instead of the cancellable `before-quit`.
+ onConfirmedQuit(() => service.dispose());
return service;
}
diff --git a/apps/desktop/test/confirmed-quit-teardown.test.mjs b/apps/desktop/test/confirmed-quit-teardown.test.mjs
new file mode 100644
index 000000000..a6e821486
--- /dev/null
+++ b/apps/desktop/test/confirmed-quit-teardown.test.mjs
@@ -0,0 +1,134 @@
+import assert from "node:assert/strict";
+import { readdir, readFile } from "node:fs/promises";
+import { register, registerHooks } from "node:module";
+import { join, relative } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+// Only Electron is replaced; the quit handler, the confirmed-quit registry and
+// the scheduled runner use their production code. `app.quit()` re-enters
+// `before-quit` the way Electron does.
+registerHooks({
+ resolve(specifier, context, next) {
+ if (specifier === "electron") return { url: "test:electron", shortCircuit: true };
+ return next(specifier, context);
+ },
+ load(url, context, next) {
+ if (url === "test:electron") return {
+ format: "module", shortCircuit: true,
+ source: `import { EventEmitter } from "node:events";
+ export const app = new EventEmitter();
+ app.quit = () => { app.emit("before-quit", { preventDefault() {} }); };
+ export const globalShortcut = { unregister() {} };`,
+ };
+ return next(url, context);
+ },
+});
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const { app } = await import("electron");
+const { registerShutdownHandlers } = await import("../electron/main/bootstrap/shutdown.ts");
+const { onConfirmedQuit, resetConfirmedQuitForTests } = await import(
+ "../electron/main/bootstrap/confirmed-quit.ts"
+);
+const { createScheduledRunner } = await import("../electron/main/runtime/scheduled-runner.ts");
+
+const settle = () => new Promise((resolve) => setImmediate(resolve));
+
+function installQuitHandler(answers) {
+ const state = {
+ shutdownComplete: false, shutdownPromise: null, quitting: false,
+ quitConfirmed: false, closeBehavior: "tray", tray: null,
+ pluginLauncherAccelerator: null, toggleWindowAccelerator: null,
+ };
+ const dispose = () => undefined;
+ const warnings = [];
+ registerShutdownHandlers({
+ hasSingleInstanceLock: true, state,
+ getHost: () => null, getSidecar: () => null, getMcpControl: () => null,
+ activeTurns: new Map(),
+ persistenceOutbox: { flush: async () => {} },
+ inflightCheckpointer: { flushAll: async () => {}, dispose },
+ flushEventPersistence: async () => {},
+ pluginPanels: { closeAll: async () => {} },
+ plugins: { disposeAll: async () => {} }, userMcp: { disposeAll: dispose },
+ browserHost: { dispose }, pluginViews: { dispose: async () => {} },
+ updater: { dispose, isInstallingUpdate: () => false },
+ logger: { app: (_area, level, event) => { if (level === "warn") warnings.push(event); } },
+ confirmQuitDialog: async () => answers.shift(),
+ disposePowerSaveBlockers: dispose,
+ });
+ return { state, warnings };
+}
+
+test("a cancelled quit keeps scheduled tasks dispatching; a confirmed quit stops them", async (t) => {
+ resetConfirmedQuitForTests();
+ t.after(() => { app.removeAllListeners(); resetConfirmedQuitForTests(); });
+ const { state } = installQuitHandler([false, true]);
+ let duePolls = 0;
+ const host = { async call(method) {
+ assert.equal(method, "scheduled.due");
+ duePolls++;
+ return { ids: [] };
+ } };
+ const runner = createScheduledRunner({ getHost: () => host, execute: async () => {}, report: (error) => { throw error; } });
+ onConfirmedQuit(() => runner.stop());
+
+ await runner.tick();
+ assert.equal(duePolls, 1);
+
+ // Cmd+Q / tray Quit, then "Cancel" in the confirmation dialog.
+ app.quit();
+ await settle();
+ assert.equal(state.quitting, false, "the cancelled quit leaves the app running");
+ await runner.tick();
+ assert.equal(duePolls, 2, "due tasks are still polled after a cancelled quit");
+
+ // The user quits again and confirms.
+ app.quit();
+ await settle();
+ assert.equal(state.quitting, true);
+ await state.shutdownPromise;
+ await runner.tick();
+ assert.equal(duePolls, 2, "a committed quit stops the runner");
+});
+
+test("teardown registered after the quit is committed runs immediately and only once", async (t) => {
+ resetConfirmedQuitForTests();
+ t.after(() => { app.removeAllListeners(); resetConfirmedQuitForTests(); });
+ const { state, warnings } = installQuitHandler([true]);
+ const calls = [];
+ onConfirmedQuit(() => { throw new Error("broken teardown"); });
+ onConfirmedQuit(() => calls.push("early"));
+ const unregistered = onConfirmedQuit(() => calls.push("unregistered"));
+ unregistered();
+ app.quit();
+ await settle();
+ await state.shutdownPromise;
+ onConfirmedQuit(() => calls.push("late"));
+ app.quit();
+ await settle();
+ assert.deepEqual(calls, ["early", "late"]);
+ assert.deepEqual(warnings, ["quit teardown failed"]);
+});
+
+test("main-process services do not tear themselves down from a cancellable before-quit", async () => {
+ // Only the shutdown handler may listen to `before-quit`: it alone knows
+ // whether the quit was cancelled. Services use onConfirmedQuit instead.
+ const root = fileURLToPath(new URL("../electron/main/", import.meta.url));
+ const offenders = [];
+ const visit = async (dir) => {
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) await visit(path);
+ else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {
+ const source = await readFile(path, "utf8");
+ if (/\.(on|once|addListener|prependListener)\(\s*["']before-quit["']/.test(source)) {
+ offenders.push(relative(root, path).replaceAll("\\", "/"));
+ }
+ }
+ }
+ };
+ await visit(root);
+ assert.deepEqual(offenders.sort(), ["bootstrap/shutdown.ts"]);
+});
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index 823540b3f..a4e65cba3 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -272,6 +272,15 @@ path, or an update install still enters the normal shutdown sequence above;
destroying the tray happens during `before-quit` so shutdown cannot be
intercepted by a stale shell affordance.
+`before-quit` alone is not a shutdown signal: the first explicit quit is held
+for the D363 confirmation, and Cancel keeps the app running. Only the shutdown
+handler listens to `before-quit`. Long-lived main-process services that must
+survive a cancelled quit — the scheduled-task runner and the voice service —
+register through `onConfirmedQuit` (`electron/main/bootstrap/confirmed-quit.ts`)
+and stop only once the quit is committed. A service that stopped from its own
+`before-quit` listener stayed stopped after Cancel until the next restart
+(issue #2048).
+
On macOS the app runs under the regular (foreground) activation policy for its
whole lifetime, so it is always listed in the Dock and Cmd+Tab: Main never
transforms the process type, and the always-on-top plugin launcher joins every
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 6f450db4c..5adefab0a 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -18613,6 +18613,11 @@ the latest destination. These assertions measure work counts, not device FPS.
- **Scenario:** Workspace identity.
- **Expected:** Stored workspace bindings use the existing project canonicalization contract on both write and read. On Windows, slash direction, case, trailing separators and extended path prefixes do not hide a task from its own project's conversation. The distinction between missing legacy bindings and explicit null remains unchanged. Foreign-project tools cannot list or mutate bound tasks.
- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-paths.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.
+### E2E-SCHEDULED-cancelled-quit-keeps-runner
+
+- **Scenario:** Cancelled quit and automatic runs (issue #2048, D363).
+- **Expected:** An explicit quit that the user cancels in the quit confirmation leaves the app running with no `app shutdown` lifecycle entry and no scheduled-runner stop. A task that becomes due afterwards still runs automatically, and its `nextRunAt` advances. A later quit prompts again; Confirm runs the ordered shutdown, the process exits with code 0, and the runtime log records `scheduled runner stopped` exactly once. Only the shutdown handler listens to `before-quit`; services that must survive a cancelled quit stop through `onConfirmedQuit`.
+- **Automation:** `pnpm test:e2e:scheduled-quit-cancel` (`scripts/e2e-scheduled-quit-cancel.mjs`) drives the built desktop, preload, real Host SQLite and agent sidecar over CDP in an isolated profile, clicking the in-app confirmation with real pointer input. Only the model is a local SSE fixture; the due instant is set through `configJson.nextRunAt` instead of waiting for the wall clock. Requires `apps/desktop/out` and a host-core debug binary.
### E2E-MARKDOWN-table-actions
diff --git a/package.json b/package.json
index e579253ae..1a848febc 100644
--- a/package.json
+++ b/package.json
@@ -27,6 +27,7 @@
"test:e2e:worktree-live": "node scripts/e2e-worktree-live.mjs",
"test:e2e:question-notification": "node scripts/e2e-question-notification.mjs",
"test:e2e:scheduled": "node scripts/e2e-scheduled.mjs",
+ "test:e2e:scheduled-quit-cancel": "node scripts/e2e-scheduled-quit-cancel.mjs",
"test:e2e:keep-awake": "node scripts/e2e-keep-awake.mjs",
"test:e2e:live-voice": "node scripts/e2e-live-voice.mjs",
"test:e2e:rpc-unicode": "node scripts/e2e-rpc-unicode.mjs",
diff --git a/scripts/e2e-scheduled-quit-cancel.mjs b/scripts/e2e-scheduled-quit-cancel.mjs
new file mode 100644
index 000000000..d43ef39ad
--- /dev/null
+++ b/scripts/e2e-scheduled-quit-cancel.mjs
@@ -0,0 +1,216 @@
+#!/usr/bin/env node
+// E2E-SCHEDULED-cancelled-quit-keeps-runner (issue #2048).
+// Real desktop, preload, Host SQLite and agent sidecar; only the model is a local SSE.
+// A quit that the user cancels in the D363 confirmation must leave automatic
+// scheduled runs working; only the confirmed quit stops the runner.
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createServer } from "node:http";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { once } from "node:events";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+import { waitFor } from "./e2e/wait.mjs";
+
+const root = mkdtempSync(join(tmpdir(), "pi-scheduled-quit-cancel-e2e-"));
+const dataDir = join(root, "data");
+const project = join(root, "project");
+const home = join(root, "home");
+mkdirSync(project);
+mkdirSync(home);
+
+let modelCalls = 0;
+const server = createServer(async (req, res) => {
+ if (req.method === "GET" && req.url?.endsWith("/models")) {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ object: "list", data: [{ id: "fixture", object: "model" }] }));
+ return;
+ }
+ for await (const _ of req);
+ modelCalls++;
+ const chunk = (delta, finish_reason = null) =>
+ res.write(`data: ${JSON.stringify({
+ id: `quit-cancel-${modelCalls}`, object: "chat.completion.chunk", created: 1, model: "fixture",
+ choices: [{ index: 0, delta, finish_reason }],
+ })}\n\n`);
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ chunk({ role: "assistant" });
+ chunk({ content: "Scheduled run after cancelled quit." });
+ chunk({}, "stop");
+ res.end("data: [DONE]\n\n");
+});
+server.listen(0, "127.0.0.1");
+await once(server, "listening");
+
+const host = new Host(resolveHostBinary(), dataDir, { env: { HOME: home, USERPROFILE: home } });
+await host.start();
+await host.call("workspace.set", { path: project });
+const { provider } = await host.call("providers.create", {
+ name: "Quit cancel model", vendorKey: "custom", type: "openai_compatible",
+ protocol: "openai_compatible", baseUrl: `http://127.0.0.1:${server.address().port}/v1`,
+ authKind: "none", defaultModelId: "fixture", apiStyle: "chat_completions",
+});
+await host.call("settings.set", {
+ ...(await host.call("settings.get")),
+ language: "en", onboardingDismissed: true, autoGenerateTitle: false,
+ defaultProviderId: provider.id, defaultModelId: "fixture",
+ defaultMode: "agent", defaultPermissionMode: "auto",
+});
+await host.stop();
+
+const { appDir, electronBinary } = resolveElectronBinary();
+const env = {
+ ...process.env, HOME: home, USERPROFILE: home, PI_DESKTOP_DATA_DIR: dataDir,
+ PI_DESKTOP_START_MAXIMIZED: "0", ELECTRON_RENDERER_URL: "",
+};
+delete env.ELECTRON_RUN_AS_NODE;
+delete env.PI_DESKTOP_BOOT_PROBE;
+const child = spawn(
+ electronBinary,
+ // An ephemeral DevTools port: a fixed one could attach this run to another
+ // desktop instance that still holds it.
+ ["--remote-debugging-port=0", `--user-data-dir=${join(root, "profile")}`, "."],
+ { cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"] },
+);
+let output = "";
+child.stdout.on("data", (data) => { output += data; });
+child.stderr.on("data", (data) => { output += data; });
+const exited = once(child, "exit");
+const devtoolsOrigin = () => output.match(/DevTools listening on ws:\/\/(127\.0\.0\.1:\d+)\//)?.[1];
+
+const logLines = (category) => {
+ const lines = [];
+ const walk = (dir) => {
+ if (!existsSync(dir)) return;
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) walk(path);
+ else if (entry.name.startsWith(`${category}.`) && entry.name.endsWith(".log"))
+ lines.push(...readFileSync(path, "utf8").split("\n").filter(Boolean));
+ }
+ };
+ walk(join(dataDir, "logs"));
+ return lines;
+};
+const countLog = (category, text) => logLines(category).filter((line) => line.includes(text)).length;
+
+let ws;
+try {
+ let target;
+ await waitFor(async () => {
+ const origin = devtoolsOrigin();
+ if (!origin) return false;
+ try {
+ target = (await (await fetch(`http://${origin}/json/list`)).json()).find(
+ (entry) => entry.type === "page" && entry.url.includes("index.html") && !entry.url.includes("plugin-launcher"),
+ );
+ return !!target;
+ } catch {
+ return false;
+ }
+ }, 30_000, "desktop CDP target");
+ ws = new WebSocket(target.webSocketDebuggerUrl);
+ await once(ws, "open");
+ let sequence = 0;
+ const pending = new Map();
+ ws.onmessage = ({ data }) => {
+ const message = JSON.parse(data), entry = pending.get(message.id);
+ if (!entry) return;
+ pending.delete(message.id);
+ if (message.error) entry.reject(new Error(JSON.stringify(message.error)));
+ else entry.resolve(message.result);
+ };
+ ws.onclose = () => {
+ for (const entry of pending.values()) entry.reject(new Error("CDP closed"));
+ pending.clear();
+ };
+ const send = (method, params = {}) => new Promise((resolveCall, reject) => {
+ const id = ++sequence;
+ pending.set(id, { resolve: resolveCall, reject });
+ ws.send(JSON.stringify({ id, method, params }));
+ });
+ const evaluate = async (expression) => {
+ const result = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
+ if (result.exceptionDetails)
+ throw new Error(result.exceptionDetails.exception?.description ?? JSON.stringify(result.exceptionDetails));
+ return result.result.value;
+ };
+ const invoke = (name, ...args) => evaluate(
+ `(async () => { const r = await window.piDesktop.invoke(window.piDesktop.channels.invoke[${JSON.stringify(name)}], ...${JSON.stringify(args)}); if (!r.ok) throw new Error(JSON.stringify(r.error)); return r.data; })()`,
+ );
+ const dialogOpen = () => evaluate(`!!document.querySelector('.lifecycle-confirmation-dialog')`);
+ // Real pointer input on the dialog button, the same hit-test a user click gets.
+ const clickDialogButton = async (label) => {
+ const point = await evaluate(`(() => { const b = [...document.querySelectorAll('.lifecycle-confirmation-dialog button')].find(e => e.textContent.trim() === ${JSON.stringify(label)}); if (!b) return null; const r = b.getBoundingClientRect(), x = r.x + r.width / 2, y = r.y + r.height / 2; return b.contains(document.elementFromPoint(x, y)) ? { x, y } : null; })()`);
+ assert.ok(point, `dialog button hit target: ${label}`);
+ await send("Input.dispatchMouseEvent", { type: "mousePressed", ...point, button: "left", clickCount: 1 });
+ await send("Input.dispatchMouseEvent", { type: "mouseReleased", ...point, button: "left", clickCount: 1 });
+ };
+ const requestQuit = async () => {
+ await invoke("appQuit");
+ await waitFor(dialogOpen, 10_000, "quit confirmation dialog");
+ };
+
+ await waitFor(() => evaluate(`!!document.querySelector('.app-shell:not(.app-shell-boot)')`), 60_000, "desktop shell");
+ await waitFor(() => countLog("runtime", "scheduled runner started") === 1, 10_000, "runner start log");
+ console.log("PASS desktop booted and the scheduled runner logged its start");
+
+ const { task } = await invoke("scheduledCreate", {
+ title: "Quit cancel probe", prompt: "Reply OK", cadence: "hourly",
+ schedule: { hour: 0, minute: 0, weekday: 0 }, permissionMode: "auto",
+ });
+
+ // 1) Explicit quit, then Cancel: the app keeps running.
+ await requestQuit();
+ await clickDialogButton("Cancel");
+ await waitFor(async () => !(await dialogOpen()), 5_000, "dialog dismissed after Cancel");
+ assert.equal(child.exitCode, null, "app still running after Cancel");
+ assert.equal(countLog("lifecycle", "app shutdown"), 0, "Cancel does not enter shutdown");
+ assert.equal(countLog("runtime", "scheduled runner stopped"), 0, "Cancel does not stop the runner");
+ console.log("PASS cancelled quit keeps the app running without a shutdown or runner stop");
+
+ // 2) A task that becomes due after the cancelled quit still runs automatically.
+ // The runner polls every 30s; the due instant is controlled, not waited for.
+ await invoke("scheduledUpdate", { id: task.id, configJson: { nextRunAt: Date.now() } });
+ const callsBefore = modelCalls;
+ let runs = [];
+ await waitFor(async () => {
+ runs = (await invoke("scheduledListRuns", { taskId: task.id })).runs;
+ return runs[0]?.status === "completed";
+ }, 75_000, "automatic run after cancelled quit", 500);
+ assert.equal(runs.length, 1, "exactly one automatic run");
+ assert.ok(modelCalls > callsBefore, "the automatic run reached the model");
+ assert.ok(Date.parse((await invoke("scheduledList")).tasks.find((t) => t.id === task.id).nextRunAt) > Date.now(),
+ "nextRunAt advanced past now");
+ console.log("PASS task due after the cancelled quit ran automatically and nextRunAt advanced");
+
+ // 3) A second quit prompts again; Confirm runs the ordered shutdown and stops the runner.
+ await requestQuit();
+ await clickDialogButton("Quit");
+ const [code] = await Promise.race([
+ exited,
+ new Promise((_, reject) => setTimeout(() => reject(new Error("app did not exit after Confirm")), 30_000)),
+ ]);
+ assert.equal(code, 0, "confirmed quit exits cleanly");
+ assert.equal(countLog("lifecycle", "app shutdown"), 1, "one ordered shutdown");
+ assert.equal(countLog("runtime", "scheduled runner stopped"), 1, "runner stopped on the confirmed quit");
+ assert.equal(countLog("runtime", "quit teardown failed"), 0, "no teardown listener failed");
+ console.log("PASS second quit prompts again; Confirm shuts down and stops the runner once");
+ console.log(`Isolated profile: ${root}`);
+} catch (error) {
+ console.error(output.slice(-4000));
+ console.error(`Isolated profile kept for diagnosis: ${root}`);
+ throw error;
+} finally {
+ ws?.close();
+ // SIGTERM reaches `before-quit`, which holds the quit for the confirmation
+ // dialog, so a failed run would otherwise leave the app (and its host-core)
+ // running. Kill it outright once the graceful path is no longer expected.
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill("SIGKILL");
+ await exited;
+ }
+ server.close();
+}