Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(desktop): wait for daemon shutdown before quitting (MUL-8290) (#9590)

SUBARUAWA486b20cea33ad1a
diff --git a/apps/desktop/src/main/daemon-manager-quit.test.ts b/apps/desktop/src/main/daemon-manager-quit.test.ts
new file mode 100644
index 0000000000..4082612787
--- /dev/null
+++ b/apps/desktop/src/main/daemon-manager-quit.test.ts
@@ -0,0 +1,354 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const context = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ beforeQuit: null as null | ((event: { preventDefault: () => void }) => void),
+ quit: vi.fn(), emit: vi.fn(), dialog: vi.fn(), exec: vi.fn(), health: vi.fn(), readPort: vi.fn(), exists: vi.fn(), install: vi.fn(),
+ pid: null as number | null,
+ autoStart: false, autoStop: true, locale: "en", holdStart: false,
+ windows: [] as Array<{
+ isDestroyed: () => boolean; isVisible: () => boolean;
+ hide: () => void; show: () => void;
+ }>,
+ finishStart: null as null | (() => void),
+ finishStop: null as null | ((error?: Error) => void),
+}));
+vi.mock("electron", () => ({
+ app: {
+ getAppPath: () => "/test/desktop", getPreferredSystemLanguages: () => [context.locale],
+ on: (_event: string, handler: (event: { preventDefault: () => void }) => void) => { context.beforeQuit = handler; },
+ quit: context.quit, emit: context.emit,
+ },
+ dialog: { showMessageBox: context.dialog },
+ BrowserWindow: { getAllWindows: () => context.windows },
+ ipcMain: {
+ handle: (name: string, handler: (...args: unknown[]) => unknown) => { context.handlers.set(name, handler); },
+ on: vi.fn(),
+ },
+}));
+vi.mock("child_process", () => ({ execFile: context.exec }));
+vi.mock("fs", async (original) => ({ ...await original<typeof import("fs")>(), existsSync: context.exists }));
+vi.mock("fs/promises", async (original) => ({
+ ...await original<typeof import("fs/promises")>(),
+ readFile: vi.fn(async (path: string) => {
+ if (path.endsWith("daemon.pid")) {
+ if (context.pid !== null) return String(context.pid);
+ throw Object.assign(new Error("No PID file"), { code: "ENOENT" });
+ }
+ return path.endsWith("desktop_prefs.json")
+ ? JSON.stringify({ autoStart: context.autoStart, autoStop: context.autoStop })
+ : JSON.stringify({ server_url: "https://example.test" });
+ }),
+ writeFile: vi.fn(), mkdir: vi.fn(),
+}));
+vi.mock("./cli-bootstrap", () => ({ ensureManagedCli: context.install, managedCliPath: () => "/test/managed/multica" }));
+vi.mock("./daemon-port", () => ({ probeProfileHealth: context.health, readDaemonPortRecord: context.readPort }));
+
+async function setup() {
+ const { setupDaemonManager } = await import("./daemon-manager");
+ setupDaemonManager(() => null);
+ await context.handlers.get("daemon:set-target-api-url")!({}, "https://example.test");
+ await context.handlers.get("daemon:is-cli-installed")!({});
+ context.exec.mockClear();
+}
+async function setupInstallingCLI() {
+ context.exists.mockReturnValue(false);
+ context.health.mockResolvedValue(null);
+ context.install.mockReturnValue(new Promise(() => {}));
+ const { setupDaemonManager } = await import("./daemon-manager");
+ setupDaemonManager(() => null);
+ await context.handlers.get("daemon:set-target-api-url")!({}, "https://example.test");
+}
+function requestQuit() {
+ const event = { preventDefault: vi.fn() };
+ context.beforeQuit!(event);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+}
+
+function addWindow(initiallyVisible = true) {
+ let visible = initiallyVisible;
+ const window = {
+ isDestroyed: vi.fn(() => false), isVisible: () => visible,
+ hide: vi.fn(() => { visible = false; }),
+ show: vi.fn(() => { visible = true; }),
+ };
+ context.windows.push(window);
+ return window;
+}
+
+describe("desktop quit uses the CLI lifecycle", () => {
+ beforeEach(() => {
+ vi.resetModules(); vi.clearAllMocks(); vi.useFakeTimers(); context.handlers.clear();
+ context.autoStart = false; context.autoStop = true; context.locale = "en"; context.holdStart = false;
+ context.windows = [];
+ context.pid = null; context.readPort.mockResolvedValue(null);
+ context.exists.mockReturnValue(true); context.install.mockReset();
+ context.finishStart = null; context.finishStop = null;
+ context.health.mockResolvedValue({ status: "running", active_task_count: 1 });
+ context.dialog.mockReset().mockResolvedValue({ response: 1 });
+ context.exec.mockImplementation((_bin: string, args: string[], _options: unknown, callback: (error: Error | null, output?: string) => void) => {
+ if (args[0] === "version") callback(null, '{"version":"test"}');
+ else if (args[1] === "start" && context.holdStart) context.finishStart = () => callback(null);
+ else if (args[1] === "stop") context.finishStop = (error) => callback(error ?? null);
+ else callback(null);
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ });
+ afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); vi.restoreAllMocks(); });
+
+ it("leaves an already prevented quit to the Windows updater", async () => {
+ await setup();
+ const event = { defaultPrevented: true, preventDefault: vi.fn() };
+ context.beforeQuit!(event);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(context.dialog).not.toHaveBeenCalled();
+ expect(context.exec).not.toHaveBeenCalled();
+ expect(context.quit).not.toHaveBeenCalled();
+ });
+
+ it("allows the updater-owned final quit without a second daemon stop", async () => {
+ await setup();
+ const manager = await import("./daemon-manager");
+ await expect(manager.prepareDaemonForUpdateInstall({ interruptActiveTasks: false }))
+ .resolves.toEqual({ kind: "busy", activeTasks: 1 });
+ const event = { defaultPrevented: false, preventDefault: vi.fn() };
+ context.beforeQuit!(event);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(context.dialog).not.toHaveBeenCalled();
+ expect(context.exec).not.toHaveBeenCalled();
+ expect(context.quit).not.toHaveBeenCalled();
+ manager.resumeDaemonAfterAbortedUpdateInstall();
+ });
+
+ it("shows English confirmation and waits for the profile-scoped CLI result", async () => {
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ expect(context.dialog).toHaveBeenCalledWith(expect.objectContaining({
+ message: "1 run is active on this device.",
+ buttons: ["Cancel", "Stop now and quit"], defaultId: 0,
+ }));
+ expect(context.exec).toHaveBeenCalledWith(expect.any(String), ["daemon", "stop", "--force", "--profile", "desktop-example.test"], expect.objectContaining({ timeout: 55_000 }), expect.any(Function));
+ expect(context.quit).not.toHaveBeenCalled();
+ context.finishStop!();
+ await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ });
+
+ it("cancels the Chinese task warning without issuing a stop", async () => {
+ context.locale = "zh-CN"; context.dialog.mockResolvedValue({ response: 0 });
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.emit).toHaveBeenCalledWith("activate"));
+ expect(context.dialog).toHaveBeenCalledWith(expect.objectContaining({ buttons: ["取消", "立即停止并退出"] }));
+ expect(context.exec).not.toHaveBeenCalled(); expect(context.quit).not.toHaveBeenCalled();
+ });
+
+ it("offers ignore-and-quit only after the CLI reports failure", async () => {
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ context.finishStop!(new Error("daemon was forcibly terminated; task cleanup could not be confirmed"));
+ await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ expect(context.dialog).toHaveBeenLastCalledWith(expect.objectContaining({
+ message: "Could not confirm whether the daemon and its runs have stopped.",
+ detail: expect.stringContaining("automatic daemon restart disabled"),
+ buttons: ["Cancel quit", "Ignore and quit"], defaultId: 0,
+ }));
+ });
+
+ it("hides visible windows during shutdown and does not restore them on success", async () => {
+ const main = addWindow();
+ const issue = addWindow();
+ const hidden = addWindow(false);
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ expect(main.hide).toHaveBeenCalledOnce();
+ expect(issue.hide).toHaveBeenCalledOnce();
+ expect(hidden.hide).not.toHaveBeenCalled();
+ requestQuit();
+ expect(main.hide).toHaveBeenCalledOnce();
+ expect(context.quit).not.toHaveBeenCalled();
+ context.finishStop!();
+ await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ expect(main.show).not.toHaveBeenCalled();
+ expect(issue.show).not.toHaveBeenCalled();
+ });
+
+ it("keeps windows visible when the interruption warning is cancelled", async () => {
+ const window = addWindow();
+ context.dialog.mockResolvedValue({ response: 0 });
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.emit).toHaveBeenCalledWith("activate"));
+ expect(window.hide).not.toHaveBeenCalled();
+ expect(window.isVisible()).toBe(true);
+ });
+
+ it("restores visible windows before reporting failed cleanup and keeps the daemon stopped after cancellation", async () => {
+ const main = addWindow();
+ const hidden = addWindow(false);
+ context.dialog.mockResolvedValueOnce({ response: 1 });
+ context.dialog.mockImplementationOnce(async () => {
+ expect(main.show).toHaveBeenCalledOnce();
+ expect(main.isVisible()).toBe(true);
+ expect(hidden.show).not.toHaveBeenCalled();
+ return { response: 0 };
+ });
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ context.health.mockResolvedValue(null);
+ context.finishStop!(new Error("daemon was forcibly terminated; task cleanup could not be confirmed"));
+ await vi.waitFor(() => expect(context.emit).toHaveBeenCalledWith("activate"));
+ expect(context.dialog).toHaveBeenLastCalledWith(expect.objectContaining({
+ message: "The daemon has stopped, but its runs could not be confirmed to have exited.",
+ detail: expect.stringContaining("the daemon remains stopped"),
+ }));
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(context.exec.mock.calls.filter(([, args]) => args[1] === "start")).toHaveLength(0);
+ expect(context.quit).not.toHaveBeenCalled();
+ });
+
+ it("does not prompt for an idle daemon", async () => {
+ context.health.mockResolvedValue({ status: "running", active_task_count: 0 });
+ const window = addWindow();
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ expect(context.dialog).not.toHaveBeenCalled();
+ expect(window.hide).toHaveBeenCalledOnce();
+ context.finishStop!();
+ await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ });
+
+ it.each([undefined, -1, 1.5, Infinity, "2"])("uses unknown-state copy for an unconfirmed run count %s", async (count) => {
+ context.health.mockResolvedValue({ status: "running", active_task_count: count });
+ context.dialog.mockResolvedValue({ response: 0 });
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.dialog).toHaveBeenCalledWith(expect.objectContaining({
+ message: "Could not confirm whether any runs are active on this device.",
+ })));
+ expect(context.exec).not.toHaveBeenCalled();
+ });
+
+ it("queues the final stop behind an earlier CLI start", async () => {
+ await setup(); context.holdStart = true; context.health.mockResolvedValue(null);
+ const started = context.handlers.get("daemon:start")!({});
+ await vi.waitFor(() => expect(context.finishStart).toBeTypeOf("function"));
+ requestQuit(); await vi.advanceTimersByTimeAsync(0);
+ expect(context.finishStop).toBeNull(); expect(context.quit).not.toHaveBeenCalled();
+ context.finishStart!(); await started;
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ context.finishStop!();
+ await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ });
+
+ it("does not wait for CLI installation when no daemon has started", async () => {
+ await setupInstallingCLI();
+ requestQuit();
+ await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ expect(context.dialog).not.toHaveBeenCalled();
+ expect(context.exec).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])("requires explicit ignore=%s when the CLI is unavailable and a port-record process is alive", async (ignore) => {
+ context.readPort.mockResolvedValue({ port: 19515, pid: 20001 });
+ vi.spyOn(process, "kill").mockImplementation((pid, signal) => {
+ if (pid === 20001 && signal === 0) return true;
+ throw Object.assign(new Error("Process is absent"), { code: "ESRCH" });
+ });
+ context.dialog.mockResolvedValueOnce({ response: 1 }).mockResolvedValueOnce({ response: ignore ? 1 : 0 });
+ await setupInstallingCLI();
+ requestQuit();
+ await vi.waitFor(() => expect(context.dialog).toHaveBeenCalledTimes(2));
+ expect(context.dialog).toHaveBeenLastCalledWith(expect.objectContaining({
+ buttons: ["Cancel quit", "Ignore and quit"], defaultId: 0,
+ }));
+ if (ignore) await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ else {
+ await vi.waitFor(() => expect(context.emit).toHaveBeenCalledWith("activate"));
+ expect(context.quit).not.toHaveBeenCalled();
+ }
+ expect(context.exec).not.toHaveBeenCalled();
+ });
+
+ it("rechecks process evidence after confirmation and exits if cleanup has completed", async () => {
+ let alive = true;
+ context.readPort.mockResolvedValue({ port: 19515, pid: 20001 });
+ vi.spyOn(process, "kill").mockImplementation((pid, signal) => {
+ if (alive && pid === 20001 && signal === 0) return true;
+ throw Object.assign(new Error("Process is absent"), { code: "ESRCH" });
+ });
+ context.dialog.mockImplementation(async () => { alive = false; return { response: 1 }; });
+ await setupInstallingCLI();
+ requestQuit();
+ await vi.waitFor(() => expect(context.quit).toHaveBeenCalledOnce());
+ expect(context.dialog).toHaveBeenCalledOnce();
+ expect(context.exec).not.toHaveBeenCalled();
+ });
+
+ it.each(["PID file", "port record"])("confirms task interruption when health is lost but the %s PID is alive", async (source) => {
+ await setup();
+ if (source === "PID file") context.pid = 20001;
+ else context.readPort.mockResolvedValue({ port: 19515, pid: 20001 });
+ vi.spyOn(process, "kill").mockImplementation((pid, signal) => {
+ if (pid === 20001 && signal === 0) return true;
+ throw Object.assign(new Error("Process is absent"), { code: "ESRCH" });
+ });
+ context.health.mockResolvedValue(null);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(await context.handlers.get("daemon:get-status")!({})).toMatchObject({ state: "stopped" });
+ context.dialog.mockResolvedValue({ response: 0 });
+ requestQuit();
+ await vi.waitFor(() => expect(context.dialog).toHaveBeenCalledWith(expect.objectContaining({
+ type: "warning", buttons: ["Cancel", "Stop now and quit"], defaultId: 0,
+ })));
+ expect(context.exec).not.toHaveBeenCalled();
+ expect(context.quit).not.toHaveBeenCalled();
+ });
+ it("keeps auto-start suppressed when cancelling a failed quit recreates the renderer", async () => {
+ context.autoStart = true;
+ context.dialog.mockResolvedValueOnce({ response: 1 }).mockResolvedValueOnce({ response: 0 });
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ context.health.mockResolvedValue(null);
+ context.finishStop!(new Error("task cleanup could not be confirmed"));
+ await vi.waitFor(() => expect(context.emit).toHaveBeenCalledWith("activate"));
+ // A recreated renderer calls auto-start again through syncDaemonOnLogin.
+ await context.handlers.get("daemon:auto-start")!({});
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(context.exec.mock.calls.filter(([, args]) => args[1] === "start")).toHaveLength(0);
+ expect(await context.handlers.get("daemon:get-prefs")!({})).toMatchObject({ autoStart: true });
+ expect(context.quit).not.toHaveBeenCalled();
+
+ await context.handlers.get("daemon:start")!({});
+ expect(context.exec.mock.calls.filter(([, args]) => args[1] === "start")).toHaveLength(1);
+ context.exec.mockClear();
+ await context.handlers.get("daemon:auto-start")!({});
+ expect(context.exec.mock.calls.filter(([, args]) => args[1] === "start")).toHaveLength(1);
+ });
+
+ it("still allows auto-start after cancelling the initial interruption warning", async () => {
+ context.autoStart = true;
+ context.dialog.mockResolvedValue({ response: 0 });
+ await setup(); requestQuit();
+ await vi.waitFor(() => expect(context.emit).toHaveBeenCalledWith("activate"));
+ context.health.mockResolvedValue(null);
+ await context.handlers.get("daemon:auto-start")!({});
+ expect(context.exec.mock.calls.filter(([, args]) => args[1] === "start")).toHaveLength(1);
+ });
+
+ it("does not perform a deferred version restart after cancelling a failed quit", async () => {
+ context.autoStart = true;
+ context.health.mockResolvedValue({ status: "running", active_task_count: 1, cli_version: "old" });
+ context.dialog.mockResolvedValueOnce({ response: 1 }).mockResolvedValueOnce({ response: 0 });
+ await setup();
+ await context.handlers.get("daemon:auto-start")!({});
+ requestQuit();
+ await vi.waitFor(() => expect(context.finishStop).toBeTypeOf("function"));
+ context.finishStop!(new Error("OS refused termination"));
+ await vi.waitFor(() => expect(context.emit).toHaveBeenCalledWith("activate"));
+ context.exec.mockClear();
+ context.health.mockResolvedValue({ status: "running", active_task_count: 0, cli_version: "old" });
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(context.exec.mock.calls.filter(([, args]) => args[1] === "stop" || args[1] === "start")).toHaveLength(0);
+ });
+});
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
index ac70e044d9..aad967589c 100644
--- a/apps/desktop/src/main/daemon-manager.ts
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -1,4 +1,4 @@
-import { app, ipcMain, BrowserWindow, shell } from "electron";
+import { app, ipcMain, BrowserWindow, shell, dialog, type MessageBoxOptions } from "electron";
import { execFile } from "child_process";
import {
readFile,
@@ -24,6 +24,8 @@ import type {
import { daemonStatusAlive } from "../shared/daemon-types";
import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";
import { decideVersionAction } from "./version-decision";
+import { createDaemonQuitHandler } from "./daemon-quit";
+import { quitConfirmationOptions, quitFailureOptions } from "./daemon-quit-dialogs";
import {
prepareDaemonForInstall,
type DaemonInstallPrep,
@@ -37,7 +39,7 @@ import {
profilePidPath,
profileUserIdPath,
} from "./daemon-profile";
-import { probeProfileHealth } from "./daemon-port";
+import { probeProfileHealth, readDaemonPortRecord } from "./daemon-port";
import {
DaemonOperationGate,
DaemonRecoveryPolicy,
@@ -106,6 +108,10 @@ let desiredDaemonRunning = false;
// Non-null while the Windows updater owns daemon shutdown and installation.
let desiredRunningBeforeUpdateStop: boolean | null = null;
const UPDATE_IN_PROGRESS = { success: false, error: "An update is being installed. Try again shortly." };
+let quitting = false;
+// Renderer recreation must not undo a failed-quit cancellation. Keep this
+// process-local until an explicit start/restart, without changing preferences.
+let autoStartSuppressedAfterQuit = false;
// Once a foreign-OS daemon (for example WSL2) is observed on this profile, do
// not replace it with a native daemon if its forwarded health endpoint drops.
let externalDaemonObserved = false;
@@ -319,6 +325,7 @@ function invalidateActiveProfile(): void {
function setDesiredDaemonRunning(desired: boolean, explicit = false): void {
if (desired && desiredRunningBeforeUpdateStop !== null) return;
+ if (desired && explicit) autoStartSuppressedAfterQuit = false;
if (desiredDaemonRunning === desired && !explicit) return;
desiredDaemonRunning = desired;
recoveryPolicy.reset();
@@ -516,6 +523,7 @@ async function probeCliBinary(
* installs are de-duplicated via `cliResolvePromise`.
*/
async function resolveCliBinary(): Promise<string | null> {
+ if (quitting) return cachedCliBinary ?? null;
if (cachedCliBinary !== undefined) return cachedCliBinary;
if (cliResolvePromise) return cliResolvePromise;
@@ -615,6 +623,7 @@ async function getCliBinaryVersion(): Promise<string | null> {
async function ensureRunningDaemonVersionMatches(): Promise<
"restarted" | "deferred" | "ok" | "not_running"
> {
+ if (quitting || autoStartSuppressedAfterQuit) return "deferred";
const active = await ensureActiveProfile();
if (!active) return "not_running";
const running = await fetchProfileHealth(active);
@@ -628,7 +637,11 @@ async function ensureRunningDaemonVersionMatches(): Promise<
}
const bundled = await getCliBinaryVersion();
- if (desiredRunningBeforeUpdateStop !== null) {
+ if (
+ quitting ||
+ autoStartSuppressedAfterQuit ||
+ desiredRunningBeforeUpdateStop !== null
+ ) {
pendingVersionRestart = true;
return "deferred";
}
@@ -964,6 +977,7 @@ async function startDaemon(
recoveryProfile?: ActiveProfile,
): Promise<{ success: boolean; error?: string }> {
if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
+ if (quitting) return { success: false, error: "Application is quitting" };
const bin = await resolveCliBinary();
if (!bin) return { success: false, error: "multica CLI is not installed" };
@@ -1007,6 +1021,7 @@ async function startDaemon(
}
if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
+ if (quitting) return { success: false, error: "Application is quitting" };
if (recoveryProfile) recoveryPolicy.recordRecoveryAttempt(Date.now());
currentState = "starting";
// Begin a fresh auth-probe window for this attempt.
@@ -1057,8 +1072,9 @@ async function lifecycleBlockedByForeignDaemon(): Promise<boolean> {
}
async function stopDaemon(
- signal?: AbortSignal,
+ options: { force?: boolean; signal?: AbortSignal } = {},
): Promise<{ success: boolean; error?: string }> {
+ const { signal } = options;
if (signal?.aborted) return { success: true };
// Central lifecycle guard: a daemon running in an environment we can't drive
// (e.g. Linux in WSL2 behind a Windows desktop) can't be stopped by the
@@ -1082,10 +1098,11 @@ async function stopDaemon(
startingSince = null;
sendStatus({ state: "stopping" });
- const args = ["daemon", "stop", ...profileArgs(active.name)];
+ const args = ["daemon", "stop", ...(options.force ? ["--force"] : []), ...profileArgs(active.name)];
return new Promise((resolve) => {
- execFile(bin, args, { timeout: 15_000 }, (err) => {
+ // The CLI's forced stop includes the existing 40s shutdown budget.
+ execFile(bin, args, { timeout: options.force ? 55_000 : 15_000 }, (err) => {
if (err) {
resolve({ success: false, error: err.message });
} else {
@@ -1099,6 +1116,7 @@ async function stopDaemon(
async function restartDaemon(): Promise<{ success: boolean; error?: string }> {
if (desiredRunningBeforeUpdateStop !== null) return UPDATE_IN_PROGRESS;
+ if (quitting) return { success: false, error: "Application is quitting" };
// Same central, live-preflighted guard as stopDaemon: we can neither stop nor
// start a daemon we don't manage, so don't try (user-switch, reauth,
// first-workspace, and any future restart caller all route through here).
@@ -1134,6 +1152,12 @@ async function daemonPidIsConfirmedAbsent(profile: string): Promise<boolean> {
}
}
+async function daemonProcessIsConfirmedAbsent(profile: string): Promise<boolean> {
+ const record = await readDaemonPortRecord(profile);
+ return await daemonPidIsConfirmedAbsent(profile)
+ && !(record && daemonProcessExists(record.pid));
+}
+
async function attemptDaemonRecovery(active: ActiveProfile): Promise<void> {
const startAllowed = () =>
recoveryStartAllowed({
@@ -1207,10 +1231,11 @@ function recoveryDecision(status: DaemonStatus) {
}
async function pollOnce(): Promise<void> {
- if (statusPollInProgress) return;
+ if (quitting || statusPollInProgress) return;
statusPollInProgress = true;
try {
const status = await fetchHealth();
+ if (quitting) return;
currentState = status.state;
observeDaemonBoundary(status);
const decision = recoveryDecision(status);
@@ -1245,7 +1270,7 @@ async function pollOnce(): Promise<void> {
}
function startPolling(): void {
- if (statusPollTimer || desiredRunningBeforeUpdateStop !== null) return;
+ if (quitting || statusPollTimer || desiredRunningBeforeUpdateStop !== null) return;
void pollOnce();
statusPollTimer = setInterval(() => void pollOnce(), POLL_INTERVAL_MS);
}
@@ -1390,7 +1415,7 @@ export function prepareDaemonForUpdateInstall(options: {
};
},
stop: async (signal) => {
- const result = await lifecycleOperations.runForeground(() => stopDaemon(signal));
+ const result = await lifecycleOperations.runForeground(() => stopDaemon({ signal }));
if (!result.success) throw new Error(result.error ?? "daemon stop failed");
},
processExists: daemonProcessExists,
@@ -1496,14 +1521,17 @@ export function setupDaemonManager(
);
ipcMain.handle("daemon:auto-start", async () => {
const prefs = await loadPrefs();
+ if (quitting || autoStartSuppressedAfterQuit) return;
setDesiredDaemonRunning(prefs.autoStart);
if (!prefs.autoStart) return;
// Login auto-start is emitted once per session. Queue it behind bootstrap
// instead of dropping it like a retryable poll operation.
await lifecycleOperations.runForeground(async () => {
+ if (quitting || autoStartSuppressedAfterQuit) return;
const bin = await resolveCliBinary();
if (!bin) return;
const health = await fetchHealth();
+ if (quitting || autoStartSuppressedAfterQuit) return;
observeDaemonBoundary(health);
if (health.state === "running") {
// Daemon is up but may be running an older CLI than the one we just
@@ -1544,32 +1572,96 @@ export function setupDaemonManager(
sendStatus({ state: "installing_cli" });
void lifecycleOperations.runBackground(() => bootstrapCli());
- let isQuitting = false;
- app.on("before-quit", (event) => {
- // The updater registers first and owns shutdown while its gate is pending.
- // Do not issue a second stop or re-enter app.quit() before PID exit is known.
- if (event.defaultPrevented || isQuitting) return;
- setDesiredDaemonRunning(false);
- stopPolling();
- stopLogTail();
-
- // The update gate already stopped the daemon or exhausted its deadline.
- // Let its approved quit proceed without another stop/re-entrant quit.
- if (desiredRunningBeforeUpdateStop !== null) return;
-
- loadPrefs().then(async (prefs) => {
- if (prefs.autoStop) {
- isQuitting = true;
- event.preventDefault();
- try {
- // stopDaemon no-ops for an externally-managed daemon (WSL2 etc.), so
- // this is safe and instant in that case — the guard lives there. #3916
- await stopDaemon();
- } catch {
- // Best-effort stop on quit
- }
- app.quit();
+ let desiredBeforeQuit = false;
+ const language = app.getPreferredSystemLanguages()[0] ?? "en";
+ let hiddenQuitWindows: BrowserWindow[] = [];
+ const hideQuitWindows = () => {
+ hiddenQuitWindows = BrowserWindow.getAllWindows().filter((window) =>
+ !window.isDestroyed() && window.isVisible(),
+ );
+ for (const window of hiddenQuitWindows) window.hide();
+ };
+ const restoreQuitWindows = () => {
+ for (const window of hiddenQuitWindows) {
+ if (!window.isDestroyed()) window.show();
+ }
+ hiddenQuitWindows = [];
+ };
+ const show = (options: MessageBoxOptions) => {
+ const window = getMainWindow();
+ return window && !window.isDestroyed() && window.isVisible()
+ ? dialog.showMessageBox(window, options) : dialog.showMessageBox(options);
+ };
+ const handleQuit = createDaemonQuitHandler({
+ loadPrefs,
+ pause: () => {
+ desiredBeforeQuit = desiredDaemonRunning;
+ quitting = true;
+ setDesiredDaemonRunning(false);
+ stopPolling();
+ },
+ resume: (restoreDesired) => {
+ restoreQuitWindows();
+ if (!restoreDesired) autoStartSuppressedAfterQuit = true;
+ quitting = false;
+ setDesiredDaemonRunning(restoreDesired && desiredBeforeQuit);
+ startPolling();
+ if (!getMainWindow()) app.emit("activate");
+ },
+ stop: async () => {
+ const active = await ensureActiveProfile();
+ if (!active) return true;
+ const health = await fetchProfileHealth(active);
+ if (isDaemonExternallyManaged(health?.os, normalizeHostOS(process.platform))) return true;
+ const healthy = daemonStatusAlive(health?.status);
+ const reportedRuns = health?.active_task_count;
+ const activeRuns = healthy && typeof reportedRuns === "number"
+ && Number.isSafeInteger(reportedRuns) && reportedRuns >= 0 ? reportedRuns : null;
+ let busy = healthy
+ ? activeRuns !== 0
+ : currentState === "running" || currentState === "starting";
+ if (!healthy && !busy) {
+ busy = !await daemonProcessIsConfirmedAbsent(active.name);
}
- });
+ if (busy && (await show(quitConfirmationOptions(language, activeRuns))).response !== 1) return false;
+ // Reuse the lifecycle queue: an earlier start must finish before stop.
+ // Do not queue behind an unresolved CLI installation during quit.
+ if (!cachedCliBinary) {
+ if (!healthy && await daemonProcessIsConfirmedAbsent(active.name)) return true;
+ throw new Error("Multica CLI is not available");
+ }
+ const window = getMainWindow();
+ window?.setProgressBar(2);
+ // Make the accepted quit visible even while a prior start or cleanup drains.
+ hideQuitWindows();
+ try {
+ const result = await lifecycleOperations.runForeground(() => stopDaemon({ force: true }));
+ if (!result.success) throw new Error(result.error ?? "Could not stop the daemon");
+ } finally {
+ if (window && !window.isDestroyed()) window.setProgressBar(-1);
+ }
+ return true;
+ },
+ confirmIgnore: async (error) => {
+ console.warn("[daemon] could not stop on quit:", error);
+ restoreQuitWindows();
+ const active = await ensureActiveProfile();
+ const health = active ? await fetchProfileHealth(active) : null;
+ const daemonStopped = Boolean(active && !daemonStatusAlive(health?.status)
+ && await daemonProcessIsConfirmedAbsent(active.name));
+ return (await show(quitFailureOptions(language, daemonStopped))).response === 1;
+ },
+ quit: () => { stopLogTail(); app.quit(); },
+ });
+ app.on("before-quit", (event) => {
+ // The Windows updater registers first and owns its pending or approved quit.
+ if (event.defaultPrevented) return;
+ if (desiredRunningBeforeUpdateStop !== null) {
+ setDesiredDaemonRunning(false);
+ stopPolling();
+ stopLogTail();
+ return;
+ }
+ handleQuit(event);
});
}
diff --git a/apps/desktop/src/main/daemon-quit-dialogs.test.ts b/apps/desktop/src/main/daemon-quit-dialogs.test.ts
new file mode 100644
index 0000000000..63ca882834
--- /dev/null
+++ b/apps/desktop/src/main/daemon-quit-dialogs.test.ts
@@ -0,0 +1,53 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { quitConfirmationOptions, quitFailureOptions } from "./daemon-quit-dialogs";
+
+describe("daemon quit dialog copy", () => {
+ it.each([
+ [1, "1 run is active on this device."],
+ [3, "3 runs are active on this device."],
+ [null, "Could not confirm whether any runs are active on this device."],
+ ])("distinguishes known run count %s from unknown state", (count, message) => {
+ expect(quitConfirmationOptions("en-US", count)).toMatchObject({
+ message, buttons: ["Cancel", "Stop now and quit"], defaultId: 0, cancelId: 0,
+ });
+ });
+
+ it.each([
+ ["zh-CN", "退出 Multica"],
+ ["zh-SG", "退出 Multica"],
+ ["zh-Hant", "結束 Multica"],
+ ["zh-TW", "結束 Multica"],
+ ["zh-HK", "結束 Multica"],
+ ["zh-MO", "結束 Multica"],
+ ["ja-JP", "Multica を終了"],
+ ["ko-KR", "Multica 종료"],
+ ["fr-FR", "Quit Multica"],
+ ["", "Quit Multica"],
+ ])("resolves OS language %s using the native menu locale policy", (language, title) => {
+ const options = quitConfirmationOptions(language, 3);
+ expect(options.title).toBe(title);
+ expect(options.message).toContain("3");
+ expect(options.message).not.toContain("Agent tasks");
+ });
+
+ it.each(["en", "zh-Hans", "zh-Hant", "ja", "ko"])("distinguishes stopped and unconfirmed daemon states in %s", (language) => {
+ const stopped = quitFailureOptions(language, true);
+ const unknown = quitFailureOptions(language, false);
+ expect(stopped.message).not.toEqual(unknown.message);
+ expect(stopped.detail).not.toEqual(unknown.detail);
+ expect(stopped).toMatchObject({ defaultId: 0, cancelId: 0 });
+ expect(unknown.buttons).toEqual(stopped.buttons);
+ });
+
+ it("explains the resulting cancellation state without asserting an unconfirmed kill", () => {
+ expect(quitFailureOptions("en", true)).toMatchObject({
+ message: "The daemon has stopped, but its runs could not be confirmed to have exited.",
+ detail: expect.stringContaining("the daemon remains stopped"),
+ });
+ expect(quitFailureOptions("en", false)).toMatchObject({
+ message: "Could not confirm whether the daemon and its runs have stopped.",
+ detail: expect.stringContaining("automatic daemon restart disabled"),
+ });
+ });
+});
diff --git a/apps/desktop/src/main/daemon-quit-dialogs.ts b/apps/desktop/src/main/daemon-quit-dialogs.ts
new file mode 100644
index 0000000000..00deca8cd1
--- /dev/null
+++ b/apps/desktop/src/main/daemon-quit-dialogs.ts
@@ -0,0 +1,145 @@
+import type { MessageBoxOptions } from "electron";
+
+interface QuitLabels {
+ title: string;
+ activeRuns: (count: number) => string;
+ unknownRuns: string;
+ interruptRuns: string;
+ interruptUnknownRuns: string;
+ cancel: string;
+ stopAndQuit: string;
+ failureTitle: string;
+ daemonStopped: string;
+ shutdownUnknown: string;
+ cancelAfterStop: string;
+ cancelUnconfirmed: string;
+ cancelQuit: string;
+ ignoreAndQuit: string;
+}
+
+const labels: Record<string, QuitLabels> = {
+ en: {
+ title: "Quit Multica",
+ activeRuns: (count) => `${count} ${count === 1 ? "run is" : "runs are"} active on this device.`,
+ unknownRuns: "Could not confirm whether any runs are active on this device.",
+ interruptRuns: "Stopping the daemon now will interrupt active runs.",
+ interruptUnknownRuns: "Stopping the daemon may interrupt runs on this device.",
+ cancel: "Cancel",
+ stopAndQuit: "Stop now and quit",
+ failureTitle: "Could not confirm shutdown",
+ daemonStopped: "The daemon has stopped, but its runs could not be confirmed to have exited.",
+ shutdownUnknown: "Could not confirm whether the daemon and its runs have stopped.",
+ cancelAfterStop: "If you cancel, Multica stays open and the daemon remains stopped. Background runs may continue.",
+ cancelUnconfirmed: "If you cancel, Multica stays open with automatic daemon restart disabled. Background runs may continue.",
+ cancelQuit: "Cancel quit",
+ ignoreAndQuit: "Ignore and quit",
+ },
+ "zh-Hans": {
+ title: "退出 Multica",
+ activeRuns: (count) => `此设备上有 ${count} 次运行尚未结束。`,
+ unknownRuns: "无法确认此设备上是否有运行正在进行。",
+ interruptRuns: "立即停止守护进程会中断这些运行。",
+ interruptUnknownRuns: "停止守护进程可能中断此设备上的运行。",
+ cancel: "取消",
+ stopAndQuit: "立即停止并退出",
+ failureTitle: "无法确认停止完成",
+ daemonStopped: "守护进程已停止,但无法确认其运行进程是否已全部退出。",
+ shutdownUnknown: "无法确认守护进程及其运行是否已全部停止。",
+ cancelAfterStop: "取消后 Multica 会保持打开,守护进程保持停止。后台运行可能继续执行。",
+ cancelUnconfirmed: "取消后 Multica 会保持打开,守护进程不会自动重启。后台运行可能继续执行。",
+ cancelQuit: "取消退出",
+ ignoreAndQuit: "忽略并退出",
+ },
+ "zh-Hant": {
+ title: "結束 Multica",
+ activeRuns: (count) => `此裝置上有 ${count} 次執行尚未結束。`,
+ unknownRuns: "無法確認此裝置上是否有執行正在進行。",
+ interruptRuns: "立即停止守護進程會中斷這些執行。",
+ interruptUnknownRuns: "停止守護進程可能中斷此裝置上的執行。",
+ cancel: "取消",
+ stopAndQuit: "立即停止並結束",
+ failureTitle: "無法確認停止完成",
+ daemonStopped: "守護進程已停止,但無法確認其執行程序是否已全部結束。",
+ shutdownUnknown: "無法確認守護進程及其執行是否已全部停止。",
+ cancelAfterStop: "取消後 Multica 會保持開啟,守護進程保持停止。背景執行可能繼續進行。",
+ cancelUnconfirmed: "取消後 Multica 會保持開啟,守護進程不會自動重新啟動。背景執行可能繼續進行。",
+ cancelQuit: "取消結束",
+ ignoreAndQuit: "忽略並結束",
+ },
+ ja: {
+ title: "Multica を終了",
+ activeRuns: (count) => `このデバイスで ${count} 件の実行が進行中です。`,
+ unknownRuns: "このデバイスで実行が進行中か確認できませんでした。",
+ interruptRuns: "今すぐデーモンを停止すると、これらの実行は中断されます。",
+ interruptUnknownRuns: "デーモンを停止すると、このデバイスでの実行が中断される可能性があります。",
+ cancel: "キャンセル",
+ stopAndQuit: "今すぐ停止して終了",
+ failureTitle: "停止を確認できませんでした",
+ daemonStopped: "デーモンは停止しましたが、実行プロセスがすべて終了したか確認できませんでした。",
+ shutdownUnknown: "デーモンと実行プロセスがすべて停止したか確認できませんでした。",
+ cancelAfterStop: "キャンセルすると Multica は開いたままとなり、デーモンは停止したままです。バックグラウンドの実行が続く可能性があります。",
+ cancelUnconfirmed: "キャンセルすると Multica は開いたままとなり、デーモンの自動再起動は無効のままです。バックグラウンドの実行が続く可能性があります。",
+ cancelQuit: "終了をキャンセル",
+ ignoreAndQuit: "無視して終了",
+ },
+ ko: {
+ title: "Multica 종료",
+ activeRuns: (count) => `이 기기에서 ${count}개의 실행이 진행 중입니다.`,
+ unknownRuns: "이 기기에서 진행 중인 실행이 있는지 확인할 수 없습니다.",
+ interruptRuns: "지금 데몬을 중지하면 이 실행들이 중단됩니다.",
+ interruptUnknownRuns: "데몬을 중지하면 이 기기의 실행이 중단될 수 있습니다.",
+ cancel: "취소",
+ stopAndQuit: "지금 중지하고 종료",
+ failureTitle: "중지 완료를 확인할 수 없음",
+ daemonStopped: "데몬은 중지되었지만 실행 프로세스가 모두 종료되었는지 확인할 수 없습니다.",
+ shutdownUnknown: "데몬과 실행 프로세스가 모두 중지되었는지 확인할 수 없습니다.",
+ cancelAfterStop: "취소하면 Multica는 열린 상태로 유지되고 데몬은 중지된 상태로 유지됩니다. 백그라운드 실행은 계속될 수 있습니다.",
+ cancelUnconfirmed: "취소하면 Multica는 열린 상태로 유지되고 데몬은 자동으로 다시 시작되지 않습니다. 백그라운드 실행은 계속될 수 있습니다.",
+ cancelQuit: "종료 취소",
+ ignoreAndQuit: "무시하고 종료",
+ },
+};
+
+function quitLabels(preferredLanguage: string): QuitLabels {
+ const preferred = preferredLanguage.toLowerCase();
+ if (preferred.startsWith("zh")) {
+ return /^zh-(hant|tw|hk|mo)\b/.test(preferred) ? labels["zh-Hant"] : labels["zh-Hans"];
+ }
+ if (preferred.startsWith("ja")) return labels.ja;
+ if (preferred.startsWith("ko")) return labels.ko;
+ return labels.en;
+}
+
+export function quitConfirmationOptions(
+ preferredLanguage: string,
+ activeRuns: number | null,
+): MessageBoxOptions {
+ const copy = quitLabels(preferredLanguage);
+ return {
+ type: "warning",
+ title: copy.title,
+ message: activeRuns === null ? copy.unknownRuns : copy.activeRuns(activeRuns),
+ detail: activeRuns === null ? copy.interruptUnknownRuns : copy.interruptRuns,
+ buttons: [copy.cancel, copy.stopAndQuit],
+ defaultId: 0,
+ cancelId: 0,
+ noLink: true,
+ };
+}
+
+export function quitFailureOptions(
+ preferredLanguage: string,
+ daemonStopped: boolean,
+): MessageBoxOptions {
+ const copy = quitLabels(preferredLanguage);
+ return {
+ type: "warning",
+ title: copy.failureTitle,
+ message: daemonStopped ? copy.daemonStopped : copy.shutdownUnknown,
+ detail: daemonStopped ? copy.cancelAfterStop : copy.cancelUnconfirmed,
+ buttons: [copy.cancelQuit, copy.ignoreAndQuit],
+ defaultId: 0,
+ cancelId: 0,
+ noLink: true,
+ };
+}
diff --git a/apps/desktop/src/main/daemon-quit.test.ts b/apps/desktop/src/main/daemon-quit.test.ts
new file mode 100644
index 0000000000..9998846c74
--- /dev/null
+++ b/apps/desktop/src/main/daemon-quit.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from "vitest";
+import { createDaemonQuitHandler } from "./daemon-quit";
+
+function setup() {
+ const deps = {
+ loadPrefs: vi.fn(async () => ({ autoStop: true })), pause: vi.fn(), resume: vi.fn(),
+ stop: vi.fn(async () => true), confirmIgnore: vi.fn(async () => false), quit: vi.fn(),
+ };
+ const handler = createDaemonQuitHandler(deps);
+ const request = () => { const event = { preventDefault: vi.fn() }; handler(event); return event; };
+ return { deps, request };
+}
+
+describe("quit with daemon auto-stop", () => {
+ it("synchronously blocks repeated quits until stopping finishes", async () => {
+ const { deps, request } = setup();
+ let finish!: (result: boolean) => void;
+ deps.stop.mockReturnValue(new Promise((resolve) => { finish = resolve; }));
+ expect(request().preventDefault).toHaveBeenCalledOnce();
+ request();
+ await vi.waitFor(() => expect(deps.stop).toHaveBeenCalledOnce());
+ expect(deps.quit).not.toHaveBeenCalled();
+ finish(true);
+ await vi.waitFor(() => expect(deps.quit).toHaveBeenCalledOnce());
+ expect(request().preventDefault).not.toHaveBeenCalled();
+ });
+
+ it("preserves the daemon when auto-stop is disabled", async () => {
+ const { deps, request } = setup();
+ deps.loadPrefs.mockResolvedValue({ autoStop: false });
+ request();
+ await vi.waitFor(() => expect(deps.quit).toHaveBeenCalledOnce());
+ expect(deps.pause).not.toHaveBeenCalled();
+ expect(deps.stop).not.toHaveBeenCalled();
+ });
+
+ it("resumes normal use when the task warning is cancelled", async () => {
+ const { deps, request } = setup();
+ deps.stop.mockResolvedValue(false);
+ request();
+ await vi.waitFor(() => expect(deps.resume).toHaveBeenCalledWith(true));
+ expect(deps.quit).not.toHaveBeenCalled();
+ expect(deps.confirmIgnore).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])("only quits after a stop failure when ignore is %s", async (ignore) => {
+ const { deps, request } = setup();
+ const error = new Error("OS refused termination");
+ deps.stop.mockRejectedValue(error);
+ deps.confirmIgnore.mockResolvedValue(ignore);
+ request();
+ await vi.waitFor(() => expect(deps.confirmIgnore).toHaveBeenCalledWith(error));
+ await vi.waitFor(() => expect(ignore ? deps.quit : deps.resume).toHaveBeenCalledOnce());
+ if (ignore) expect(deps.resume).not.toHaveBeenCalled();
+ else {
+ expect(deps.resume).toHaveBeenCalledWith(false);
+ expect(deps.quit).not.toHaveBeenCalled();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/daemon-quit.ts b/apps/desktop/src/main/daemon-quit.ts
new file mode 100644
index 0000000000..11b1ce22f0
--- /dev/null
+++ b/apps/desktop/src/main/daemon-quit.ts
@@ -0,0 +1,40 @@
+interface QuitDependencies {
+ loadPrefs: () => Promise<{ autoStop: boolean }>;
+ pause: () => void;
+ resume: (restoreDesired: boolean) => void;
+ stop: () => Promise<boolean>;
+ confirmIgnore: (error: unknown) => Promise<boolean>;
+ quit: () => void;
+}
+
+export function createDaemonQuitHandler(deps: QuitDependencies) {
+ let busy = false;
+ let ready = false;
+ return (event: { preventDefault: () => void }) => {
+ if (ready) return;
+ event.preventDefault();
+ if (busy) return;
+ busy = true;
+ void (async () => {
+ let paused = false;
+ let restoreDesired = true;
+ try {
+ if ((await deps.loadPrefs()).autoStop) {
+ deps.pause();
+ paused = true;
+ try {
+ if (!await deps.stop()) return;
+ } catch (error) {
+ restoreDesired = false;
+ if (!await deps.confirmIgnore(error)) return;
+ }
+ }
+ ready = true;
+ deps.quit();
+ } finally {
+ if (paused && !ready) deps.resume(restoreDesired);
+ busy = false;
+ }
+ })().catch((error) => console.warn("[daemon] quit interrupted:", error));
+ };
+}
diff --git a/apps/desktop/src/main/update-install-lifecycle.test.ts b/apps/desktop/src/main/update-install-lifecycle.test.ts
index 280d3a964d..9aa7e8227b 100644
--- a/apps/desktop/src/main/update-install-lifecycle.test.ts
+++ b/apps/desktop/src/main/update-install-lifecycle.test.ts
@@ -35,6 +35,7 @@ vi.mock("electron", () => ({
getPath: () => "/review-only/user-data",
getAppPath: () => "/review-only/app",
getVersion: () => "0.7.0",
+ getPreferredSystemLanguages: () => ["en"],
},
BrowserWindow: class {},
ipcMain: {
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 6b7a3ee598..56aa14f291 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -112,6 +112,7 @@ func init() {
f.Bool("no-auto-update", false, "Disable periodic CLI self-update (env: MULTICA_DAEMON_AUTO_UPDATE=false)")
f.Duration("auto-update-interval", 0, "How often to poll GitHub for a newer release (env: MULTICA_DAEMON_AUTO_UPDATE_INTERVAL)")
f.Bool("no-auto-reload", false, "Disable restarting when the multica binary on disk changes version (env: MULTICA_DAEMON_AUTO_RELOAD=false)")
+ daemonStopCmd.Flags().Bool("force", false, "Wait for graceful shutdown, then force termination if needed")
daemonLogsCmd.Flags().BoolP("follow", "f", false, "Follow log output")
daemonLogsCmd.Flags().IntP("lines", "n", 50, "Number of lines to show")
@@ -1118,6 +1119,9 @@ func runDaemonForeground(cmd *cobra.Command) error {
if daemonAlive(existing) && daemonIdentityMismatch(existing, profile, port) == nil {
return fmt.Errorf("daemon %s is already running or starting", describeProfile(profile))
}
+ if err := writeDaemonShutdownResult(profile, daemonShutdownResult{PID: os.Getpid()}); err != nil {
+ return fmt.Errorf("initialize daemon shutdown result: %w", err)
+ }
healthLn, actualPort, err := bindDaemonHealthPort(cfg.HealthPort, net.Listen)
if err != nil {
return err
@@ -1141,8 +1145,12 @@ func runDaemonForeground(cmd *cobra.Command) error {
}
defer os.Remove(daemonPIDPathForProfile(profile))
- if err := d.RunWithHealthListener(ctx, healthLn); err != nil && !errors.Is(err, context.Canceled) {
- return err
+ runErr := d.RunWithHealthListener(ctx, healthLn)
+ if err := writeDaemonShutdownResult(profile, daemonShutdownResult{PID: os.Getpid(), CleanupConfirmed: d.ShutdownCleanupConfirmed()}); err != nil {
+ return fmt.Errorf("write daemon shutdown result: %w", err)
+ }
+ if runErr != nil && !errors.Is(runErr, context.Canceled) {
+ return runErr
}
// Check if the daemon needs to restart after a CLI update.
@@ -1359,6 +1367,13 @@ func runDaemonStop(cmd *cobra.Command, _ []string) error {
defer cancel()
health := checkDaemonHealthOnPort(ctx, healthPort)
+ if force, _ := cmd.Flags().GetBool("force"); force {
+ if err := stopDaemonAndWait(profile, healthPort, health, daemonShutdownLockWait, 2*time.Second); err != nil {
+ return err
+ }
+ fmt.Fprintln(os.Stderr, "Daemon stopped.")
+ return nil
+ }
if !daemonAlive(health) {
label := "Daemon"
if profile != "" {
diff --git a/server/cmd/multica/cmd_daemon_port_test.go b/server/cmd/multica/cmd_daemon_port_test.go
index 09c7fb30f5..df108f109a 100644
--- a/server/cmd/multica/cmd_daemon_port_test.go
+++ b/server/cmd/multica/cmd_daemon_port_test.go
@@ -3,6 +3,7 @@ package main
import (
"bufio"
"context"
+ "encoding/json"
"fmt"
"net"
"net/http"
@@ -179,6 +180,30 @@ func TestDaemonProfileLockHolderProcess(t *testing.T) {
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if _, err := os.Stat(releasePath); err == nil {
+ if path := os.Getenv("MULTICA_TEST_DAEMON_STOP_RESULT"); path != "" {
+ outcome, _ := os.ReadFile(releasePath + ".outcome")
+ result := daemonShutdownResult{PID: os.Getpid(), CleanupConfirmed: true}
+ switch string(outcome) {
+ case "missing":
+ return
+ case "malformed":
+ if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return
+ case "unconfirmed":
+ result.CleanupConfirmed = false
+ case "stale":
+ result.PID++
+ }
+ data, err := json.Marshal(result)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
return
}
time.Sleep(50 * time.Millisecond)
diff --git a/server/cmd/multica/cmd_daemon_shutdown_result.go b/server/cmd/multica/cmd_daemon_shutdown_result.go
new file mode 100644
index 0000000000..2982c4893c
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_shutdown_result.go
@@ -0,0 +1,68 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+type daemonShutdownResult struct {
+ PID int `json:"pid"`
+ CleanupConfirmed bool `json:"cleanup_confirmed"`
+}
+
+func daemonShutdownResultPath(profile string) string {
+ return filepath.Join(daemonDirForProfile(profile), "daemon.shutdown.json")
+}
+
+// Written only while the daemon holds the profile lock, first as unconfirmed
+// at startup, then with the final cleanup outcome before releasing the lock.
+func writeDaemonShutdownResult(profile string, result daemonShutdownResult) error {
+ data, err := json.Marshal(result)
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(daemonShutdownResultPath(profile), data, 0o600)
+}
+
+func confirmDaemonCleanup(profile string, pid int) error {
+ result, err := readDaemonShutdownResult(profile)
+ if err != nil || pid <= 1 || result.PID != pid || !result.CleanupConfirmed {
+ // A daemon without a matching result (for example one started by an
+ // older CLI) leaves nothing behind after it exits. Persist the failure so
+ // a repeated stop cannot treat the now-idle profile as cleanly stopped.
+ // The next daemon start overwrites this record with its own PID.
+ if err != nil || result.PID != pid || result.CleanupConfirmed {
+ _ = writeDaemonShutdownResult(profile, daemonShutdownResult{PID: max(pid, 0)})
+ }
+ return fmt.Errorf("daemon exited but task cleanup could not be confirmed; background tasks may still be running")
+ }
+ return nil
+}
+
+func readDaemonShutdownResult(profile string) (daemonShutdownResult, error) {
+ var result daemonShutdownResult
+ data, err := os.ReadFile(daemonShutdownResultPath(profile))
+ if err == nil {
+ err = json.Unmarshal(data, &result)
+ }
+ return result, err
+}
+
+func daemonStopPID(profile string, health map[string]any) int {
+ if value, ok := health["pid"].(float64); ok && value > 1 && float64(int(value)) == value {
+ return int(value)
+ }
+ if data, err := os.ReadFile(daemonPIDPathForProfile(profile)); err == nil {
+ if pid, err := strconv.Atoi(strings.TrimSpace(string(data))); err == nil && pid > 1 {
+ return pid
+ }
+ }
+ if record, ok := readDaemonPortRecord(profile); ok {
+ return record.PID
+ }
+ return 0
+}
diff --git a/server/cmd/multica/cmd_daemon_stop.go b/server/cmd/multica/cmd_daemon_stop.go
new file mode 100644
index 0000000000..a6d14349ea
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_stop.go
@@ -0,0 +1,193 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// The daemon holds this lock through task cleanup and runtime deregistration,
+// after its health listener has closed. Release confirms daemon termination,
+// but only the shutdown result can confirm that task processes were cleaned up.
+func daemonStopComplete(profile string) (bool, error) {
+ path := filepath.Join(daemonDirForProfile(profile), "daemon.lock")
+ if _, err := os.Stat(path); os.IsNotExist(err) {
+ return true, nil
+ }
+ lock, acquired, err := tryLockDaemonProfile(path)
+ if lock != nil {
+ if closeErr := lock.Close(); err == nil {
+ err = closeErr
+ }
+ }
+ return acquired, err
+}
+
+func waitDaemonStop(profile string, timeout time.Duration) (bool, error) {
+ deadline := time.Now().Add(timeout)
+ for {
+ stopped, err := daemonStopComplete(profile)
+ if stopped || err != nil || !time.Now().Before(deadline) {
+ return stopped, err
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+func stopDaemonAndWait(profile string, port int, health map[string]any, grace, killWait time.Duration) error {
+ if daemonAlive(health) {
+ if err := daemonIdentityMismatch(health, profile, port); err != nil {
+ return err
+ }
+ if hostOS, _ := health["os"].(string); hostOS != "" && hostOS != runtime.GOOS {
+ return fmt.Errorf("daemon runs on %s; the native CLI cannot stop it", hostOS)
+ }
+ }
+ stopped, err := daemonStopComplete(profile)
+ if err != nil {
+ return err
+ }
+ if stopped && !daemonAlive(health) {
+ // No daemon was observed in this call. Preserve the idle no-op, but do
+ // not turn a previous failed cleanup into success on a repeated quit.
+ result, err := readDaemonShutdownResult(profile)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return confirmDaemonCleanup(profile, result.PID)
+ }
+ pidAtStop := daemonStopPID(profile, health)
+ // Keep the official cancellation path, including Agent process-group cleanup.
+ _ = requestDaemonShutdown(port)
+ if stopped {
+ return fmt.Errorf("shutdown requested but the daemon has no profile lock; cannot confirm completion")
+ }
+ // The endpoint may already be closed while a previous shutdown is cleaning
+ // up. A failed request must not shorten the lock holder's grace period.
+ if stopped, err = waitDaemonStop(profile, grace); err != nil || stopped {
+ if err != nil {
+ return err
+ }
+ return confirmDaemonCleanup(profile, pidAtStop)
+ }
+ // A fresh health identity is preferred. If health has closed or wedged,
+ // validate the profile PID file against the OS command before signalling it.
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ health = checkDaemonHealthOnPort(ctx, port)
+ var pid int
+ if daemonAlive(health) {
+ if err := daemonIdentityMismatch(health, profile, port); err != nil {
+ return err
+ }
+ if hostOS, _ := health["os"].(string); hostOS != "" && hostOS != runtime.GOOS {
+ return fmt.Errorf("refusing to terminate a daemon on %s", hostOS)
+ }
+ value, _ := health["pid"].(float64)
+ pid = int(value)
+ if float64(pid) != value {
+ return fmt.Errorf("invalid daemon PID")
+ }
+ } else {
+ data, err := os.ReadFile(daemonPIDPathForProfile(profile))
+ if os.IsNotExist(err) {
+ // An earlier plain stop can remove daemon.pid when health closes,
+ // while the daemon still owns its port record and shutdown lock.
+ if record, ok := readDaemonPortRecord(profile); ok {
+ data, err = []byte(strconv.Itoa(record.PID)), nil
+ }
+ }
+ if err != nil {
+ if stopped, probeErr := daemonStopComplete(profile); probeErr == nil && stopped {
+ return confirmDaemonCleanup(profile, pidAtStop)
+ }
+ return fmt.Errorf("read daemon PID before forced stop: %w", err)
+ }
+ pid, err = strconv.Atoi(strings.TrimSpace(string(data)))
+ if err != nil || pid <= 1 || pid == os.Getpid() {
+ return fmt.Errorf("invalid daemon PID file")
+ }
+ if err := verifyDaemonStopProcess(pid, profile); err != nil {
+ if stopped, probeErr := daemonStopComplete(profile); probeErr == nil && stopped {
+ return confirmDaemonCleanup(profile, pidAtStop)
+ }
+ return err
+ }
+ }
+ if pid <= 1 || pid == os.Getpid() {
+ return fmt.Errorf("invalid daemon PID")
+ }
+ if stopped, err = daemonStopComplete(profile); err != nil || stopped {
+ if err != nil {
+ return err
+ }
+ return confirmDaemonCleanup(profile, pidAtStop)
+ }
+ process, err := os.FindProcess(pid)
+ if err != nil {
+ return err
+ }
+ defer process.Release()
+ if err := process.Kill(); err != nil {
+ if stopped, probeErr := daemonStopComplete(profile); probeErr == nil && stopped {
+ return confirmDaemonCleanup(profile, pidAtStop)
+ }
+ return fmt.Errorf("force stop daemon: %w", err)
+ }
+ if stopped, err = waitDaemonStop(profile, killWait); err != nil {
+ return err
+ }
+ if stopped {
+ // Killing the daemon bypasses its cancellation handlers. In particular,
+ // Unix Agent processes own independent process groups and can survive.
+ // Even an accepted shutdown request does not prove cleanup completed.
+ return fmt.Errorf("daemon was forcibly terminated; task cleanup could not be confirmed and background tasks may still be running")
+ }
+ return fmt.Errorf("daemon profile %q is still locked after forced termination", profile)
+}
+
+func verifyDaemonStopProcess(pid int, profile string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ var name, command string
+ if runtime.GOOS == "windows" {
+ script := fmt.Sprintf("Get-CimInstance Win32_Process -Filter 'ProcessId = %d' | Select-Object Name,CommandLine | ConvertTo-Json -Compress", pid)
+ data, err := exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script).Output()
+ if err != nil {
+ return err
+ }
+ var record struct{ Name, CommandLine string }
+ if err := json.Unmarshal(data, &record); err != nil {
+ return err
+ }
+ name, command = record.Name, record.CommandLine
+ } else {
+ data, err := exec.CommandContext(ctx, "ps", "-p", strconv.Itoa(pid), "-o", "comm=").Output()
+ if err != nil {
+ return err
+ }
+ name = strings.TrimSpace(string(data))
+ data, err = exec.CommandContext(ctx, "ps", "-p", strconv.Itoa(pid), "-o", "args=").Output()
+ if err != nil {
+ return err
+ }
+ command = string(data)
+ }
+ profileMatches := !strings.Contains(command, "--profile") && profile == ""
+ if profile != "" {
+ profileMatches = regexp.MustCompile(`--profile(?:=|\s+)"?` + regexp.QuoteMeta(profile) + `"?(?:\s|$)`).MatchString(command)
+ }
+ base := filepath.Base(name)
+ if (base != "multica" && base != "multica.exe") || !regexp.MustCompile(`\bdaemon\s+start\b`).MatchString(command) || !profileMatches {
+ return fmt.Errorf("PID %d does not identify the daemon for profile %q", pid, profile)
+ }
+ return nil
+}
diff --git a/server/cmd/multica/cmd_daemon_stop_completion_unix_test.go b/server/cmd/multica/cmd_daemon_stop_completion_unix_test.go
new file mode 100644
index 0000000000..d9fcf219bc
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_stop_completion_unix_test.go
@@ -0,0 +1,91 @@
+//go:build !windows
+
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// Model a daemon that releases its profile lock without cleaning up an
+// independent run process.
+func TestDaemonStopUnconfirmedExitHelper(t *testing.T) {
+ if os.Getenv("MULTICA_TEST_UNCONFIRMED_EXIT") != "1" {
+ t.Skip("subprocess only")
+ }
+ lock, acquired, err := tryLockDaemonProfile(os.Getenv("MULTICA_TEST_UNCONFIRMED_LOCK"))
+ if err != nil || !acquired {
+ t.Fatalf("lock: %v, acquired=%v", err, acquired)
+ }
+ defer lock.Close()
+ task := exec.Command("/bin/sleep", "30")
+ task.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ if err := task.Start(); err != nil {
+ t.Fatal(err)
+ }
+ fmt.Println(task.Process.Pid)
+ defer task.Process.Release()
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ if _, err := os.Stat(os.Getenv("MULTICA_TEST_UNCONFIRMED_RELEASE")); err == nil {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ _ = task.Process.Kill()
+ t.Fatal("shutdown request never arrived")
+}
+
+func TestDaemonStopForceRejectsGracefulExitWithSurvivingRun(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-unconfirmed-cleanup"
+ mkProfiles(t, profile)
+ release := filepath.Join(t.TempDir(), "release")
+ child := exec.Command(os.Args[0], "-test.run=^TestDaemonStopUnconfirmedExitHelper$")
+ child.Env = append(os.Environ(),
+ "MULTICA_TEST_UNCONFIRMED_EXIT=1",
+ "MULTICA_TEST_UNCONFIRMED_LOCK="+filepath.Join(daemonDirForProfile(profile), "daemon.lock"),
+ "MULTICA_TEST_UNCONFIRMED_RELEASE="+release)
+ stdout, err := child.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := child.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = child.Process.Kill(); _ = child.Wait() })
+ line, err := bufio.NewReader(stdout).ReadString('\n')
+ if err != nil {
+ t.Fatal(err)
+ }
+ taskPID, err := strconv.Atoi(strings.TrimSpace(line))
+ if err != nil || taskPID <= 1 {
+ t.Fatalf("invalid test task PID: %q (%v)", line, err)
+ }
+ t.Cleanup(func() { _ = syscall.Kill(taskPID, syscall.SIGKILL) })
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(child.Process.Pid)}
+ _, port := stopTestServer(t, health, func() { _ = os.WriteFile(release, nil, 0o600) })
+ stopErr := stopDaemonAndWait(profile, port, health, time.Second, time.Second)
+ if err := child.Wait(); err != nil {
+ t.Fatalf("test daemon did not exit normally: %v", err)
+ }
+ if err := syscall.Kill(taskPID, 0); err != nil {
+ t.Fatalf("test run did not survive: %v", err)
+ }
+ if stopErr == nil {
+ t.Fatal("stop returned success after daemon exited normally, but its independent run process is still alive")
+ }
+ // Cancelling the failure dialog and quitting again must not erase the
+ // uncertainty while the same independent run process is still alive.
+ if retryErr := stopDaemonAndWait(profile, 0, nil, 0, 0); retryErr == nil {
+ t.Fatal("repeated stop returned success without cleanup confirmation while the independent run process is still alive")
+ }
+}
diff --git a/server/cmd/multica/cmd_daemon_stop_test.go b/server/cmd/multica/cmd_daemon_stop_test.go
new file mode 100644
index 0000000000..8084366de1
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_stop_test.go
@@ -0,0 +1,291 @@
+package main
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// Reuse the existing bounded lock-holder test process; never run an Agent CLI.
+func startStopLockHolder(t *testing.T, profile string, daemonName bool) (*exec.Cmd, string) {
+ t.Helper()
+ executable := os.Args[0]
+ if daemonName {
+ name := "multica"
+ if runtime.GOOS == "windows" {
+ name += ".exe"
+ }
+ executable = filepath.Join(t.TempDir(), name)
+ in, err := os.Open(os.Args[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer in.Close()
+ out, err := os.OpenFile(executable, os.O_CREATE|os.O_WRONLY, 0o700)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = io.Copy(out, in)
+ out.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ release := filepath.Join(t.TempDir(), "release")
+ child := exec.Command(executable, "-test.run=^TestDaemonProfileLockHolderProcess$", "daemon", "start", "--foreground", "--profile", profile)
+ child.Env = append(os.Environ(),
+ "MULTICA_TEST_DAEMON_LOCK_PATH="+filepath.Join(daemonDirForProfile(profile), "daemon.lock"),
+ "MULTICA_TEST_DAEMON_LOCK_RELEASE="+release,
+ "MULTICA_TEST_DAEMON_STOP_RESULT="+daemonShutdownResultPath(profile))
+ stdout, err := child.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := child.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = child.Process.Kill(); _ = child.Wait() })
+ if line, err := bufio.NewReader(stdout).ReadString('\n'); err != nil || line != "locked\n" {
+ t.Fatalf("start lock holder: %q, %v", line, err)
+ }
+ if err := os.WriteFile(daemonPIDPathForProfile(profile), []byte(strconv.Itoa(child.Process.Pid)), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return child, release
+}
+
+func stopTestServer(t *testing.T, health map[string]any, shutdown func()) (*httptest.Server, int) {
+ t.Helper()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/shutdown" {
+ shutdown()
+ fmt.Fprint(w, "{}")
+ return
+ }
+ _ = json.NewEncoder(w).Encode(health)
+ }))
+ t.Cleanup(server.Close)
+ return server, server.Listener.Addr().(*net.TCPAddr).Port
+}
+
+func TestDaemonStopForceWaitsForCleanupAfterHealthCloses(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-cleanup-test"
+ mkProfiles(t, profile)
+ child, release := startStopLockHolder(t, profile, false)
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(child.Process.Pid)}
+ var shutdowns atomic.Int32
+ _, port := stopTestServer(t, nil, func() {
+ shutdowns.Add(1)
+ go func() { time.Sleep(200 * time.Millisecond); _ = os.WriteFile(release, nil, 0o600) }()
+ })
+ start := time.Now()
+ if err := stopDaemonAndWait(profile, port, health, time.Second, time.Second); err != nil {
+ t.Fatal(err)
+ }
+ if time.Since(start) < 150*time.Millisecond || shutdowns.Load() != 1 {
+ t.Fatal("stop returned before cleanup released the profile lock")
+ }
+ if err := child.Wait(); err != nil {
+ t.Fatalf("graceful daemon was killed: %v", err)
+ }
+}
+
+func TestDaemonStopForceWaitsForExistingCleanupWhenShutdownFails(t *testing.T) {
+ for _, closed := range []bool{false, true} {
+ t.Run(fmt.Sprintf("endpoint_closed_%t", closed), func(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-existing-cleanup-test"
+ mkProfiles(t, profile)
+ child, release := startStopLockHolder(t, profile, true)
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(child.Process.Pid)}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/shutdown" {
+ http.Error(w, "already shutting down", http.StatusServiceUnavailable)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(health)
+ }))
+ t.Cleanup(server.Close)
+ port := server.Listener.Addr().(*net.TCPAddr).Port
+ if closed {
+ server.Close()
+ health = nil
+ }
+ go func() { time.Sleep(200 * time.Millisecond); _ = os.WriteFile(release, nil, 0o600) }()
+ if err := stopDaemonAndWait(profile, port, health, time.Second, time.Second); err != nil {
+ t.Fatal(err)
+ }
+ if err := child.Wait(); err != nil {
+ t.Fatalf("daemon was killed during its cleanup grace period: %v", err)
+ }
+ })
+ }
+}
+
+func TestDaemonStopForceKillsOnlyAfterGraceExpires(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-force-test"
+ mkProfiles(t, profile)
+ child, _ := startStopLockHolder(t, profile, false)
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(child.Process.Pid)}
+ _, port := stopTestServer(t, health, func() {})
+ start := time.Now()
+ if err := stopDaemonAndWait(profile, port, health, 50*time.Millisecond, time.Second); err == nil || !strings.Contains(err.Error(), "task cleanup could not be confirmed") {
+ t.Fatalf("forced termination must report uncertain task cleanup: %v", err)
+ }
+ if time.Since(start) < 50*time.Millisecond {
+ t.Fatal("daemon was killed before the grace period expired")
+ }
+ if err := child.Wait(); err == nil {
+ t.Fatal("unresponsive daemon was not force stopped")
+ }
+}
+
+func TestDaemonStopForceHandlesUnresponsiveHealthWithVerifiedProfilePID(t *testing.T) {
+ for _, portRecord := range []bool{false, true} {
+ t.Run(fmt.Sprintf("port_record_%t", portRecord), func(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-unresponsive-test"
+ mkProfiles(t, profile)
+ child, _ := startStopLockHolder(t, profile, true)
+ _, port := stopTestServer(t, nil, func() {})
+ if portRecord {
+ if err := publishDaemonPort(profile, daemonPortRecord{Port: port, PID: child.Process.Pid}); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(daemonPIDPathForProfile(profile)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := stopDaemonAndWait(profile, port, nil, 0, time.Second); err == nil || !strings.Contains(err.Error(), "task cleanup could not be confirmed") {
+ t.Fatalf("forced termination must report uncertain task cleanup: %v", err)
+ }
+ if err := child.Wait(); err == nil {
+ t.Fatal("unresponsive verified daemon was not force stopped")
+ }
+ })
+ }
+}
+
+func TestDaemonStopForceFlagUsesTheCLIStopPath(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-command-test"
+ mkProfiles(t, profile)
+ child, release := startStopLockHolder(t, profile, false)
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(child.Process.Pid)}
+ _, port := stopTestServer(t, health, func() { _ = os.WriteFile(release, nil, 0o600) })
+ if err := publishDaemonPort(profile, daemonPortRecord{Port: port, PID: child.Process.Pid}); err != nil {
+ t.Fatal(err)
+ }
+ cmd := daemonStatusCmdFor(t, profile, "")
+ cmd.Flags().Bool("force", true, "")
+ if err := runDaemonStop(cmd, nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := child.Wait(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDaemonStopForceRequiresMatchingCleanupResult(t *testing.T) {
+ for _, outcome := range []string{"confirmed", "unconfirmed", "missing", "malformed", "stale"} {
+ t.Run(outcome, func(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-result-test"
+ mkProfiles(t, profile)
+ child, release := startStopLockHolder(t, profile, false)
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(child.Process.Pid)}
+ _, port := stopTestServer(t, health, func() { _ = os.WriteFile(release, nil, 0o600) })
+ // The child writes these variants before releasing its lock.
+ if err := os.WriteFile(release+".outcome", []byte(outcome), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ err := stopDaemonAndWait(profile, port, health, time.Second, time.Second)
+ if (err == nil) != (outcome == "confirmed") {
+ t.Fatalf("cleanup outcome %s: %v", outcome, err)
+ }
+ if err := child.Wait(); err != nil {
+ t.Fatalf("graceful daemon was killed: %v", err)
+ }
+ // Cancelling the failure dialog and quitting again must keep the
+ // failure, even when the daemon left no usable result behind.
+ if err := stopDaemonAndWait(profile, 0, nil, 0, 0); (err == nil) != (outcome == "confirmed") {
+ t.Fatalf("repeated stop after cleanup outcome %s: %v", outcome, err)
+ }
+ })
+ }
+}
+
+func TestDaemonStopForceKeepsFailedCleanupOnRepeatedStop(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-repeated-test"
+ mkProfiles(t, profile)
+ if err := stopDaemonAndWait(profile, 0, nil, 0, 0); err != nil {
+ t.Fatalf("idle stop: %v", err)
+ }
+ for _, confirmed := range []bool{false, true} {
+ if err := writeDaemonShutdownResult(profile, daemonShutdownResult{PID: 12345, CleanupConfirmed: confirmed}); err != nil {
+ t.Fatal(err)
+ }
+ if err := stopDaemonAndWait(profile, 0, nil, 0, 0); (err == nil) != confirmed {
+ t.Fatalf("previous cleanup confirmed=%t: %v", confirmed, err)
+ }
+ }
+}
+
+func TestDaemonStopForceRefusesUnverifiedPIDAndForeignProfile(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-identity-test"
+ mkProfiles(t, profile)
+ child, _ := startStopLockHolder(t, profile, false)
+ var shutdowns atomic.Int32
+ _, port := stopTestServer(t, nil, func() { shutdowns.Add(1) })
+ foreign := map[string]any{"status": "running", "profile": "other", "pid": float64(child.Process.Pid)}
+ if err := stopDaemonAndWait(profile, port, foreign, 0, time.Second); err == nil || shutdowns.Load() != 0 {
+ t.Fatalf("foreign profile was acted on: %v", err)
+ }
+ foreignOS := "windows"
+ if runtime.GOOS == "windows" {
+ foreignOS = "linux"
+ }
+ if err := stopDaemonAndWait(profile, port, map[string]any{"status": "running", "profile": profile, "os": foreignOS}, 0, time.Second); err == nil || shutdowns.Load() != 0 {
+ t.Fatalf("foreign OS was acted on: %v", err)
+ }
+ if err := stopDaemonAndWait(profile, port, nil, 0, time.Second); err == nil || !strings.Contains(err.Error(), "does not identify") {
+ t.Fatalf("unrelated test process was accepted as a daemon: %v", err)
+ }
+ if stopped, _ := daemonStopComplete(profile); stopped {
+ t.Fatal("unverified process was terminated")
+ }
+}
+
+func TestDaemonStopForceReportsFailureIfProfileRemainsLocked(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-still-locked-test"
+ mkProfiles(t, profile)
+ lock, err := acquireDaemonProfileLock(profile, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lock.Close()
+ pid := startBlockingChild(t)
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(pid)}
+ _, port := stopTestServer(t, health, func() {})
+ if err := stopDaemonAndWait(profile, port, health, 0, 50*time.Millisecond); err == nil || !strings.Contains(err.Error(), "still locked") {
+ t.Fatalf("incomplete stop was reported as success: %v", err)
+ }
+}
diff --git a/server/cmd/multica/cmd_daemon_stop_unix_test.go b/server/cmd/multica/cmd_daemon_stop_unix_test.go
new file mode 100644
index 0000000000..350e442c2d
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_stop_unix_test.go
@@ -0,0 +1,99 @@
+//go:build !windows
+
+package main
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+func TestDaemonStopWithTaskProcess(t *testing.T) {
+ switch os.Getenv("MULTICA_TEST_STOP_PROCESS") {
+ case "task":
+ fmt.Println("ready")
+ time.Sleep(20 * time.Second)
+ return
+ case "daemon":
+ lock, acquired, err := tryLockDaemonProfile(os.Getenv("MULTICA_TEST_STOP_LOCK"))
+ if err != nil || !acquired {
+ t.Fatalf("acquire profile lock: %v", err)
+ }
+ defer lock.Close()
+ task := exec.Command(os.Args[0], "-test.run=^TestDaemonStopWithTaskProcess$")
+ task.Env = append(os.Environ(), "MULTICA_TEST_STOP_PROCESS=task")
+ task.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ stdout, err := task.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := task.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = task.Process.Kill(); _ = task.Wait() }()
+ if line, err := bufio.NewReader(stdout).ReadString('\n'); err != nil || line != "ready\n" {
+ t.Fatalf("task readiness: %q, %v", line, err)
+ }
+ fmt.Println(task.Process.Pid)
+ time.Sleep(20 * time.Second)
+ return
+ }
+ t.Skip("subprocess helper")
+}
+
+func TestDaemonStopForceDoesNotReportOrphanedTaskAsStopped(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ const profile = "stop-orphan-test"
+ mkProfiles(t, profile)
+ daemon := exec.Command(os.Args[0], "-test.run=^TestDaemonStopWithTaskProcess$")
+ daemon.Env = append(os.Environ(), "MULTICA_TEST_STOP_PROCESS=daemon",
+ "MULTICA_TEST_STOP_LOCK="+filepath.Join(daemonDirForProfile(profile), "daemon.lock"))
+ stdout, err := daemon.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := daemon.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = daemon.Process.Kill(); _ = daemon.Wait() })
+ line, err := bufio.NewReader(stdout).ReadString('\n')
+ if err != nil {
+ t.Fatal(err)
+ }
+ taskPID, err := strconv.Atoi(strings.TrimSpace(line))
+ if err != nil || taskPID <= 1 {
+ t.Fatalf("task PID: %q, %v", line, err)
+ }
+ t.Cleanup(func() { _ = syscall.Kill(-taskPID, syscall.SIGKILL) })
+ health := map[string]any{"status": "running", "profile": profile, "pid": float64(daemon.Process.Pid)}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/shutdown" {
+ http.Error(w, "shutdown unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(health)
+ }))
+ defer server.Close()
+ port := server.Listener.Addr().(*net.TCPAddr).Port
+ err = stopDaemonAndWait(profile, port, health, 0, time.Second)
+ if err == nil || !strings.Contains(err.Error(), "task cleanup could not be confirmed") {
+ t.Fatalf("forced termination must report uncertain task cleanup: %v", err)
+ }
+ if err := syscall.Kill(taskPID, 0); err != nil {
+ t.Fatalf("expected independent task to survive daemon termination: %v", err)
+ }
+ if stopped, err := daemonStopComplete(profile); err != nil || !stopped {
+ t.Fatalf("daemon lock should be released: stopped=%v, err=%v", stopped, err)
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index e90e08b279..a98e2350a4 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -654,6 +654,9 @@ type Daemon struct {
// It deliberately includes preparation and local-directory waiters because
// restart/update barriers must not kill any claimed task.
activeTasks atomic.Int64
+ // Sticky for this process: a finished task can leave independent processes
+ // behind even after activeTasks reaches zero.
+ cleanupUnconfirmed atomic.Bool
// runningTasks counts live provider execution sessions, beginning only after
// backend.Execute returns. It can briefly lag the server-side running state,
// which starts during preparation before provider launch. resourceWaitTasks
@@ -5316,13 +5319,7 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) er
// poller between ClaimTasksWSFirst and taskWG.Add(1) cannot race
// taskWG.Wait at a zero counter.
<-pollerDone
- waitDone := make(chan struct{})
- go func() { taskWG.Wait(); close(waitDone) }()
- select {
- case <-waitDone:
- case <-time.After(30 * time.Second):
- d.logger.Warn("timed out waiting for in-flight tasks")
- }
+ d.waitForTaskCleanup(&taskWG, 30*time.Second)
return ctx.Err()
case <-runtimeSetCh:
// The batch poller re-derives allRuntimeIDs() each cycle; nudge it to
@@ -9502,7 +9499,12 @@ func freshSessionMayHelp(errText string) bool {
// messages and is owned by the caller so a same-task retry continues the
// sequence instead of restarting at 1 — the server orders the transcript by
// seq alone, and duplicate seqs would interleave the two attempts' rows.
-func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prompt string, opts agent.ExecOptions, taskLog *slog.Logger, taskID, codexHome string, msgSeq *atomic.Int32) (agent.Result, int32, error) {
+func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prompt string, opts agent.ExecOptions, taskLog *slog.Logger, taskID, codexHome string, msgSeq *atomic.Int32) (finalResult agent.Result, finalTools int32, finalErr error) {
+ defer func() {
+ if finalResult.Status == "cleanup_unconfirmed" {
+ d.cleanupUnconfirmed.Store(true)
+ }
+ }()
phaseRecorder := taskPhaseRecorderFromContext(ctx)
// Wrap the caller's ctx so the idle watchdog (below) can interrupt both
// the agent subprocess (via the ctx passed to backend.Execute) AND the
diff --git a/server/internal/daemon/pi_cleanup_test.go b/server/internal/daemon/pi_cleanup_test.go
index 90fb91981f..36e6e4a8a6 100644
--- a/server/internal/daemon/pi_cleanup_test.go
+++ b/server/internal/daemon/pi_cleanup_test.go
@@ -3,6 +3,7 @@ package daemon
import (
"context"
"log/slog"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -42,6 +43,13 @@ func TestPiCleanupUnconfirmedOutranksCancellation(t *testing.T) {
if err != nil || result.Status != "cleanup_unconfirmed" {
t.Fatalf("manual=%v omitted=%v result=%+v err=%v", manual, omitted, result, err)
}
+ // A drained task may still leave processes behind; even a later
+ // empty shutdown drain must retain that uncertainty.
+ var tasks sync.WaitGroup
+ d.waitForTaskCleanup(&tasks, time.Second)
+ if d.ShutdownCleanupConfirmed() {
+ t.Fatal("shutdown forgot the provider's unconfirmed cleanup")
+ }
if shouldRetryWithFreshSession(result, "existing-session", 0, "pi") {
t.Fatal("unconfirmed cleanup allowed an in-turn retry")
}
diff --git a/server/internal/daemon/shutdown.go b/server/internal/daemon/shutdown.go
new file mode 100644
index 0000000000..c43ca90259
--- /dev/null
+++ b/server/internal/daemon/shutdown.go
@@ -0,0 +1,25 @@
+package daemon
+
+import (
+ "sync"
+ "time"
+)
+
+// ShutdownCleanupConfirmed is meaningful after Run returns. Daemon exit alone
+// does not prove that the providers' independent process groups have exited.
+func (d *Daemon) ShutdownCleanupConfirmed() bool {
+ return !d.cleanupUnconfirmed.Load()
+}
+
+func (d *Daemon) waitForTaskCleanup(tasks *sync.WaitGroup, timeout time.Duration) {
+ done := make(chan struct{})
+ go func() { tasks.Wait(); close(done) }()
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
+ select {
+ case <-done:
+ case <-timer.C:
+ d.cleanupUnconfirmed.Store(true)
+ d.logger.Warn("timed out waiting for in-flight tasks")
+ }
+}
diff --git a/server/internal/daemon/shutdown_test.go b/server/internal/daemon/shutdown_test.go
new file mode 100644
index 0000000000..0443510803
--- /dev/null
+++ b/server/internal/daemon/shutdown_test.go
@@ -0,0 +1,26 @@
+package daemon
+
+import (
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestShutdownCleanupWait(t *testing.T) {
+ for _, finishes := range []bool{true, false} {
+ t.Run(map[bool]string{true: "drained", false: "timed_out"}[finishes], func(t *testing.T) {
+ d := newTestDaemon(t)
+ var tasks sync.WaitGroup
+ tasks.Add(1)
+ if finishes {
+ tasks.Done()
+ } else {
+ defer tasks.Done()
+ }
+ d.waitForTaskCleanup(&tasks, 50*time.Millisecond)
+ if d.ShutdownCleanupConfirmed() != finishes {
+ t.Fatalf("cleanup confirmed=%t after finishes=%t", d.ShutdownCleanupConfirmed(), finishes)
+ }
+ })
+ }
+}